@multiplayer-app/ai-agent-react 0.1.0-beta.81 → 0.1.0-beta.84

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.
@@ -8290,7 +8290,7 @@
8290
8290
  */var E6e=["input:not([inert])","select:not([inert])","textarea:not([inert])","a[href]:not([inert])","button:not([inert])","[tabindex]:not(slot):not([inert])","audio[controls]:not([inert])","video[controls]:not([inert])",'[contenteditable]:not([contenteditable="false"]):not([inert])',"details>summary:first-of-type:not([inert])","details:not([inert])"],Xu=E6e.join(","),M5=typeof Element>"u",pa=M5?function(){}:Element.prototype.matches||Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector,Oi=!M5&&Element.prototype.getRootNode?function(e){var t;return e==null||(t=e.getRootNode)===null||t===void 0?void 0:t.call(e)}:function(e){return e?.ownerDocument},ha=function(t,n){var r;n===void 0&&(n=!0);var a=t==null||(r=t.getAttribute)===null||r===void 0?void 0:r.call(t,"inert"),i=a===""||a==="true",o=i||n&&t&&ha(t.parentNode);return o},M6e=function(t){var n,r=t==null||(n=t.getAttribute)===null||n===void 0?void 0:n.call(t,"contenteditable");return r===""||r==="true"},S6e=function(t,n,r){if(ha(t))return[];var a=Array.prototype.slice.apply(t.querySelectorAll(Xu));return n&&pa.call(t,Xu)&&a.unshift(t),a=a.filter(r),a},Qu=function(t,n,r){for(var a=[],i=Array.from(t);i.length;){var o=i.shift();if(!ha(o,!1))if(o.tagName==="SLOT"){var s=o.assignedElements(),l=s.length?s:o.children,u=Qu(l,!0,r);r.flatten?a.push.apply(a,u):a.push({scopeParent:o,candidates:u})}else{var d=pa.call(o,Xu);d&&r.filter(o)&&(n||!t.includes(o))&&a.push(o);var p=o.shadowRoot||typeof r.getShadowRoot=="function"&&r.getShadowRoot(o),m=!ha(p,!1)&&(!r.shadowRootFilter||r.shadowRootFilter(o));if(p&&m){var h=Qu(p===!0?o.children:p.children,!0,r);r.flatten?a.push.apply(a,h):a.push({scopeParent:o,candidates:h})}else i.unshift.apply(i,o.children)}}return a},S5=function(t){return!isNaN(parseInt(t.getAttribute("tabindex"),10))},N5=function(t){if(!t)throw new Error("No node provided");return t.tabIndex<0&&(/^(AUDIO|VIDEO|DETAILS)$/.test(t.tagName)||M6e(t))&&!S5(t)?0:t.tabIndex},N6e=function(t,n){var r=N5(t);return r<0&&n&&!S5(t)?0:r},A6e=function(t,n){return t.tabIndex===n.tabIndex?t.documentOrder-n.documentOrder:t.tabIndex-n.tabIndex},A5=function(t){return t.tagName==="INPUT"},T6e=function(t){return A5(t)&&t.type==="hidden"},C6e=function(t){var n=t.tagName==="DETAILS"&&Array.prototype.slice.apply(t.children).some(function(r){return r.tagName==="SUMMARY"});return n},R6e=function(t,n){for(var r=0;r<t.length;r++)if(t[r].checked&&t[r].form===n)return t[r]},I6e=function(t){if(!t.name)return!0;var n=t.form||Oi(t),r=function(s){return n.querySelectorAll('input[type="radio"][name="'+s+'"]')},a;if(typeof window<"u"&&typeof window.CSS<"u"&&typeof window.CSS.escape=="function")a=r(window.CSS.escape(t.name));else try{a=r(t.name)}catch(o){return console.error("Looks like you have a radio button with a name attribute containing invalid CSS selector characters and need the CSS.escape polyfill: %s",o.message),!1}var i=R6e(a,t.form);return!i||i===t},O6e=function(t){return A5(t)&&t.type==="radio"},L6e=function(t){return O6e(t)&&!I6e(t)},D6e=function(t){var n,r=t&&Oi(t),a=(n=r)===null||n===void 0?void 0:n.host,i=!1;if(r&&r!==t){var o,s,l;for(i=!!((o=a)!==null&&o!==void 0&&(s=o.ownerDocument)!==null&&s!==void 0&&s.contains(a)||t!=null&&(l=t.ownerDocument)!==null&&l!==void 0&&l.contains(t));!i&&a;){var u,d,p;r=Oi(a),a=(u=r)===null||u===void 0?void 0:u.host,i=!!((d=a)!==null&&d!==void 0&&(p=d.ownerDocument)!==null&&p!==void 0&&p.contains(a))}}return i},zh=function(t){var n=t.getBoundingClientRect(),r=n.width,a=n.height;return r===0&&a===0},z6e=function(t,n){var r=n.displayCheck,a=n.getShadowRoot;if(r==="full-native"&&"checkVisibility"in t){var i=t.checkVisibility({checkOpacity:!1,opacityProperty:!1,contentVisibilityAuto:!0,visibilityProperty:!0,checkVisibilityCSS:!0});return!i}if(getComputedStyle(t).visibility==="hidden")return!0;var o=pa.call(t,"details>summary:first-of-type"),s=o?t.parentElement:t;if(pa.call(s,"details:not([open]) *"))return!0;if(!r||r==="full"||r==="full-native"||r==="legacy-full"){if(typeof a=="function"){for(var l=t;t;){var u=t.parentElement,d=Oi(t);if(u&&!u.shadowRoot&&a(u)===!0)return zh(t);t.assignedSlot?t=t.assignedSlot:!u&&d!==t.ownerDocument?t=d.host:t=u}t=l}if(D6e(t))return!t.getClientRects().length;if(r!=="legacy-full")return!0}else if(r==="non-zero-area")return zh(t);return!1},$6e=function(t){if(/^(INPUT|BUTTON|SELECT|TEXTAREA)$/.test(t.tagName))for(var n=t.parentElement;n;){if(n.tagName==="FIELDSET"&&n.disabled){for(var r=0;r<n.children.length;r++){var a=n.children.item(r);if(a.tagName==="LEGEND")return pa.call(n,"fieldset[disabled] *")?!0:!a.contains(t)}return!0}n=n.parentElement}return!1},F6e=function(t,n){return!(n.disabled||ha(n)||T6e(n)||z6e(n,t)||C6e(n)||$6e(n))},$h=function(t,n){return!(L6e(n)||N5(n)<0||!F6e(t,n))},P6e=function(t){var n=parseInt(t.getAttribute("tabindex"),10);return!!(isNaN(n)||n>=0)},T5=function(t){var n=[],r=[];return t.forEach(function(a,i){var o=!!a.scopeParent,s=o?a.scopeParent:a,l=N6e(s,o),u=o?T5(a.candidates):s;l===0?o?n.push.apply(n,u):n.push(s):r.push({documentOrder:i,tabIndex:l,item:a,isScope:o,content:u})}),r.sort(A6e).reduce(function(a,i){return i.isScope?a.push.apply(a,i.content):a.push(i.content),a},[]).concat(n)},C5=function(t,n){n=n||{};var r;return n.getShadowRoot?r=Qu([t],n.includeContainer,{filter:$h.bind(null,n),flatten:!1,getShadowRoot:n.getShadowRoot,shadowRootFilter:P6e}):r=S6e(t,n.includeContainer,$h.bind(null,n)),T5(r)};function R5(){const e=navigator.userAgentData;return e!=null&&e.platform?e.platform:navigator.platform}function I5(){const e=navigator.userAgentData;return e&&Array.isArray(e.brands)?e.brands.map(t=>{let{brand:n,version:r}=t;return n+"/"+r}).join(" "):navigator.userAgent}function O5(){return/apple/i.test(navigator.vendor)}function Ju(){const e=/android/i;return e.test(R5())||e.test(I5())}function q6e(){return R5().toLowerCase().startsWith("mac")&&!navigator.maxTouchPoints}function L5(){return I5().includes("jsdom/")}const Fh="data-floating-ui-focusable",B6e="input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])",Fo="ArrowLeft",Po="ArrowRight",U6e="ArrowUp",H6e="ArrowDown";function ma(e){let t=e.activeElement;for(;((n=t)==null||(n=n.shadowRoot)==null?void 0:n.activeElement)!=null;){var n;t=t.shadowRoot.activeElement}return t}function fr(e,t){if(!e||!t)return!1;const n=t.getRootNode==null?void 0:t.getRootNode();if(e.contains(t))return!0;if(n&&Ku(n)){let r=t;for(;r;){if(e===r)return!0;r=r.parentNode||r.host}}return!1}function Ar(e){return"composedPath"in e?e.composedPath()[0]:e.target}function qo(e,t){if(t==null)return!1;if("composedPath"in e)return e.composedPath().includes(t);const n=e;return n.target!=null&&t.contains(n.target)}function j6e(e){return e.matches("html,body")}function dn(e){return e?.ownerDocument||document}function Ud(e){return xt(e)&&e.matches(B6e)}function V6e(e){return e?e.getAttribute("role")==="combobox"&&Ud(e):!1}function G6e(e){if(!e||L5())return!0;try{return e.matches(":focus-visible")}catch{return!0}}function D5(e){return e?e.hasAttribute(Fh)?e:e.querySelector("["+Fh+"]")||e:null}function oa(e,t,n){return n===void 0&&(n=!0),e.filter(a=>{var i;return a.parentId===t&&(!n||((i=a.context)==null?void 0:i.open))}).flatMap(a=>[a,...oa(e,a.id,n)])}function W6e(e,t){let n,r=-1;function a(i,o){o>r&&(n=i,r=o),oa(e,i).forEach(l=>{a(l.id,o+1)})}return a(t,0),e.find(i=>i.id===n)}function Xt(e){e.preventDefault(),e.stopPropagation()}function K6e(e){return"nativeEvent"in e}function Y6e(e){return e.mozInputSource===0&&e.isTrusted?!0:Ju()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function Z6e(e){return L5()?!1:!Ju()&&e.width===0&&e.height===0||Ju()&&e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"||e.width<1&&e.height<1&&e.pressure===0&&e.detail===0&&e.pointerType==="touch"}function fa(e,t){const n=["mouse","pen"];return t||n.push("",void 0),n.includes(e)}var X6e=typeof document<"u",Q6e=function(){},gt=X6e?V.useLayoutEffect:Q6e;const J6e={...te};function Rn(e){const t=te.useRef(e);return gt(()=>{t.current=e}),t}const e8e=J6e.useInsertionEffect,t8e=e8e||(e=>e());function Vt(e){const t=te.useRef(()=>{if(process.env.NODE_ENV!=="production")throw new Error("Cannot call an event handler while rendering.")});return t8e(()=>{t.current=e}),te.useCallback(function(){for(var n=arguments.length,r=new Array(n),a=0;a<n;a++)r[a]=arguments[a];return t.current==null?void 0:t.current(...r)},[])}function Ua(e,t,n){return Math.floor(e/t)!==n}function sa(e,t){return t<0||t>=e.current.length}function Bo(e,t){return kt(e,{disabledIndices:t})}function Ph(e,t){return kt(e,{decrement:!0,startingIndex:e.current.length,disabledIndices:t})}function kt(e,t){let{startingIndex:n=-1,decrement:r=!1,disabledIndices:a,amount:i=1}=t===void 0?{}:t,o=n;do o+=r?-i:i;while(o>=0&&o<=e.current.length-1&&gi(e,o,a));return o}function n8e(e,t){let{event:n,orientation:r,loop:a,rtl:i,cols:o,disabledIndices:s,minIndex:l,maxIndex:u,prevIndex:d,stopEvent:p=!1}=t,m=d;if(n.key===U6e){if(p&&Xt(n),d===-1)m=u;else if(m=kt(e,{startingIndex:m,amount:o,decrement:!0,disabledIndices:s}),a&&(d-o<l||m<0)){const h=d%o,g=u%o,f=u-(g-h);g===h?m=u:m=g>h?f:f-o}sa(e,m)&&(m=d)}if(n.key===H6e&&(p&&Xt(n),d===-1?m=l:(m=kt(e,{startingIndex:d,amount:o,disabledIndices:s}),a&&d+o>u&&(m=kt(e,{startingIndex:d%o-o,amount:o,disabledIndices:s}))),sa(e,m)&&(m=d)),r==="both"){const h=Lr(d/o);n.key===(i?Fo:Po)&&(p&&Xt(n),d%o!==o-1?(m=kt(e,{startingIndex:d,disabledIndices:s}),a&&Ua(m,o,h)&&(m=kt(e,{startingIndex:d-d%o-1,disabledIndices:s}))):a&&(m=kt(e,{startingIndex:d-d%o-1,disabledIndices:s})),Ua(m,o,h)&&(m=d)),n.key===(i?Po:Fo)&&(p&&Xt(n),d%o!==0?(m=kt(e,{startingIndex:d,decrement:!0,disabledIndices:s}),a&&Ua(m,o,h)&&(m=kt(e,{startingIndex:d+(o-d%o),decrement:!0,disabledIndices:s}))):a&&(m=kt(e,{startingIndex:d+(o-d%o),decrement:!0,disabledIndices:s})),Ua(m,o,h)&&(m=d));const g=Lr(u/o)===h;sa(e,m)&&(a&&g?m=n.key===(i?Po:Fo)?u:kt(e,{startingIndex:d-d%o-1,disabledIndices:s}):m=d)}return m}function r8e(e,t,n){const r=[];let a=0;return e.forEach((i,o)=>{let{width:s,height:l}=i;if(s>t&&process.env.NODE_ENV!=="production")throw new Error("[Floating UI]: Invalid grid - item width at index "+o+" is greater than grid columns");let u=!1;for(n&&(a=0);!u;){const d=[];for(let p=0;p<s;p++)for(let m=0;m<l;m++)d.push(a+p+m*t);a%t+s<=t&&d.every(p=>r[p]==null)?(d.forEach(p=>{r[p]=o}),u=!0):a++}}),[...r]}function a8e(e,t,n,r,a){if(e===-1)return-1;const i=n.indexOf(e),o=t[e];switch(a){case"tl":return i;case"tr":return o?i+o.width-1:i;case"bl":return o?i+(o.height-1)*r:i;case"br":return n.lastIndexOf(e)}}function i8e(e,t){return t.flatMap((n,r)=>e.includes(n)?[r]:[])}function gi(e,t,n){if(typeof n=="function")return n(t);if(n)return n.includes(t);const r=e.current[t];return r==null||r.hasAttribute("disabled")||r.getAttribute("aria-disabled")==="true"}const z5=()=>({getShadowRoot:!0,displayCheck:typeof ResizeObserver=="function"&&ResizeObserver.toString().includes("[native code]")?"full":"none"});function $5(e,t){const n=C5(e,z5()),r=n.length;if(r===0)return;const a=ma(dn(e)),i=n.indexOf(a),o=i===-1?t===1?0:r-1:i+t;return n[o]}function o8e(e){return $5(dn(e).body,1)||e}function s8e(e){return $5(dn(e).body,-1)||e}function Uo(e,t){const n=t||e.currentTarget,r=e.relatedTarget;return!r||!fr(n,r)}function l8e(e){C5(e,z5()).forEach(n=>{n.dataset.tabindex=n.getAttribute("tabindex")||"",n.setAttribute("tabindex","-1")})}function qh(e){e.querySelectorAll("[data-tabindex]").forEach(n=>{const r=n.dataset.tabindex;delete n.dataset.tabindex,r?n.setAttribute("tabindex",r):n.removeAttribute("tabindex")})}function Bh(e,t,n){let{reference:r,floating:a}=e;const i=Kn(t),o=E5(t),s=x5(o),l=mr(t),u=i==="y",d=r.x+r.width/2-a.width/2,p=r.y+r.height/2-a.height/2,m=r[s]/2-a[s]/2;let h;switch(l){case"top":h={x:d,y:r.y-a.height};break;case"bottom":h={x:d,y:r.y+r.height};break;case"right":h={x:r.x+r.width,y:p};break;case"left":h={x:r.x-a.width,y:p};break;default:h={x:r.x,y:r.y}}switch(ao(t)){case"start":h[o]-=m*(n&&u?-1:1);break;case"end":h[o]+=m*(n&&u?-1:1);break}return h}const c8e=async(e,t,n)=>{const{placement:r="bottom",strategy:a="absolute",middleware:i=[],platform:o}=n,s=i.filter(Boolean),l=await(o.isRTL==null?void 0:o.isRTL(t));let u=await o.getElementRects({reference:e,floating:t,strategy:a}),{x:d,y:p}=Bh(u,r,l),m=r,h={},g=0;for(let f=0;f<s.length;f++){const{name:w,fn:v}=s[f],{x:k,y:_,data:E,reset:S}=await v({x:d,y:p,initialPlacement:r,placement:m,strategy:a,middlewareData:h,rects:u,platform:o,elements:{reference:e,floating:t}});d=k??d,p=_??p,h={...h,[w]:{...h[w],...E}},S&&g<=50&&(g++,typeof S=="object"&&(S.placement&&(m=S.placement),S.rects&&(u=S.rects===!0?await o.getElementRects({reference:e,floating:t,strategy:a}):S.rects),{x:d,y:p}=Bh(u,m,l)),f=-1)}return{x:d,y:p,placement:m,strategy:a,middlewareData:h}};async function F5(e,t){var n;t===void 0&&(t={});const{x:r,y:a,platform:i,rects:o,elements:s,strategy:l}=e,{boundary:u="clippingAncestors",rootBoundary:d="viewport",elementContext:p="floating",altBoundary:m=!1,padding:h=0}=ro(t,e),g=x6e(h),w=s[m?p==="floating"?"reference":"floating":p],v=Ii(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(w)))==null||n?w:w.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(s.floating)),boundary:u,rootBoundary:d,strategy:l})),k=p==="floating"?{x:r,y:a,width:o.floating.width,height:o.floating.height}:o.reference,_=await(i.getOffsetParent==null?void 0:i.getOffsetParent(s.floating)),E=await(i.isElement==null?void 0:i.isElement(_))?await(i.getScale==null?void 0:i.getScale(_))||{x:1,y:1}:{x:1,y:1},S=Ii(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:k,offsetParent:_,strategy:l}):k);return{top:(v.top-S.top+g.top)/E.y,bottom:(S.bottom-v.bottom+g.bottom)/E.y,left:(v.left-S.left+g.left)/E.x,right:(S.right-v.right+g.right)/E.x}}const u8e=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:a,middlewareData:i,rects:o,initialPlacement:s,platform:l,elements:u}=t,{mainAxis:d=!0,crossAxis:p=!0,fallbackPlacements:m,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:f=!0,...w}=ro(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const v=mr(a),k=Kn(s),_=mr(s)===s,E=await(l.isRTL==null?void 0:l.isRTL(u.floating)),S=m||(_||!f?[Ri(s)]:y6e(s)),x=g!=="none";!m&&x&&S.push(..._6e(s,f,g,E));const D=[s,...S],P=await F5(t,w),C=[];let L=((r=i.flip)==null?void 0:r.overflows)||[];if(d&&C.push(P[v]),p){const K=g6e(a,o,E);C.push(P[K[0]],P[K[1]])}if(L=[...L,{placement:a,overflows:C}],!C.every(K=>K<=0)){var G,X;const K=(((G=i.flip)==null?void 0:G.index)||0)+1,R=D[K];if(R&&(!(p==="alignment"?k!==Kn(R):!1)||L.every(z=>Kn(z.placement)===k?z.overflows[0]>0:!0)))return{data:{index:K,overflows:L},reset:{placement:R}};let B=(X=L.filter(H=>H.overflows[0]<=0).sort((H,z)=>H.overflows[1]-z.overflows[1])[0])==null?void 0:X.placement;if(!B)switch(h){case"bestFit":{var J;const H=(J=L.filter(z=>{if(x){const j=Kn(z.placement);return j===k||j==="y"}return!0}).map(z=>[z.placement,z.overflows.filter(j=>j>0).reduce((j,A)=>j+A,0)]).sort((z,j)=>z[1]-j[1])[0])==null?void 0:J[0];H&&(B=H);break}case"initialPlacement":B=s;break}if(a!==B)return{reset:{placement:B}}}return{}}}},d8e=new Set(["left","top"]);async function p8e(e,t){const{placement:n,platform:r,elements:a}=e,i=await(r.isRTL==null?void 0:r.isRTL(a.floating)),o=mr(n),s=ao(n),l=Kn(n)==="y",u=d8e.has(o)?-1:1,d=i&&l?-1:1,p=ro(t,e);let{mainAxis:m,crossAxis:h,alignmentAxis:g}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return s&&typeof g=="number"&&(h=s==="end"?g*-1:g),l?{x:h*d,y:m*u}:{x:m*u,y:h*d}}const h8e=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:a,y:i,placement:o,middlewareData:s}=t,l=await p8e(t,e);return o===((n=s.offset)==null?void 0:n.placement)&&(r=s.arrow)!=null&&r.alignmentOffset?{}:{x:a+l.x,y:i+l.y,data:{...l,placement:o}}}}},m8e=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:a}=t,{mainAxis:i=!0,crossAxis:o=!1,limiter:s={fn:w=>{let{x:v,y:k}=w;return{x:v,y:k}}},...l}=ro(e,t),u={x:n,y:r},d=await F5(t,l),p=Kn(mr(a)),m=w5(p);let h=u[m],g=u[p];if(i){const w=m==="y"?"top":"left",v=m==="y"?"bottom":"right",k=h+d[w],_=h-d[v];h=Oh(k,h,_)}if(o){const w=p==="y"?"top":"left",v=p==="y"?"bottom":"right",k=g+d[w],_=g-d[v];g=Oh(k,g,_)}const f=s.fn({...t,[m]:h,[p]:g});return{...f,data:{x:f.x-n,y:f.y-r,enabled:{[m]:i,[p]:o}}}}}};function P5(e){const t=an(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const a=xt(e),i=a?e.offsetWidth:n,o=a?e.offsetHeight:r,s=Ci(n)!==i||Ci(r)!==o;return s&&(n=i,r=o),{width:n,height:r,$:s}}function Hd(e){return Qe(e)?e:e.contextElement}function zr(e){const t=Hd(e);if(!xt(t))return vn(1);const n=t.getBoundingClientRect(),{width:r,height:a,$:i}=P5(t);let o=(i?Ci(n.width):n.width)/r,s=(i?Ci(n.height):n.height)/a;return(!o||!Number.isFinite(o))&&(o=1),(!s||!Number.isFinite(s))&&(s=1),{x:o,y:s}}const f8e=vn(0);function q5(e){const t=$t(e);return!to()||!t.visualViewport?f8e:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function g8e(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==$t(e)?!1:t}function gr(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const a=e.getBoundingClientRect(),i=Hd(e);let o=vn(1);t&&(r?Qe(r)&&(o=zr(r)):o=zr(e));const s=g8e(i,n,r)?q5(i):vn(0);let l=(a.left+s.x)/o.x,u=(a.top+s.y)/o.y,d=a.width/o.x,p=a.height/o.y;if(i){const m=$t(i),h=r&&Qe(r)?$t(r):r;let g=m,f=Yu(g);for(;f&&r&&h!==g;){const w=zr(f),v=f.getBoundingClientRect(),k=an(f),_=v.left+(f.clientLeft+parseFloat(k.paddingLeft))*w.x,E=v.top+(f.clientTop+parseFloat(k.paddingTop))*w.y;l*=w.x,u*=w.y,d*=w.x,p*=w.y,l+=_,u+=E,g=$t(f),f=Yu(g)}}return Ii({width:d,height:p,x:l,y:u})}function io(e,t){const n=no(e).scrollLeft;return t?t.left+n:gr(xn(e)).left+n}function B5(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-io(e,n),a=n.top+t.scrollTop;return{x:r,y:a}}function y8e(e){let{elements:t,rect:n,offsetParent:r,strategy:a}=e;const i=a==="fixed",o=xn(r),s=t?eo(t.floating):!1;if(r===o||s&&i)return n;let l={scrollLeft:0,scrollTop:0},u=vn(1);const d=vn(0),p=xt(r);if((p||!p&&!i)&&((Ur(r)!=="body"||Sa(o))&&(l=no(r)),xt(r))){const h=gr(r);u=zr(r),d.x=h.x+r.clientLeft,d.y=h.y+r.clientTop}const m=o&&!p&&!i?B5(o,l):vn(0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-l.scrollLeft*u.x+d.x+m.x,y:n.y*u.y-l.scrollTop*u.y+d.y+m.y}}function b8e(e){return Array.from(e.getClientRects())}function k8e(e){const t=xn(e),n=no(e),r=e.ownerDocument.body,a=pr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=pr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let o=-n.scrollLeft+io(e);const s=-n.scrollTop;return an(r).direction==="rtl"&&(o+=pr(t.clientWidth,r.clientWidth)-a),{width:a,height:i,x:o,y:s}}const Uh=25;function v8e(e,t){const n=$t(e),r=xn(e),a=n.visualViewport;let i=r.clientWidth,o=r.clientHeight,s=0,l=0;if(a){i=a.width,o=a.height;const d=to();(!d||d&&t==="fixed")&&(s=a.offsetLeft,l=a.offsetTop)}const u=io(r);if(u<=0){const d=r.ownerDocument,p=d.body,m=getComputedStyle(p),h=d.compatMode==="CSS1Compat"&&parseFloat(m.marginLeft)+parseFloat(m.marginRight)||0,g=Math.abs(r.clientWidth-p.clientWidth-h);g<=Uh&&(i-=g)}else u<=Uh&&(i+=u);return{width:i,height:o,x:s,y:l}}const _8e=new Set(["absolute","fixed"]);function w8e(e,t){const n=gr(e,!0,t==="fixed"),r=n.top+e.clientTop,a=n.left+e.clientLeft,i=xt(e)?zr(e):vn(1),o=e.clientWidth*i.x,s=e.clientHeight*i.y,l=a*i.x,u=r*i.y;return{width:o,height:s,x:l,y:u}}function Hh(e,t,n){let r;if(t==="viewport")r=v8e(e,n);else if(t==="document")r=k8e(xn(e));else if(Qe(t))r=w8e(t,n);else{const a=q5(e);r={x:t.x-a.x,y:t.y-a.y,width:t.width,height:t.height}}return Ii(r)}function U5(e,t){const n=$n(e);return n===t||!Qe(n)||Ln(n)?!1:an(n).position==="fixed"||U5(n,t)}function x8e(e,t){const n=t.get(e);if(n)return n;let r=Xn(e,[],!1).filter(s=>Qe(s)&&Ur(s)!=="body"),a=null;const i=an(e).position==="fixed";let o=i?$n(e):e;for(;Qe(o)&&!Ln(o);){const s=an(o),l=Bd(o);!l&&s.position==="fixed"&&(a=null),(i?!l&&!a:!l&&s.position==="static"&&!!a&&_8e.has(a.position)||Sa(o)&&!l&&U5(e,o))?r=r.filter(d=>d!==o):a=s,o=$n(o)}return t.set(e,r),r}function E8e(e){let{element:t,boundary:n,rootBoundary:r,strategy:a}=e;const o=[...n==="clippingAncestors"?eo(t)?[]:x8e(t,this._c):[].concat(n),r],s=o[0],l=o.reduce((u,d)=>{const p=Hh(t,d,a);return u.top=pr(p.top,u.top),u.right=Ti(p.right,u.right),u.bottom=Ti(p.bottom,u.bottom),u.left=pr(p.left,u.left),u},Hh(t,s,a));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function M8e(e){const{width:t,height:n}=P5(e);return{width:t,height:n}}function S8e(e,t,n){const r=xt(t),a=xn(t),i=n==="fixed",o=gr(e,!0,i,t);let s={scrollLeft:0,scrollTop:0};const l=vn(0);function u(){l.x=io(a)}if(r||!r&&!i)if((Ur(t)!=="body"||Sa(a))&&(s=no(t)),r){const h=gr(t,!0,i,t);l.x=h.x+t.clientLeft,l.y=h.y+t.clientTop}else a&&u();i&&!r&&a&&u();const d=a&&!r&&!i?B5(a,s):vn(0),p=o.left+s.scrollLeft-l.x-d.x,m=o.top+s.scrollTop-l.y-d.y;return{x:p,y:m,width:o.width,height:o.height}}function Ho(e){return an(e).position==="static"}function jh(e,t){if(!xt(e)||an(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return xn(e)===n&&(n=n.ownerDocument.body),n}function H5(e,t){const n=$t(e);if(eo(e))return n;if(!xt(e)){let a=$n(e);for(;a&&!Ln(a);){if(Qe(a)&&!Ho(a))return a;a=$n(a)}return n}let r=jh(e,t);for(;r&&o6e(r)&&Ho(r);)r=jh(r,t);return r&&Ln(r)&&Ho(r)&&!Bd(r)?n:r||d6e(e)||n}const N8e=async function(e){const t=this.getOffsetParent||H5,n=this.getDimensions,r=await n(e.floating);return{reference:S8e(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function A8e(e){return an(e).direction==="rtl"}const T8e={convertOffsetParentRelativeRectToViewportRelativeRect:y8e,getDocumentElement:xn,getClippingRect:E8e,getOffsetParent:H5,getElementRects:N8e,getClientRects:b8e,getDimensions:M8e,getScale:zr,isElement:Qe,isRTL:A8e};function j5(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function C8e(e,t){let n=null,r;const a=xn(e);function i(){var s;clearTimeout(r),(s=n)==null||s.disconnect(),n=null}function o(s,l){s===void 0&&(s=!1),l===void 0&&(l=1),i();const u=e.getBoundingClientRect(),{left:d,top:p,width:m,height:h}=u;if(s||t(),!m||!h)return;const g=Lr(p),f=Lr(a.clientWidth-(d+m)),w=Lr(a.clientHeight-(p+h)),v=Lr(d),_={rootMargin:-g+"px "+-f+"px "+-w+"px "+-v+"px",threshold:pr(0,Ti(1,l))||1};let E=!0;function S(x){const D=x[0].intersectionRatio;if(D!==l){if(!E)return o();D?o(!1,D):r=setTimeout(()=>{o(!1,1e-7)},1e3)}D===1&&!j5(u,e.getBoundingClientRect())&&o(),E=!1}try{n=new IntersectionObserver(S,{..._,root:a.ownerDocument})}catch{n=new IntersectionObserver(S,_)}n.observe(e)}return o(!0),i}function jd(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:a=!0,ancestorResize:i=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:s=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,u=Hd(e),d=a||i?[...u?Xn(u):[],...Xn(t)]:[];d.forEach(v=>{a&&v.addEventListener("scroll",n,{passive:!0}),i&&v.addEventListener("resize",n)});const p=u&&s?C8e(u,n):null;let m=-1,h=null;o&&(h=new ResizeObserver(v=>{let[k]=v;k&&k.target===u&&h&&(h.unobserve(t),cancelAnimationFrame(m),m=requestAnimationFrame(()=>{var _;(_=h)==null||_.observe(t)})),n()}),u&&!l&&h.observe(u),h.observe(t));let g,f=l?gr(e):null;l&&w();function w(){const v=gr(e);f&&!j5(f,v)&&n(),f=v,g=requestAnimationFrame(w)}return n(),()=>{var v;d.forEach(k=>{a&&k.removeEventListener("scroll",n),i&&k.removeEventListener("resize",n)}),p?.(),(v=h)==null||v.disconnect(),h=null,l&&cancelAnimationFrame(g)}}const R8e=h8e,I8e=m8e,O8e=u8e,L8e=(e,t,n)=>{const r=new Map,a={platform:T8e,...n},i={...a.platform,_c:r};return c8e(e,t,{...a,platform:i})};var D8e=typeof document<"u",z8e=function(){},yi=D8e?V.useLayoutEffect:z8e;function Li(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,a;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(!Li(e[r],t[r]))return!1;return!0}if(a=Object.keys(e),n=a.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,a[r]))return!1;for(r=n;r--!==0;){const i=a[r];if(!(i==="_owner"&&e.$$typeof)&&!Li(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function V5(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Vh(e,t){const n=V5(e);return Math.round(t*n)/n}function jo(e){const t=te.useRef(e);return yi(()=>{t.current=e}),t}function $8e(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:a,elements:{reference:i,floating:o}={},transform:s=!0,whileElementsMounted:l,open:u}=e,[d,p]=te.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[m,h]=te.useState(r);Li(m,r)||h(r);const[g,f]=te.useState(null),[w,v]=te.useState(null),k=te.useCallback(z=>{z!==x.current&&(x.current=z,f(z))},[]),_=te.useCallback(z=>{z!==D.current&&(D.current=z,v(z))},[]),E=i||g,S=o||w,x=te.useRef(null),D=te.useRef(null),P=te.useRef(d),C=l!=null,L=jo(l),G=jo(a),X=jo(u),J=te.useCallback(()=>{if(!x.current||!D.current)return;const z={placement:t,strategy:n,middleware:m};G.current&&(z.platform=G.current),L8e(x.current,D.current,z).then(j=>{const A={...j,isPositioned:X.current!==!1};K.current&&!Li(P.current,A)&&(P.current=A,o5.flushSync(()=>{p(A)}))})},[m,t,n,G,X]);yi(()=>{u===!1&&P.current.isPositioned&&(P.current.isPositioned=!1,p(z=>({...z,isPositioned:!1})))},[u]);const K=te.useRef(!1);yi(()=>(K.current=!0,()=>{K.current=!1}),[]),yi(()=>{if(E&&(x.current=E),S&&(D.current=S),E&&S){if(L.current)return L.current(E,S,J);J()}},[E,S,J,L,C]);const R=te.useMemo(()=>({reference:x,floating:D,setReference:k,setFloating:_}),[k,_]),B=te.useMemo(()=>({reference:E,floating:S}),[E,S]),H=te.useMemo(()=>{const z={position:n,left:0,top:0};if(!B.floating)return z;const j=Vh(B.floating,d.x),A=Vh(B.floating,d.y);return s?{...z,transform:"translate("+j+"px, "+A+"px)",...V5(B.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:j,top:A}},[n,s,B.floating,d.x,d.y]);return te.useMemo(()=>({...d,update:J,refs:R,elements:B,floatingStyles:H}),[d,J,R,B,H])}const Vd=(e,t)=>({...R8e(e),options:[e,t]}),Gd=(e,t)=>({...I8e(e),options:[e,t]}),Wd=(e,t)=>({...O8e(e),options:[e,t]}),F8e="data-floating-ui-focusable",Gh="active",Wh="selected",Na="ArrowLeft",Aa="ArrowRight",G5="ArrowUp",oo="ArrowDown",P8e={...te};let Kh=!1,q8e=0;const Yh=()=>"floating-ui-"+Math.random().toString(36).slice(2,6)+q8e++;function B8e(){const[e,t]=te.useState(()=>Kh?Yh():void 0);return gt(()=>{e==null&&t(Yh())},[]),te.useEffect(()=>{Kh=!0},[]),e}const U8e=P8e.useId,Kd=U8e||B8e;let ga;process.env.NODE_ENV!=="production"&&(ga=new Set);function Vo(){for(var e,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];const a="Floating UI: "+n.join(" ");if(!((e=ga)!=null&&e.has(a))){var i;(i=ga)==null||i.add(a),console.warn(a)}}function H8e(){for(var e,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];const a="Floating UI: "+n.join(" ");if(!((e=ga)!=null&&e.has(a))){var i;(i=ga)==null||i.add(a),console.error(a)}}function j8e(){const e=new Map;return{emit(t,n){var r;(r=e.get(t))==null||r.forEach(a=>a(n))},on(t,n){e.has(t)||e.set(t,new Set),e.get(t).add(n)},off(t,n){var r;(r=e.get(t))==null||r.delete(n)}}}const V8e=te.createContext(null),G8e=te.createContext(null),so=()=>{var e;return((e=te.useContext(V8e))==null?void 0:e.id)||null},lo=()=>te.useContext(G8e);function Ta(e){return"data-floating-ui-"+e}function Zt(e){e.current!==-1&&(clearTimeout(e.current),e.current=-1)}const Zh=Ta("safe-polygon");function Go(e,t,n){if(n&&!fa(n))return 0;if(typeof e=="number")return e;if(typeof e=="function"){const r=e();return typeof r=="number"?r:r?.[t]}return e?.[t]}function Wo(e){return typeof e=="function"?e():e}function W8e(e,t){t===void 0&&(t={});const{open:n,onOpenChange:r,dataRef:a,events:i,elements:o}=e,{enabled:s=!0,delay:l=0,handleClose:u=null,mouseOnly:d=!1,restMs:p=0,move:m=!0}=t,h=lo(),g=so(),f=Rn(u),w=Rn(l),v=Rn(n),k=Rn(p),_=te.useRef(),E=te.useRef(-1),S=te.useRef(),x=te.useRef(-1),D=te.useRef(!0),P=te.useRef(!1),C=te.useRef(()=>{}),L=te.useRef(!1),G=Vt(()=>{var H;const z=(H=a.current.openEvent)==null?void 0:H.type;return z?.includes("mouse")&&z!=="mousedown"});te.useEffect(()=>{if(!s)return;function H(z){let{open:j}=z;j||(Zt(E),Zt(x),D.current=!0,L.current=!1)}return i.on("openchange",H),()=>{i.off("openchange",H)}},[s,i]),te.useEffect(()=>{if(!s||!f.current||!n)return;function H(j){G()&&r(!1,j,"hover")}const z=dn(o.floating).documentElement;return z.addEventListener("mouseleave",H),()=>{z.removeEventListener("mouseleave",H)}},[o.floating,n,r,s,f,G]);const X=te.useCallback(function(H,z,j){z===void 0&&(z=!0),j===void 0&&(j="hover");const A=Go(w.current,"close",_.current);A&&!S.current?(Zt(E),E.current=window.setTimeout(()=>r(!1,H,j),A)):z&&(Zt(E),r(!1,H,j))},[w,r]),J=Vt(()=>{C.current(),S.current=void 0}),K=Vt(()=>{if(P.current){const H=dn(o.floating).body;H.style.pointerEvents="",H.removeAttribute(Zh),P.current=!1}}),R=Vt(()=>a.current.openEvent?["click","mousedown"].includes(a.current.openEvent.type):!1);te.useEffect(()=>{if(!s)return;function H(ee){if(Zt(E),D.current=!1,d&&!fa(_.current)||Wo(k.current)>0&&!Go(w.current,"open"))return;const O=Go(w.current,"open",_.current);O?E.current=window.setTimeout(()=>{v.current||r(!0,ee,"hover")},O):n||r(!0,ee,"hover")}function z(ee){if(R()){K();return}C.current();const O=dn(o.floating);if(Zt(x),L.current=!1,f.current&&a.current.floatingContext){n||Zt(E),S.current=f.current({...a.current.floatingContext,tree:h,x:ee.clientX,y:ee.clientY,onClose(){K(),J(),R()||X(ee,!0,"safe-polygon")}});const ge=S.current;O.addEventListener("mousemove",ge),C.current=()=>{O.removeEventListener("mousemove",ge)};return}(_.current==="touch"?!fr(o.floating,ee.relatedTarget):!0)&&X(ee)}function j(ee){R()||a.current.floatingContext&&(f.current==null||f.current({...a.current.floatingContext,tree:h,x:ee.clientX,y:ee.clientY,onClose(){K(),J(),R()||X(ee)}})(ee))}function A(){Zt(E)}function Y(ee){R()||X(ee,!1)}if(Qe(o.domReference)){const ee=o.domReference,O=o.floating;return n&&ee.addEventListener("mouseleave",j),m&&ee.addEventListener("mousemove",H,{once:!0}),ee.addEventListener("mouseenter",H),ee.addEventListener("mouseleave",z),O&&(O.addEventListener("mouseleave",j),O.addEventListener("mouseenter",A),O.addEventListener("mouseleave",Y)),()=>{n&&ee.removeEventListener("mouseleave",j),m&&ee.removeEventListener("mousemove",H),ee.removeEventListener("mouseenter",H),ee.removeEventListener("mouseleave",z),O&&(O.removeEventListener("mouseleave",j),O.removeEventListener("mouseenter",A),O.removeEventListener("mouseleave",Y))}}},[o,s,e,d,m,X,J,K,r,n,v,h,w,f,a,R,k]),gt(()=>{var H;if(s&&n&&(H=f.current)!=null&&(H=H.__options)!=null&&H.blockPointerEvents&&G()){P.current=!0;const j=o.floating;if(Qe(o.domReference)&&j){var z;const A=dn(o.floating).body;A.setAttribute(Zh,"");const Y=o.domReference,ee=h==null||(z=h.nodesRef.current.find(O=>O.id===g))==null||(z=z.context)==null?void 0:z.elements.floating;return ee&&(ee.style.pointerEvents=""),A.style.pointerEvents="none",Y.style.pointerEvents="auto",j.style.pointerEvents="auto",()=>{A.style.pointerEvents="",Y.style.pointerEvents="",j.style.pointerEvents=""}}}},[s,n,g,o,h,f,G]),gt(()=>{n||(_.current=void 0,L.current=!1,J(),K())},[n,J,K]),te.useEffect(()=>()=>{J(),Zt(E),Zt(x),K()},[s,o.domReference,J,K]);const B=te.useMemo(()=>{function H(z){_.current=z.pointerType}return{onPointerDown:H,onPointerEnter:H,onMouseMove(z){const{nativeEvent:j}=z;function A(){!D.current&&!v.current&&r(!0,j,"hover")}d&&!fa(_.current)||n||Wo(k.current)===0||L.current&&z.movementX**2+z.movementY**2<2||(Zt(x),_.current==="touch"?A():(L.current=!0,x.current=window.setTimeout(A,Wo(k.current))))}}},[d,r,n,v,k]);return te.useMemo(()=>s?{reference:B}:{},[s,B])}let Xh=0;function K8e(e,t){t===void 0&&(t={});const{preventScroll:n=!1,cancelPrevious:r=!0,sync:a=!1}=t;r&&cancelAnimationFrame(Xh);const i=()=>e?.focus({preventScroll:n});a?i():Xh=requestAnimationFrame(i)}const W5={border:0,clip:"rect(0 0 0 0)",height:"1px",margin:"-1px",overflow:"hidden",padding:0,position:"fixed",whiteSpace:"nowrap",width:"1px",top:0,left:0},Qh=te.forwardRef(function(t,n){const[r,a]=te.useState();gt(()=>{O5()&&a("button")},[]);const i={ref:n,tabIndex:0,role:r,"aria-hidden":r?void 0:!0,[Ta("focus-guard")]:"",style:W5};return N.jsx("span",{...t,...i})}),K5=te.createContext(null),Jh=Ta("portal");function Y8e(e){e===void 0&&(e={});const{id:t,root:n}=e,r=Kd(),a=X8e(),[i,o]=te.useState(null),s=te.useRef(null);return gt(()=>()=>{i?.remove(),queueMicrotask(()=>{s.current=null})},[i]),gt(()=>{if(!r||s.current)return;const l=t?document.getElementById(t):null;if(!l)return;const u=document.createElement("div");u.id=r,u.setAttribute(Jh,""),l.appendChild(u),s.current=u,o(u)},[t,r]),gt(()=>{if(n===null||!r||s.current)return;let l=n||a?.portalNode;l&&!qd(l)&&(l=l.current),l=l||document.body;let u=null;t&&(u=document.createElement("div"),u.id=t,l.appendChild(u));const d=document.createElement("div");d.id=r,d.setAttribute(Jh,""),l=u||l,l.appendChild(d),s.current=d,o(d)},[t,n,r,a]),i}function Z8e(e){const{children:t,id:n,root:r,preserveTabOrder:a=!0}=e,i=Y8e({id:n,root:r}),[o,s]=te.useState(null),l=te.useRef(null),u=te.useRef(null),d=te.useRef(null),p=te.useRef(null),m=o?.modal,h=o?.open,g=!!o&&!o.modal&&o.open&&a&&!!(r||i);return te.useEffect(()=>{if(!i||!a||m)return;function f(w){i&&Uo(w)&&(w.type==="focusin"?qh:l8e)(i)}return i.addEventListener("focusin",f,!0),i.addEventListener("focusout",f,!0),()=>{i.removeEventListener("focusin",f,!0),i.removeEventListener("focusout",f,!0)}},[i,a,m]),te.useEffect(()=>{i&&(h||qh(i))},[h,i]),N.jsxs(K5.Provider,{value:te.useMemo(()=>({preserveTabOrder:a,beforeOutsideRef:l,afterOutsideRef:u,beforeInsideRef:d,afterInsideRef:p,portalNode:i,setFocusManagerState:s}),[a,i]),children:[g&&i&&N.jsx(Qh,{"data-type":"outside",ref:l,onFocus:f=>{if(Uo(f,i)){var w;(w=d.current)==null||w.focus()}else{const v=o?o.domReference:null,k=s8e(v);k?.focus()}}}),g&&i&&N.jsx("span",{"aria-owns":i.id,style:W5}),i&&o5.createPortal(t,i),g&&i&&N.jsx(Qh,{"data-type":"outside",ref:u,onFocus:f=>{if(Uo(f,i)){var w;(w=p.current)==null||w.focus()}else{const v=o?o.domReference:null,k=o8e(v);k?.focus(),o?.closeOnFocusOut&&o?.onOpenChange(!1,f.nativeEvent,"focus-out")}}})]})}const X8e=()=>te.useContext(K5);function e2(e){return xt(e.target)&&e.target.tagName==="BUTTON"}function Q8e(e){return xt(e.target)&&e.target.tagName==="A"}function t2(e){return Ud(e)}function Y5(e,t){t===void 0&&(t={});const{open:n,onOpenChange:r,dataRef:a,elements:{domReference:i}}=e,{enabled:o=!0,event:s="click",toggle:l=!0,ignoreMouse:u=!1,keyboardHandlers:d=!0,stickIfOpen:p=!0}=t,m=te.useRef(),h=te.useRef(!1),g=te.useMemo(()=>({onPointerDown(f){m.current=f.pointerType},onMouseDown(f){const w=m.current;f.button===0&&s!=="click"&&(fa(w,!0)&&u||(n&&l&&(!(a.current.openEvent&&p)||a.current.openEvent.type==="mousedown")?r(!1,f.nativeEvent,"click"):(f.preventDefault(),r(!0,f.nativeEvent,"click"))))},onClick(f){const w=m.current;if(s==="mousedown"&&m.current){m.current=void 0;return}fa(w,!0)&&u||(n&&l&&(!(a.current.openEvent&&p)||a.current.openEvent.type==="click")?r(!1,f.nativeEvent,"click"):r(!0,f.nativeEvent,"click"))},onKeyDown(f){m.current=void 0,!(f.defaultPrevented||!d||e2(f))&&(f.key===" "&&!t2(i)&&(f.preventDefault(),h.current=!0),!Q8e(f)&&f.key==="Enter"&&r(!(n&&l),f.nativeEvent,"click"))},onKeyUp(f){f.defaultPrevented||!d||e2(f)||t2(i)||f.key===" "&&h.current&&(h.current=!1,r(!(n&&l),f.nativeEvent,"click"))}}),[a,i,s,u,d,r,n,p,l]);return te.useMemo(()=>o?{reference:g}:{},[o,g])}const J8e={pointerdown:"onPointerDown",mousedown:"onMouseDown",click:"onClick"},e7e={pointerdown:"onPointerDownCapture",mousedown:"onMouseDownCapture",click:"onClickCapture"},n2=e=>{var t,n;return{escapeKey:typeof e=="boolean"?e:(t=e?.escapeKey)!=null?t:!1,outsidePress:typeof e=="boolean"?e:(n=e?.outsidePress)!=null?n:!0}};function Yd(e,t){t===void 0&&(t={});const{open:n,onOpenChange:r,elements:a,dataRef:i}=e,{enabled:o=!0,escapeKey:s=!0,outsidePress:l=!0,outsidePressEvent:u="pointerdown",referencePress:d=!1,referencePressEvent:p="pointerdown",ancestorScroll:m=!1,bubbles:h,capture:g}=t,f=lo(),w=Vt(typeof l=="function"?l:()=>!1),v=typeof l=="function"?w:l,k=te.useRef(!1),{escapeKey:_,outsidePress:E}=n2(h),{escapeKey:S,outsidePress:x}=n2(g),D=te.useRef(!1),P=Vt(K=>{var R;if(!n||!o||!s||K.key!=="Escape"||D.current)return;const B=(R=i.current.floatingContext)==null?void 0:R.nodeId,H=f?oa(f.nodesRef.current,B):[];if(!_&&(K.stopPropagation(),H.length>0)){let z=!0;if(H.forEach(j=>{var A;if((A=j.context)!=null&&A.open&&!j.context.dataRef.current.__escapeKeyBubbles){z=!1;return}}),!z)return}r(!1,K6e(K)?K.nativeEvent:K,"escape-key")}),C=Vt(K=>{var R;const B=()=>{var H;P(K),(H=Ar(K))==null||H.removeEventListener("keydown",B)};(R=Ar(K))==null||R.addEventListener("keydown",B)}),L=Vt(K=>{var R;const B=i.current.insideReactTree;i.current.insideReactTree=!1;const H=k.current;if(k.current=!1,u==="click"&&H||B||typeof v=="function"&&!v(K))return;const z=Ar(K),j="["+Ta("inert")+"]",A=dn(a.floating).querySelectorAll(j);let Y=Qe(z)?z:null;for(;Y&&!Ln(Y);){const ge=$n(Y);if(Ln(ge)||!Qe(ge))break;Y=ge}if(A.length&&Qe(z)&&!j6e(z)&&!fr(z,a.floating)&&Array.from(A).every(ge=>!fr(Y,ge)))return;if(xt(z)&&J){const ge=Ln(z),ke=an(z),Te=/auto|scroll/,qe=ge||Te.test(ke.overflowX),Ke=ge||Te.test(ke.overflowY),re=qe&&z.clientWidth>0&&z.scrollWidth>z.clientWidth,_e=Ke&&z.clientHeight>0&&z.scrollHeight>z.clientHeight,Ge=ke.direction==="rtl",We=_e&&(Ge?K.offsetX<=z.offsetWidth-z.clientWidth:K.offsetX>z.clientWidth),Ce=re&&K.offsetY>z.clientHeight;if(We||Ce)return}const ee=(R=i.current.floatingContext)==null?void 0:R.nodeId,O=f&&oa(f.nodesRef.current,ee).some(ge=>{var ke;return qo(K,(ke=ge.context)==null?void 0:ke.elements.floating)});if(qo(K,a.floating)||qo(K,a.domReference)||O)return;const se=f?oa(f.nodesRef.current,ee):[];if(se.length>0){let ge=!0;if(se.forEach(ke=>{var Te;if((Te=ke.context)!=null&&Te.open&&!ke.context.dataRef.current.__outsidePressBubbles){ge=!1;return}}),!ge)return}r(!1,K,"outside-press")}),G=Vt(K=>{var R;const B=()=>{var H;L(K),(H=Ar(K))==null||H.removeEventListener(u,B)};(R=Ar(K))==null||R.addEventListener(u,B)});te.useEffect(()=>{if(!n||!o)return;i.current.__escapeKeyBubbles=_,i.current.__outsidePressBubbles=E;let K=-1;function R(A){r(!1,A,"ancestor-scroll")}function B(){window.clearTimeout(K),D.current=!0}function H(){K=window.setTimeout(()=>{D.current=!1},to()?5:0)}const z=dn(a.floating);s&&(z.addEventListener("keydown",S?C:P,S),z.addEventListener("compositionstart",B),z.addEventListener("compositionend",H)),v&&z.addEventListener(u,x?G:L,x);let j=[];return m&&(Qe(a.domReference)&&(j=Xn(a.domReference)),Qe(a.floating)&&(j=j.concat(Xn(a.floating))),!Qe(a.reference)&&a.reference&&a.reference.contextElement&&(j=j.concat(Xn(a.reference.contextElement)))),j=j.filter(A=>{var Y;return A!==((Y=z.defaultView)==null?void 0:Y.visualViewport)}),j.forEach(A=>{A.addEventListener("scroll",R,{passive:!0})}),()=>{s&&(z.removeEventListener("keydown",S?C:P,S),z.removeEventListener("compositionstart",B),z.removeEventListener("compositionend",H)),v&&z.removeEventListener(u,x?G:L,x),j.forEach(A=>{A.removeEventListener("scroll",R)}),window.clearTimeout(K)}},[i,a,s,v,u,n,r,m,o,_,E,P,S,C,L,x,G]),te.useEffect(()=>{i.current.insideReactTree=!1},[i,v,u]);const X=te.useMemo(()=>({onKeyDown:P,...d&&{[J8e[p]]:K=>{r(!1,K.nativeEvent,"reference-press")},...p!=="click"&&{onClick(K){r(!1,K.nativeEvent,"reference-press")}}}}),[P,r,d,p]),J=te.useMemo(()=>({onKeyDown:P,onMouseDown(){k.current=!0},onMouseUp(){k.current=!0},[e7e[u]]:()=>{i.current.insideReactTree=!0}}),[P,u,i]);return te.useMemo(()=>o?{reference:X,floating:J}:{},[o,X,J])}function t7e(e){const{open:t=!1,onOpenChange:n,elements:r}=e,a=Kd(),i=te.useRef({}),[o]=te.useState(()=>j8e()),s=so()!=null;if(process.env.NODE_ENV!=="production"){const h=r.reference;h&&!Qe(h)&&H8e("Cannot pass a virtual element to the `elements.reference` option,","as it must be a real DOM element. Use `refs.setPositionReference()`","instead.")}const[l,u]=te.useState(r.reference),d=Vt((h,g,f)=>{i.current.openEvent=h?g:void 0,o.emit("openchange",{open:h,event:g,reason:f,nested:s}),n?.(h,g,f)}),p=te.useMemo(()=>({setPositionReference:u}),[]),m=te.useMemo(()=>({reference:l||r.reference||null,floating:r.floating||null,domReference:r.reference}),[l,r.reference,r.floating]);return te.useMemo(()=>({dataRef:i,open:t,onOpenChange:d,elements:m,events:o,floatingId:a,refs:p}),[t,d,m,o,a,p])}function Zd(e){e===void 0&&(e={});const{nodeId:t}=e,n=t7e({...e,elements:{reference:null,floating:null,...e.elements}}),r=e.rootContext||n,a=r.elements,[i,o]=te.useState(null),[s,l]=te.useState(null),d=a?.domReference||i,p=te.useRef(null),m=lo();gt(()=>{d&&(p.current=d)},[d]);const h=$8e({...e,elements:{...a,...s&&{reference:s}}}),g=te.useCallback(_=>{const E=Qe(_)?{getBoundingClientRect:()=>_.getBoundingClientRect(),getClientRects:()=>_.getClientRects(),contextElement:_}:_;l(E),h.refs.setReference(E)},[h.refs]),f=te.useCallback(_=>{(Qe(_)||_===null)&&(p.current=_,o(_)),(Qe(h.refs.reference.current)||h.refs.reference.current===null||_!==null&&!Qe(_))&&h.refs.setReference(_)},[h.refs]),w=te.useMemo(()=>({...h.refs,setReference:f,setPositionReference:g,domReference:p}),[h.refs,f,g]),v=te.useMemo(()=>({...h.elements,domReference:d}),[h.elements,d]),k=te.useMemo(()=>({...h,...r,refs:w,elements:v,nodeId:t}),[h,w,v,t,r]);return gt(()=>{r.dataRef.current.floatingContext=k;const _=m?.nodesRef.current.find(E=>E.id===t);_&&(_.context=k)}),te.useMemo(()=>({...h,context:k,refs:w,elements:v}),[h,w,v,k])}function Ko(){return q6e()&&O5()}function n7e(e,t){t===void 0&&(t={});const{open:n,onOpenChange:r,events:a,dataRef:i,elements:o}=e,{enabled:s=!0,visibleOnly:l=!0}=t,u=te.useRef(!1),d=te.useRef(-1),p=te.useRef(!0);te.useEffect(()=>{if(!s)return;const h=$t(o.domReference);function g(){!n&&xt(o.domReference)&&o.domReference===ma(dn(o.domReference))&&(u.current=!0)}function f(){p.current=!0}function w(){p.current=!1}return h.addEventListener("blur",g),Ko()&&(h.addEventListener("keydown",f,!0),h.addEventListener("pointerdown",w,!0)),()=>{h.removeEventListener("blur",g),Ko()&&(h.removeEventListener("keydown",f,!0),h.removeEventListener("pointerdown",w,!0))}},[o.domReference,n,s]),te.useEffect(()=>{if(!s)return;function h(g){let{reason:f}=g;(f==="reference-press"||f==="escape-key")&&(u.current=!0)}return a.on("openchange",h),()=>{a.off("openchange",h)}},[a,s]),te.useEffect(()=>()=>{Zt(d)},[]);const m=te.useMemo(()=>({onMouseLeave(){u.current=!1},onFocus(h){if(u.current)return;const g=Ar(h.nativeEvent);if(l&&Qe(g)){if(Ko()&&!h.relatedTarget){if(!p.current&&!Ud(g))return}else if(!G6e(g))return}r(!0,h.nativeEvent,"focus")},onBlur(h){u.current=!1;const g=h.relatedTarget,f=h.nativeEvent,w=Qe(g)&&g.hasAttribute(Ta("focus-guard"))&&g.getAttribute("data-type")==="outside";d.current=window.setTimeout(()=>{var v;const k=ma(o.domReference?o.domReference.ownerDocument:document);!g&&k===o.domReference||fr((v=i.current.floatingContext)==null?void 0:v.refs.floating.current,k)||fr(o.domReference,k)||w||r(!1,f,"focus")})}}),[i,o.domReference,r,l]);return te.useMemo(()=>s?{reference:m}:{},[s,m])}function Yo(e,t,n){const r=new Map,a=n==="item";let i=e;if(a&&e){const{[Gh]:o,[Wh]:s,...l}=e;i=l}return{...n==="floating"&&{tabIndex:-1,[F8e]:""},...i,...t.map(o=>{const s=o?o[n]:null;return typeof s=="function"?e?s(e):null:s}).concat(e).reduce((o,s)=>(s&&Object.entries(s).forEach(l=>{let[u,d]=l;if(!(a&&[Gh,Wh].includes(u)))if(u.indexOf("on")===0){if(r.has(u)||r.set(u,[]),typeof d=="function"){var p;(p=r.get(u))==null||p.push(d),o[u]=function(){for(var m,h=arguments.length,g=new Array(h),f=0;f<h;f++)g[f]=arguments[f];return(m=r.get(u))==null?void 0:m.map(w=>w(...g)).find(w=>w!==void 0)}}}else o[u]=d}),o),{})}}function Xd(e){e===void 0&&(e=[]);const t=e.map(s=>s?.reference),n=e.map(s=>s?.floating),r=e.map(s=>s?.item),a=te.useCallback(s=>Yo(s,e,"reference"),t),i=te.useCallback(s=>Yo(s,e,"floating"),n),o=te.useCallback(s=>Yo(s,e,"item"),r);return te.useMemo(()=>({getReferenceProps:a,getFloatingProps:i,getItemProps:o}),[a,i,o])}const r7e="Escape";function co(e,t,n){switch(e){case"vertical":return t;case"horizontal":return n;default:return t||n}}function Ha(e,t){return co(t,e===G5||e===oo,e===Na||e===Aa)}function Zo(e,t,n){return co(t,e===oo,n?e===Na:e===Aa)||e==="Enter"||e===" "||e===""}function r2(e,t,n){return co(t,n?e===Na:e===Aa,e===oo)}function a2(e,t,n,r){const a=n?e===Aa:e===Na,i=e===G5;return t==="both"||t==="horizontal"&&r&&r>1?e===r7e:co(t,a,i)}function a7e(e,t){const{open:n,onOpenChange:r,elements:a,floatingId:i}=e,{listRef:o,activeIndex:s,onNavigate:l=()=>{},enabled:u=!0,selectedIndex:d=null,allowEscape:p=!1,loop:m=!1,nested:h=!1,rtl:g=!1,virtual:f=!1,focusItemOnOpen:w="auto",focusItemOnHover:v=!0,openOnArrowKeyDown:k=!0,disabledIndices:_=void 0,orientation:E="vertical",parentOrientation:S,cols:x=1,scrollItemIntoView:D=!0,virtualItemRef:P,itemSizes:C,dense:L=!1}=t;process.env.NODE_ENV!=="production"&&(p&&(m||Vo("`useListNavigation` looping must be enabled to allow escaping."),f||Vo("`useListNavigation` must be virtual to allow escaping.")),E==="vertical"&&x>1&&Vo("In grid list navigation mode (`cols` > 1), the `orientation` should",'be either "horizontal" or "both".'));const G=D5(a.floating),X=Rn(G),J=so(),K=lo();gt(()=>{e.dataRef.current.orientation=E},[e,E]);const R=Vt(()=>{l(z.current===-1?null:z.current)}),B=V6e(a.domReference),H=te.useRef(w),z=te.useRef(d??-1),j=te.useRef(null),A=te.useRef(!0),Y=te.useRef(R),ee=te.useRef(!!a.floating),O=te.useRef(n),se=te.useRef(!1),ge=te.useRef(!1),ke=Rn(_),Te=Rn(n),qe=Rn(D),Ke=Rn(d),[re,_e]=te.useState(),[Ge,We]=te.useState(),Ce=Vt(()=>{function ce(q){if(f){var Z;(Z=q.id)!=null&&Z.endsWith("-fui-option")&&(q.id=i+"-"+Math.random().toString(16).slice(2,10)),_e(q.id),K?.events.emit("virtualfocus",q),P&&(P.current=q)}else K8e(q,{sync:se.current,preventScroll:!0})}const Me=o.current[z.current],ye=ge.current;Me&&ce(Me),(se.current?q=>q():requestAnimationFrame)(()=>{const q=o.current[z.current]||Me;if(!q)return;Me||ce(q);const Z=qe.current;Z&&Se&&(ye||!A.current)&&(q.scrollIntoView==null||q.scrollIntoView(typeof Z=="boolean"?{block:"nearest",inline:"nearest"}:Z))})});gt(()=>{u&&(n&&a.floating?H.current&&d!=null&&(ge.current=!0,z.current=d,R()):ee.current&&(z.current=-1,Y.current()))},[u,n,a.floating,d,R]),gt(()=>{if(u&&n&&a.floating)if(s==null){if(se.current=!1,Ke.current!=null)return;if(ee.current&&(z.current=-1,Ce()),(!O.current||!ee.current)&&H.current&&(j.current!=null||H.current===!0&&j.current==null)){let ce=0;const Me=()=>{o.current[0]==null?(ce<2&&(ce?requestAnimationFrame:queueMicrotask)(Me),ce++):(z.current=j.current==null||Zo(j.current,E,g)||h?Bo(o,ke.current):Ph(o,ke.current),j.current=null,R())};Me()}}else sa(o,s)||(z.current=s,Ce(),ge.current=!1)},[u,n,a.floating,s,Ke,h,o,E,g,R,Ce,ke]),gt(()=>{var ce;if(!u||a.floating||!K||f||!ee.current)return;const Me=K.nodesRef.current,ye=(ce=Me.find(Z=>Z.id===J))==null||(ce=ce.context)==null?void 0:ce.elements.floating,Fe=ma(dn(a.floating)),q=Me.some(Z=>Z.context&&fr(Z.context.elements.floating,Fe));ye&&!q&&A.current&&ye.focus({preventScroll:!0})},[u,a.floating,K,J,f]),gt(()=>{if(!u||!K||!f||J)return;function ce(Me){We(Me.id),P&&(P.current=Me)}return K.events.on("virtualfocus",ce),()=>{K.events.off("virtualfocus",ce)}},[u,K,f,J,P]),gt(()=>{Y.current=R,O.current=n,ee.current=!!a.floating}),gt(()=>{n||(j.current=null,H.current=w)},[n,w]);const Re=s!=null,Se=te.useMemo(()=>{function ce(ye){if(!Te.current)return;const Fe=o.current.indexOf(ye);Fe!==-1&&z.current!==Fe&&(z.current=Fe,R())}return{onFocus(ye){let{currentTarget:Fe}=ye;se.current=!0,ce(Fe)},onClick:ye=>{let{currentTarget:Fe}=ye;return Fe.focus({preventScroll:!0})},onMouseMove(ye){let{currentTarget:Fe}=ye;se.current=!0,ge.current=!1,v&&ce(Fe)},onPointerLeave(ye){let{pointerType:Fe}=ye;if(!(!A.current||Fe==="touch")&&(se.current=!0,!!v&&(z.current=-1,R(),!f))){var q;(q=X.current)==null||q.focus({preventScroll:!0})}}}},[Te,X,v,o,R,f]),Be=te.useCallback(()=>{var ce;return S??(K==null||(ce=K.nodesRef.current.find(Me=>Me.id===J))==null||(ce=ce.context)==null||(ce=ce.dataRef)==null?void 0:ce.current.orientation)},[J,K,S]),de=Vt(ce=>{if(A.current=!1,se.current=!0,ce.which===229||!Te.current&&ce.currentTarget===X.current)return;if(h&&a2(ce.key,E,g,x)){Ha(ce.key,Be())||Xt(ce),r(!1,ce.nativeEvent,"list-navigation"),xt(a.domReference)&&(f?K?.events.emit("virtualfocus",a.domReference):a.domReference.focus());return}const Me=z.current,ye=Bo(o,_),Fe=Ph(o,_);if(B||(ce.key==="Home"&&(Xt(ce),z.current=ye,R()),ce.key==="End"&&(Xt(ce),z.current=Fe,R())),x>1){const q=C||Array.from({length:o.current.length},()=>({width:1,height:1})),Z=r8e(q,x,L),ne=Z.findIndex(De=>De!=null&&!gi(o,De,_)),pe=Z.reduce((De,mt,bt)=>mt!=null&&!gi(o,mt,_)?bt:De,-1),Ee=Z[n8e({current:Z.map(De=>De!=null?o.current[De]:null)},{event:ce,orientation:E,loop:m,rtl:g,cols:x,disabledIndices:i8e([...(typeof _!="function"?_:null)||o.current.map((De,mt)=>gi(o,mt,_)?mt:void 0),void 0],Z),minIndex:ne,maxIndex:pe,prevIndex:a8e(z.current>Fe?ye:z.current,q,Z,x,ce.key===oo?"bl":ce.key===(g?Na:Aa)?"tr":"tl"),stopEvent:!0})];if(Ee!=null&&(z.current=Ee,R()),E==="both")return}if(Ha(ce.key,E)){if(Xt(ce),n&&!f&&ma(ce.currentTarget.ownerDocument)===ce.currentTarget){z.current=Zo(ce.key,E,g)?ye:Fe,R();return}Zo(ce.key,E,g)?m?z.current=Me>=Fe?p&&Me!==o.current.length?-1:ye:kt(o,{startingIndex:Me,disabledIndices:_}):z.current=Math.min(Fe,kt(o,{startingIndex:Me,disabledIndices:_})):m?z.current=Me<=ye?p&&Me!==-1?o.current.length:Fe:kt(o,{startingIndex:Me,decrement:!0,disabledIndices:_}):z.current=Math.max(ye,kt(o,{startingIndex:Me,decrement:!0,disabledIndices:_})),sa(o,z.current)&&(z.current=-1),R()}}),et=te.useMemo(()=>f&&n&&Re&&{"aria-activedescendant":Ge||re},[f,n,Re,Ge,re]),tt=te.useMemo(()=>({"aria-orientation":E==="both"?void 0:E,...B?{}:et,onKeyDown:de,onPointerMove(){A.current=!0}}),[et,de,E,B]),je=te.useMemo(()=>{function ce(ye){w==="auto"&&Y6e(ye.nativeEvent)&&(H.current=!0)}function Me(ye){H.current=w,w==="auto"&&Z6e(ye.nativeEvent)&&(H.current=!0)}return{...et,onKeyDown(ye){A.current=!1;const Fe=ye.key.startsWith("Arrow"),q=["Home","End"].includes(ye.key),Z=Fe||q,ne=r2(ye.key,E,g),pe=a2(ye.key,E,g,x),Ee=r2(ye.key,Be(),g),De=Ha(ye.key,E),mt=(h?Ee:De)||ye.key==="Enter"||ye.key.trim()==="";if(f&&n){const ht=K?.nodesRef.current.find(It=>It.parentId==null),Mt=K&&ht?W6e(K.nodesRef.current,ht.id):null;if(Z&&Mt&&P){const It=new KeyboardEvent("keydown",{key:ye.key,bubbles:!0});if(ne||pe){var bt,Hn;const D7=((bt=Mt.context)==null?void 0:bt.elements.domReference)===ye.currentTarget,Ch=pe&&!D7?(Hn=Mt.context)==null?void 0:Hn.elements.domReference:ne?o.current.find(Rh=>Rh?.id===re):null;Ch&&(Xt(ye),Ch.dispatchEvent(It),We(void 0))}if((De||q)&&Mt.context&&Mt.context.open&&Mt.parentId&&ye.currentTarget!==Mt.context.elements.domReference){var jn;Xt(ye),(jn=Mt.context.elements.domReference)==null||jn.dispatchEvent(It);return}}return de(ye)}if(!(!n&&!k&&Fe)){if(mt){const ht=Ha(ye.key,Be());j.current=h&&ht?null:ye.key}if(h){Ee&&(Xt(ye),n?(z.current=Bo(o,ke.current),R()):r(!0,ye.nativeEvent,"list-navigation"));return}De&&(d!=null&&(z.current=d),Xt(ye),!n&&k?r(!0,ye.nativeEvent,"list-navigation"):de(ye),n&&R())}},onFocus(){n&&!f&&(z.current=-1,R())},onPointerDown:Me,onPointerEnter:Me,onMouseDown:ce,onClick:ce}},[re,et,x,de,ke,w,o,h,R,r,n,k,E,Be,g,d,K,f,P]);return te.useMemo(()=>u?{reference:je,floating:tt,item:Se}:{},[u,je,tt,Se])}const i7e=new Map([["select","listbox"],["combobox","listbox"],["label",!1]]);function Qd(e,t){var n,r;t===void 0&&(t={});const{open:a,elements:i,floatingId:o}=e,{enabled:s=!0,role:l="dialog"}=t,u=Kd(),d=((n=i.domReference)==null?void 0:n.id)||u,p=te.useMemo(()=>{var k;return((k=D5(i.floating))==null?void 0:k.id)||o},[i.floating,o]),m=(r=i7e.get(l))!=null?r:l,g=so()!=null,f=te.useMemo(()=>m==="tooltip"||l==="label"?{["aria-"+(l==="label"?"labelledby":"describedby")]:a?p:void 0}:{"aria-expanded":a?"true":"false","aria-haspopup":m==="alertdialog"?"dialog":m,"aria-controls":a?p:void 0,...m==="listbox"&&{role:"combobox"},...m==="menu"&&{id:d},...m==="menu"&&g&&{role:"menuitem"},...l==="select"&&{"aria-autocomplete":"none"},...l==="combobox"&&{"aria-autocomplete":"list"}},[m,p,g,a,d,l]),w=te.useMemo(()=>{const k={id:p,...m&&{role:m}};return m==="tooltip"||l==="label"?k:{...k,...m==="menu"&&{"aria-labelledby":d}}},[m,p,d,l]),v=te.useCallback(k=>{let{active:_,selected:E}=k;const S={role:"option",..._&&{id:p+"-fui-option"}};switch(l){case"select":case"combobox":return{...S,"aria-selected":E}}return{}},[p,l]);return te.useMemo(()=>s?{reference:f,floating:w,item:v}:{},[s,f,w,v])}const bn=({content:e,children:t,placement:n="top",delay:r=300,disabled:a=!1,className:i=""})=>{const[o,s]=V.useState(!1),{refs:l,floatingStyles:u,context:d,isPositioned:p}=Zd({open:o,onOpenChange:s,placement:n,strategy:"absolute",whileElementsMounted:jd,middleware:[Vd(8),Wd(),Gd({padding:8})]}),m=W8e(d,{delay:{open:r,close:0},enabled:!a}),h=n7e(d,{enabled:!a}),g=Yd(d,{enabled:!0,outsidePress:!0,outsidePressEvent:"mousedown",referencePress:!0,referencePressEvent:"mousedown",escapeKey:!0,ancestorScroll:!0}),f=Qd(d,{role:"tooltip"}),{getReferenceProps:w,getFloatingProps:v}=Xd([m,h,g,f]);return V.useEffect(()=>{if(!o||a)return;const k=()=>{s(!1)};return window.addEventListener("scroll",k,!0),document.addEventListener("scroll",k,!0),()=>{window.removeEventListener("scroll",k,!0),document.removeEventListener("scroll",k,!0)}},[o,a]),a||!e?N.jsx(N.Fragment,{children:t}):N.jsxs(N.Fragment,{children:[N.jsx("span",{ref:l.setReference,...w(),children:t}),o&&N.jsx(Z8e,{children:N.jsx("div",{ref:l.setFloating,style:{...u,opacity:p?1:0,pointerEvents:"none",transition:p?"opacity 0.15s ease-out":"none"},className:`mp-agent-tooltip ${i}`.trim(),...v(),children:e})})]})},nn=({icon:e,size:t="md",iconSize:n,type:r="button",className:a="",tooltip:i,tooltipPlacement:o,...s})=>{const l=e6e[e],u=n??(t==="sm"?14:20),d=N.jsx("button",{type:r,className:`mp-agent-icon-button mp-agent-icon-button-${t} ${a}`.trim(),...s,children:l&&N.jsx(l,{size:u})});return i?N.jsx(bn,{content:i,placement:o,children:d}):d},Jd=({text:e})=>{const[t,n]=V.useState(!1),r=async()=>{try{await navigator.clipboard.writeText(e),n(!0),setTimeout(()=>n(!1),2e3)}catch(a){console.error("Failed to copy:",a)}};return N.jsx(bn,{content:"Copy to clipboard",children:N.jsx(nn,{icon:t?"Check":"Copy",onClick:r,"aria-label":"Copy message",size:"sm"})})},Wt=()=>{const e=He();return{...Ni,...e.config.translations??{}}},i2=300,Z5=V.memo(({field:e,isExpanded:t,canApply:n,onToggleExpand:r,onApply:a})=>{const i=Wt(),o=e.value.length>i2,s=o&&!t?`${e.value.slice(0,i2)}...`:e.value,l=V.useCallback(()=>{r(e.name)},[e.name,r]),u=V.useCallback(()=>{a(e)},[e,a]);return N.jsxs("div",{className:"mp-agent-form-proposal-row",children:[N.jsxs("div",{className:"mp-agent-form-proposal-main",children:[N.jsx("div",{className:"mp-agent-form-proposal-label",children:e.label||e.name}),N.jsx("div",{className:"mp-agent-form-proposal-value-container",children:N.jsxs("div",{className:"mp-agent-form-proposal-value",children:[s,o&&N.jsx("button",{type:"button",onClick:l,className:"mp-agent-form-proposal-show-all",children:t?i.formProposalShowLess:i.formProposalShowAll})]})})]}),N.jsxs("div",{className:"mp-agent-form-proposal-actions-row",children:[N.jsx(nn,{icon:"Check",onClick:u,tooltip:`${i.formProposalApplyFieldPrefix} ${e.label||e.name}`,size:"sm"}),N.jsx(Jd,{text:e.value})]})]})});Z5.displayName="FormFieldRow";const Ca=30*1e3,Ra=5*60*1e3,X5=20,Ht={all:["mp-agents","activities"],lists:()=>[...Ht.all,"list"],list:e=>[...Ht.lists(),e],infinites:()=>[...Ht.all,"infinite"],infinite:e=>[...Ht.infinites(),e],sourceTypes:e=>[...Ht.all,"sourceTypes",e],detail:e=>[...Ht.all,"detail",e],summary:e=>[...Ht.all,"summary",e]},o7e=e=>e?.pages.flatMap(t=>t.data)??[],Q5=(e,t,n)=>{const r=e.from instanceof Date?e.from.toISOString():e.from,a=e.to instanceof Date?e.to.toISOString():e.to;return{...e.groupId&&{groupId:e.groupId},...e.parentId&&{parentId:e.parentId},...e.sourceType&&{sourceType:e.sourceType},...e.sortField&&e.sortOrder&&{sort:{field:e.sortField,order:e.sortOrder}},...r&&{from:r},...a&&{to:a},...e.tenant&&{tenant:e.tenant},...e.ownerId&&{ownerId:e.ownerId},skip:t,limit:n}},J5=e=>({data:[],cursor:{total:0,skip:0,limit:e}}),s7e=e=>{const t=He(),{groupId:n,parentId:r,sourceType:a,enabled:i=!0,sortOrder:o=exports.SortOrder.Desc,sortField:s="createdAt",pageSize:l=X5,from:u,to:d,tenant:p,ownerId:m}=e??{};return yt.useInfiniteQuery({queryKey:Ht.infinite({groupId:n,parentId:r,sourceType:a,sortField:s,sortOrder:o,pageSize:l,from:u,to:d,tenant:p,ownerId:m}),queryFn:async({pageParam:h})=>t.transport.listActivities?t.transport.listActivities(Q5({groupId:n,parentId:r,sourceType:a,sortField:s,sortOrder:o,from:u,to:d,tenant:p,ownerId:m},h,l)):J5(l),initialPageParam:0,getNextPageParam:h=>{const g=(h.cursor.skip??0)+h.data.length;return g<h.cursor.total?g:void 0},enabled:i&&!!t.transport.listActivities,staleTime:Ca,gcTime:Ra})},l7e=e=>{const t=He(),{groupId:n,parentId:r,sourceType:a,page:i,enabled:o=!0,sortOrder:s=exports.SortOrder.Desc,sortField:l="createdAt",pageSize:u=X5,from:d,to:p,tenant:m,ownerId:h}=e,g=(i-1)*u,f=yt.useQuery({queryKey:Ht.list({groupId:n,parentId:r,sourceType:a,sortField:l,sortOrder:s,pageSize:u,page:i,from:d,to:p,tenant:m,ownerId:h}),queryFn:async()=>t.transport.listActivities?t.transport.listActivities(Q5({groupId:n,parentId:r,sourceType:a,sortField:l,sortOrder:s,from:d,to:p,tenant:m,ownerId:h},g,u)):J5(u),enabled:o&&!!t.transport.listActivities&&i>=1,staleTime:Ca,gcTime:Ra}),w=f.data?.cursor.total??0,v=Math.max(1,Math.ceil(w/u));return{...f,page:i,pageSize:u,totalPages:v,total:w,hasNextPage:i<v,hasPreviousPage:i>1}},c7e=e=>{const t=He();return yt.useQuery({queryKey:Ht.detail(e),queryFn:async()=>!e||!t.transport.getActivity?null:t.transport.getActivity(e),enabled:!!e&&!!t.transport.getActivity,staleTime:Ca,gcTime:Ra})},u7e=e=>{const t=He(),{enabled:n=!0,...r}=e??{};return yt.useQuery({queryKey:Ht.summary(r),queryFn:async()=>t.transport.getActivitySummary?t.transport.getActivitySummary(r):[],enabled:n&&!!t.transport.getActivitySummary,staleTime:Ca,gcTime:Ra})},d7e=e=>{const t=He(),{enabled:n=!0,groupId:r,parentId:a,from:i,to:o,tenant:s,ownerId:l}=e??{},u=i instanceof Date?i.toISOString():i,d=o instanceof Date?o.toISOString():o;return yt.useQuery({queryKey:Ht.sourceTypes({groupId:r,parentId:a,from:u,to:d,tenant:s,ownerId:l}),queryFn:async()=>t.transport.listActivitySourceTypes?t.transport.listActivitySourceTypes({...r&&{groupId:r},...a&&{parentId:a},...u&&{from:u},...d&&{to:d},...s&&{tenant:s},...l&&{ownerId:l}}):[],enabled:n&&!!t.transport.listActivitySourceTypes,staleTime:Ca,gcTime:Ra})},o2="mp-agents-guest-user-id";function Hr(){if(typeof window>"u")return`${Ai.DefaultUserId}-${_t.nanoid()}`;const e=localStorage.getItem(o2);if(e)return e;const t=`${Ai.DefaultUserId}-${_t.nanoid()}`;return localStorage.setItem(o2,t),t}const e3=30*1e3,t3=5*60*1e3,uo=20,In={all:["mp-agents","chats"],lists:()=>[...In.all,"list"],list:e=>[...In.lists(),e],infinites:()=>[...In.all,"infinite"],infinite:e=>[...In.infinites(),e],detail:e=>[...In.all,"detail",e]},n3=e=>e?.pages.flatMap(t=>t.data)??[],ep=e=>{const t=He(),n=t.config.user?.id??Hr(),r=t.config.appId,{pageSize:a=uo,sortOrder:i="desc",sortField:o="updatedAt",multiUser:s,enabled:l=!0}=e??{};return yt.useInfiniteQuery({queryKey:In.infinite({userId:n,appId:r,sortField:o,sortOrder:i,pageSize:a,multiUser:s}),queryFn:async({pageParam:u})=>await t.transport.listChats({userId:n,skip:u,limit:a,multiUser:s,sortOrder:i,sortField:o}),initialPageParam:0,getNextPageParam:u=>{const{cursor:d,data:p}=u,m=(d.skip??0)+p.length;return m<d.total?m:void 0},enabled:l&&!!n,staleTime:e3,gcTime:t3})},r3=ep,p7e=e=>{const t=He(),n=t.config.user?.id??Hr(),r=t.config.appId,{page:a,pageSize:i=uo,sortOrder:o="desc",sortField:s="updatedAt",multiUser:l,enabled:u=!0}=e,d=(a-1)*i,p=yt.useQuery({queryKey:In.list({userId:n,appId:r,sortField:s,sortOrder:o,pageSize:i,page:a,multiUser:l}),queryFn:async()=>t.transport.listChats({userId:n,skip:d,limit:i,multiUser:l,sortOrder:o,sortField:s}),enabled:u&&!!n&&a>=1,staleTime:e3,gcTime:t3}),m=p.data?.cursor.total??0,h=Math.max(1,Math.ceil(m/i));return{...p,page:a,pageSize:i,totalPages:h,total:m,hasNextPage:a<h,hasPreviousPage:a>1}},tp=e=>{const t=r3(e),n=be(r=>r.hydrateChats);return V.useEffect(()=>{if(t.data?.pages){const r=t.data.pages.flatMap(a=>a.data);n(r)}},[t.data,n]),t},h7e=(e={},t=[])=>{const{threshold:n=50,scrollOnMount:r=!0,observeMutations:a=!0}=e,i=V.useRef(null),o=V.useRef(null),[s,l]=V.useState(!0),u=V.useRef(!1),d=V.useRef(!1),p=V.useRef(),m=V.useCallback(()=>{const f=i.current;if(!f)return!1;const{scrollTop:w,scrollHeight:v,clientHeight:k}=f;return v-w-k<=n},[n]),h=V.useCallback(()=>{const f=i.current,w=o.current;!f||!w||w.scrollIntoView({behavior:"auto",block:"end"})},[]),g=V.useCallback(()=>{const f=m();l(f),f&&(u.current=!1)},[m]);return V.useEffect(()=>{const f=i.current;if(!f)return;let w=f.scrollTop,v;const k=()=>{const _=f.scrollTop;if(!d.current){const E=_<w,S=_>w;(E||S&&!m())&&(u.current=!0)}w=_,g(),v&&clearTimeout(v),v=window.setTimeout(()=>{d.current=!1},150)};return f.addEventListener("scroll",k,{passive:!0}),()=>{f.removeEventListener("scroll",k),v&&clearTimeout(v)}},[m,g]),V.useEffect(()=>{if(!a)return;const f=i.current;if(!f)return;const w=new MutationObserver(()=>{!u.current&&s&&(p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{d.current=!0,h(),setTimeout(()=>{d.current=!1},50)})),g()});return w.observe(f,{childList:!0,subtree:!0,characterData:!0,attributes:!1}),()=>{w.disconnect(),p.current&&cancelAnimationFrame(p.current)}},[s,a,h,g]),V.useEffect(()=>{t.length!==0&&!u.current&&s&&(p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{d.current=!0,h(),setTimeout(()=>{d.current=!1},50)}))},[...t]),V.useEffect(()=>{if(r&&i.current){const f=window.setTimeout(()=>{d.current=!0,h(),setTimeout(()=>{d.current=!1},50)},100);return()=>{clearTimeout(f)}}},[r,h]),{containerRef:i,sentinelRef:o,isNearBottom:s,scrollToBottom:h,checkIsNearBottom:m}},a3=()=>{const e=He();return yt.useQuery({queryKey:["mp-agents","models"],queryFn:async()=>e.transport.listModels?await e.transport.listModels():[],staleTime:5*60*1e3,refetchOnWindowFocus:!1})},ja=e=>e.type===exports.AgentAttachmentType.Context&&e?.metadata?.kind==="pageContext";var vt=(e=>(e.Idle="idle",e.Sending="sending",e.Streaming="streaming",e))(vt||{});const Di=e=>e===exports.AgentStatus.Streaming||e===exports.AgentStatus.Processing||e===exports.AgentStatus.WaitingForUserAction?"streaming":"idle",i3=()=>({messages:[],reasoning:[],artifacts:[],pendingAssistant:void 0,messageQueue:[],composerDraft:{value:"",attachments:[]},composerError:void 0,pageContextDismissed:!1,status:"idle"}),$e=(e,t)=>e.chatState[t]??i3(),m7e=e=>r5.create()((t,n)=>({contextKey:e,activeChatId:void 0,draftChatKey:`draft-${_t.nanoid()}`,chats:{},chatState:{},isChatHistoryOpen:!1,composer:{temperature:.4},setContextKey:r=>t({contextKey:r}),setActiveChat:r=>{t(a=>{let i=a.contextKey,o;if(r){const u=a.chats[r];u?.contextKey&&(i=u.contextKey),o=u?.model}const s=a.activeChatId!==r;return{activeChatId:r,contextKey:i,composer:r&&s?{...a.composer,model:o}:a.composer}})},upsertChat:r=>t(a=>{const i=a.chats[r.id],s=a.activeChatId===r.id&&(!i||i.model!==r.model);return{chats:{...a.chats,[r.id]:r},...s?{composer:{...a.composer,model:r.model}}:{}}}),upsertChatState:(r,a)=>t(i=>{const o=$e(i,r),s=typeof a=="function"?a(o):a,l={...o,...s};return{chatState:{...i.chatState,[r]:l}}}),hydrateChats:r=>t(a=>{const i={};r.forEach(u=>{i[u.id]=u});const o=a.activeChatId??r[0]?.id;o&&!i[o]&&a.chats[o]&&(i[o]=a.chats[o]);const l=o?i[o]:void 0;return{chats:i,activeChatId:o,composer:{...a.composer,model:l?.model}}}),removeChat:r=>t(a=>{if(!a.chats[r])return a;const{[r]:i,...o}=a.chats,{[r]:s,...l}=a.chatState,u=a.activeChatId===r;return{chats:o,chatState:l,...u?{activeChatId:void 0}:{}}}),pushReasoning:(r,a)=>t(i=>{const o=$e(i,r);return{chatState:{...i.chatState,[r]:{...o,reasoning:[...o.reasoning,a]}}}}),setArtifacts:(r,a)=>t(i=>{const o=$e(i,r);return{chatState:{...i.chatState,[r]:{...o,artifacts:a}}}}),setComposerOptions:r=>t(a=>({composer:{...a.composer,...r}})),setComposerDraft:(r,a)=>t(i=>{const o=$e(i,r);return{chatState:{...i.chatState,[r]:{...o,composerDraft:{value:a.value??"",attachments:a.attachments??[]}}}}}),setComposerValue:(r,a)=>t(i=>{const o=$e(i,r);return{chatState:{...i.chatState,[r]:{...o,composerDraft:{...o.composerDraft,value:a}}}}}),addComposerAttachments:(r,a)=>t(i=>{const o=$e(i,r),s=o.composerDraft.attachments??[];if(!a||a.length===0)return i;const l=s.find(ja),u=a.find(ja);if(u){const m=a.filter(v=>!ja(v)),h=s.filter(v=>!ja(v)),f=[l?{...u,id:l.id}:u,...m,...h],w=new Map;for(const v of f)w.set(v.id,v);return{chatState:{...i.chatState,[r]:{...o,composerDraft:{...o.composerDraft,attachments:Array.from(w.values())}}}}}const d=[...a,...s],p=new Map;for(const m of d)p.set(m.id,m);return{chatState:{...i.chatState,[r]:{...o,composerDraft:{...o.composerDraft,attachments:Array.from(p.values())}}}}}),removeComposerAttachment:(r,a)=>t(i=>{const o=$e(i,r);return{chatState:{...i.chatState,[r]:{...o,composerDraft:{...o.composerDraft,attachments:o.composerDraft.attachments.filter(s=>s.id!==a)}}}}}),clearComposerDraft:r=>t(a=>{const i=$e(a,r);return{chatState:{...a.chatState,[r]:{...i,composerDraft:{value:"",attachments:[]}}}}}),setComposerError:(r,a)=>t(i=>{const o=$e(i,r);return{chatState:{...i.chatState,[r]:{...o,composerError:a}}}}),setPageContextDismissed:(r,a)=>t(i=>{const o=$e(i,r);return{chatState:{...i.chatState,[r]:{...o,pageContextDismissed:a}}}}),setChatStatus:(r,a)=>t(i=>{const o=$e(i,r);return{chatState:{...i.chatState,[r]:{...o,status:a}}}}),setPendingAssistant:(r,a)=>t(i=>{const o=$e(i,r);return{chatState:{...i.chatState,[r]:{...o,pendingAssistant:a}}}}),commitPendingAssistant:r=>t(a=>{const i=$e(a,r),o=i.pendingAssistant;if(!o)return a;if(!a.chats[r])return{chatState:{...a.chatState,[r]:{...i,pendingAssistant:void 0}}};const u=typeof o.content=="string"&&o.content.trim().length>0?(()=>{if(i.messages[i.messages.length-1]?.id===o.id)return i.messages;const p={...o,chat:r};return[...i.messages,p]})():i.messages;return{chatState:{...a.chatState,[r]:{...i,messages:u,pendingAssistant:void 0}}}}),enqueueQueuedMessage:(r,a,i)=>t(o=>{const s=$e(o,r),l={id:_t.nanoid(),content:a,...i&&i.length>0?{attachments:i}:{},createdAt:new Date().toISOString()};return{chatState:{...o.chatState,[r]:{...s,messageQueue:[...s.messageQueue,l]}}}}),removeQueuedMessage:(r,a)=>t(i=>{const o=$e(i,r);if(o.messageQueue.length===0)return i;const s=o.messageQueue.filter(l=>l.id!==a);return{chatState:{...i.chatState,[r]:{...o,messageQueue:s}}}}),moveChatKeyState:(r,a)=>t(i=>{if(r===a)return i;const o=$e(i,r),s=$e(i,a);if(!(o.messageQueue.length>0||!!o.pendingAssistant||o.status!=="idle"||o.composerDraft.value.length>0||o.composerDraft.attachments.length>0||!!o.composerError))return i;const u=o.composerDraft.value.length>0||o.composerDraft.attachments.length>0,d=s.composerDraft.value.length>0||s.composerDraft.attachments.length>0,p={messages:s.messages,reasoning:s.reasoning,artifacts:s.artifacts,pendingAssistant:o.pendingAssistant??s.pendingAssistant,messageQueue:[...s.messageQueue,...o.messageQueue],composerDraft:u&&!d?o.composerDraft:s.composerDraft,composerError:o.composerError??s.composerError,pageContextDismissed:i.chatState[a]?s.pageContextDismissed:o.pageContextDismissed,status:o.status??s.status};return{chatState:{...i.chatState,[a]:p,[r]:i3()}}}),appendSystemMessage:(r,a)=>t(i=>{const o=$e(i,r),s={id:_t.nanoid(),chat:r,content:a,role:exports.MessageRole.System,createdAt:new Date().toISOString()};return{chatState:{...i.chatState,[r]:{...o,messages:[...o.messages,s]}}}}),upsertToolCall:(r,a)=>t(i=>{const o=$e(i,r),s=[...o.messages],l=s.findIndex(u=>u.role===exports.MessageRole.Tool&&u.toolCalls?.some(d=>d.id===a.id));if(l>=0){const u=s[l],d=(u.toolCalls??[]).map(p=>p.id===a.id?a:p);s[l]={...u,toolCalls:d}}else s.push({id:`tool-${a.id}`,content:"",chat:r,toolCalls:[a],role:exports.MessageRole.Tool,createdAt:new Date().toISOString()});return{chatState:{...i.chatState,[r]:{...o,messages:s}}}}),setChatHistoryOpen:r=>t({isChatHistoryOpen:r}),toggleChatHistory:()=>t(r=>({isChatHistoryOpen:!r.isChatHistoryOpen})),setChatMessages:(r,a)=>t(i=>{const o=$e(i,r),s=o.messages??[],l=typeof a=="function"?a(s):a;return{chatState:{...i.chatState,[r]:{...o,messages:l}}}}),appendMessagesToChat:(r,a)=>t(i=>{const o=$e(i,r);if(a.length===0)return i;const s=new Set(a.map(d=>d.id)),u=[...o.messages.filter(d=>!s.has(d.id)),...a].sort((d,p)=>d.createdAt.localeCompare(p.createdAt));return{chatState:{...i.chatState,[r]:{...o,messages:u}}}})})),o3=()=>{const e=be(s=>s.activeChatId??s.draftChatKey),t=be(s=>$e(s,e).composerDraft),n=be(s=>s.setComposerValue),r=be(s=>s.setComposerDraft),a=be(s=>s.clearComposerDraft),i=be(s=>s.addComposerAttachments),o=be(s=>s.removeComposerAttachment);return{chatKey:e,draft:t,setValue:s=>n(e,s),setDraft:s=>r(e,s),clearDraft:()=>a(e),addAttachments:s=>i(e,s),removeAttachment:s=>o(e,s)}},s3=e=>{const t=He();return yt.useQuery({queryKey:["mp-agents","configurations",e??"all"],queryFn:async()=>t.transport.listAgentConfigurations?t.transport.listAgentConfigurations(e):[],staleTime:6e4,refetchOnWindowFocus:!1})},f7e=(e,t=[])=>{const n=He(),r=V.useRef(e),a=V.useCallback(e,t);r.current=a;const i=V.useCallback(o=>r.current(o),[]);V.useEffect(()=>n.registerPageContextProvider(i),[n,i])},l3=e=>{const t=He();return V.useCallback(r=>{t.events.dispatchEvent(new CustomEvent(e,{detail:r}))},[t,e])},c3=(e,t,n=[],r)=>{const a=He(),i=V.useRef(t),o=V.useCallback(t,n);i.current=o;const s=V.useCallback(u=>{i.current(u)},[]),l=typeof r=="boolean"?r:r?.capture;V.useEffect(()=>(a.events.addEventListener(e,s,r),()=>{a.events.removeEventListener(e,s,l)}),[a,e,s,l])},g7e=({formId:e,onApply:t,enabled:n=!0})=>{c3(Pd,r=>{n&&r.detail.formId===e&&t(r.detail)},[n,e,t])},y7e=["mp-agents","configurations"],u3=()=>{const e=He(),t=yt.useQueryClient(),n=()=>t.invalidateQueries({queryKey:y7e}),r=yt.useMutation({mutationFn:async({agentName:i,input:o})=>{if(!e.transport.upsertAgentPreferences)throw new Error("upsertAgentPreferences is not supported by this transport");return e.transport.upsertAgentPreferences(i,o)},onSuccess:n}),a=yt.useMutation({mutationFn:async i=>{if(!e.transport.upsertAgentPreferencesBatch)throw new Error("upsertAgentPreferencesBatch is not supported by this transport");return e.transport.upsertAgentPreferencesBatch(i)},onSuccess:n});return{upsertSingle:r,upsertBatch:a}},d3=()=>{const e=He(),t=be(s=>s.activeChatId),n=be(s=>s.upsertChat),r=be(s=>s.setActiveChat),a=be(s=>s.setChatStatus),i=!!t,o=yt.useQuery({queryKey:["mp-agents","chat",t],queryFn:()=>e.transport.getChat(t),enabled:i,staleTime:6e4,retry:!1});return V.useEffect(()=>{o.data&&(n(o.data),a(o.data.id,Di(o.data.status)))},[o.data,n,a]),V.useEffect(()=>{o.isError&&t&&r(void 0)},[o.isError,t,r]),o},p3=20,np=e=>{const t=He(),n=t.config.messagesPageSize??p3,r=be(o=>o.setChatMessages),a=be(o=>!!(e&&o.chats[e])),i=yt.useInfiniteQuery({queryKey:["mp-agents","messages",e,n],queryFn:async({pageParam:o})=>{if(!e||!t.transport.getMessages)throw new Error("No chat or transport");return await t.transport.getMessages(e,{limit:n,...o?{before:o}:{}})},initialPageParam:void 0,getNextPageParam:o=>o.hasMore&&o.messages.length>0?o.messages[0]?.id:void 0,enabled:!!e&&!!t.transport.getMessages&&a,retry:!1});return V.useEffect(()=>{if(!e||!i.data?.pages)return;const s=i.data.pages.slice().reverse().flatMap(u=>u.messages),l=new Set(s.map(u=>u.id));r(e,u=>{const d=u.filter(p=>!l.has(p.id));return[...s,...d]})},[e,i.data,r]),i},rp=()=>{const e=He(),t=e.config.user?.id??Hr(),n=be(u=>u.activeChatId),r=be(u=>u.removeChat),a=be(u=>u.setActiveChat),[i,o]=V.useState(new Set),s=V.useCallback(async u=>{o(d=>new Set(d).add(u));try{await e.transport.deleteChat(u),r(u),n===u&&a(void 0),e.queryClient.invalidateQueries({queryKey:["mp-agents","chats",t]})}finally{o(d=>{const p=new Set(d);return p.delete(u),p})}},[n,r,e.queryClient,e.transport,a,t]),l=V.useCallback(u=>i.has(u),[i]);return{deleteChat:s,isDeleting:l}},b7e=e=>{if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);if(typeof e=="object")try{return JSON.stringify(e)}catch{return String(e)}return String(e)},k7e=e=>{const t=e.output??e.input??{},n=Array.isArray(t.fields)?t.fields.map(r=>({name:typeof r?.name=="string"?r.name:"",label:typeof r?.label=="string"?r.label:void 0,value:b7e(r?.value),inputType:typeof r?.inputType=="string"?r.inputType:void 0,options:Array.isArray(r?.options)?r.options:void 0})).filter(r=>r.name.length>0):[];return{formId:typeof t.formId=="string"?t.formId:void 0,formName:typeof t.formName=="string"?t.formName:void 0,fields:n,notes:typeof t.notes=="string"?t.notes:void 0}},h3=({call:e,chatId:t,applyAllButtonText:n,showStatus:r=!0})=>{const a=He(),i=l3(Pd),o=Wt(),s=V.useMemo(()=>k7e(e),[e]),[l,u]=V.useState(new Set),d=V.useMemo(()=>{const x=(e.output??{})?._mp?.lastAction,D=typeof x?.action=="string"?x.action:void 0,P=typeof x?.at=="string"?x.at:void 0;return{action:D,at:P}},[e.output]),p=V.useMemo(()=>d.action==="apply",[d.action]),m=V.useMemo(()=>d.action==="reject",[d.action]),h=V.useMemo(()=>e.status===exports.AgentToolCallStatus.Succeeded&&!!s.formId&&s.fields.length>0&&!p,[e.status,s.formId,s.fields.length,p]);V.useMemo(()=>e.status===exports.AgentToolCallStatus.Succeeded&&!!s.formId&&s.fields.length>0&&!p&&!m,[e.status,s.formId,s.fields.length,p,m]);const g=V.useCallback(async E=>{s.formId&&a.transport.recordToolCallAction&&await a.transport.recordToolCallAction(t,{toolCallId:e.id,action:E.action,data:{formId:s.formId,formName:s.formName,fields:E.fields},systemMessage:E.action==="apply"?`Applied ${E.fields.length} field(s) to ${s.formName??s.formId}.`:`Rejected ${s.formName??s.formId} suggestion.`},{excludeSocketId:!1})},[s.formId,s.formName,t,e.id,a.transport]),f=V.useCallback(async E=>{if(s.formId){i({fields:E,chatId:t,toolCallId:e.id,formId:s.formId,...s.formName?{formName:s.formName}:{}});try{await g({action:"apply",fields:E})}catch{return}}},[s.formId,s.formName,t,e.id,i,g]);V.useCallback(async()=>{if(s.formId)try{await g({action:"reject",fields:s.fields})}catch{return}},[s.formId,s.fields,g]);const w=V.useCallback(E=>{u(S=>{if(S.has(E)){if(S.size===1)return new Set;const x=new Set(S);return x.delete(E),x}else{const x=new Set(S);return x.add(E),x}})},[]),v=V.useCallback(E=>{f([E])},[f]),k=V.useCallback(()=>{f(s.fields)},[f,s.fields]),_=s.formName?`${o.formProposalHeaderPrefix} ${s.formName}`:`${o.formProposalHeaderPrefix} ${s.formId}`;return e.status===exports.AgentToolCallStatus.Failed&&e.error?N.jsx("div",{className:"mp-agent-tool-body",children:N.jsx("div",{className:"mp-agent-tool-simple-message",children:o.formProposalFailed})}):e.status!==exports.AgentToolCallStatus.Succeeded?N.jsx("div",{className:"mp-agent-tool-simple-message",children:o.formProposalPreparing}):!s.formId||s.fields.length===0?N.jsx("div",{className:"mp-agent-tool-simple-message",children:o.formProposalNone}):N.jsxs("div",{className:"mp-agent-tool-body",children:[N.jsx("div",{className:"mp-agent-tool-simple-message",children:_}),s.notes?N.jsx("div",{className:"mp-agent-tool-simple-message",children:s.notes}):null,N.jsx("div",{className:"mp-agent-form-proposal-fields",children:s.fields.map(E=>N.jsx(Z5,{field:E,isExpanded:l.has(E.name),canApply:h,onToggleExpand:w,onApply:v},E.name))}),N.jsxs("div",{className:"mp-agent-form-proposal-actions",children:[r&&(p||m)&&N.jsxs("div",{className:"mp-agent-form-proposal-status",children:[N.jsx("span",{className:`mp-agent-form-proposal-badge ${p?"is-applied":"is-rejected"}`,children:p?o.formProposalApplied:o.formProposalRejected}),d.at?N.jsx("span",{className:"mp-agent-form-proposal-status-time",children:N.jsx(r6e,{date:d.at})}):null]}),N.jsxs("button",{type:"button",onClick:k,className:"mp-agent-form-proposal-apply-all",children:[N.jsx(b5,{size:14})," ",n||o.formProposalApplyAll]})]})]})},po=e=>{const{id:t,name:n,url:r,capturedAt:a,source:i,security:o,target:s,kind:l,...u}=e,d=r??i?.url,p=i||d?{...i??{},...d?{url:d}:{}}:void 0,m=l==="webSnippet"||l==="formSnapshot"||l==="formField"?!0:void 0,h=o||(m!==void 0?{containsPII:m,redactionsApplied:[]}:void 0),g=typeof n=="string"&&n.trim().length?n.trim():l==="webSnippet"?u?.title?`Selection: ${String(u.title)}`:"Selection":l==="formField"?"Form field":l==="formSnapshot"?"Form snapshot":"Context";return{id:t??_t.nanoid(),type:exports.AgentAttachmentType.Context,name:g,...d?{url:d}:{},metadata:{schemaVersion:1,kind:l,capturedAt:a??new Date().toISOString(),...p?{source:p}:{},...h?{security:h}:{},...s?{target:s}:{},...u}}},v7e=e=>{try{const t=new URL(e),n=`${t.searchParams.toString()} ${t.hash}`.toLowerCase();return/(token|key|auth|session|code|password|secret|email)/.test(n)}catch{return/(token|key|auth|session|code|password|secret|email)/.test(e.toLowerCase())}},m3=(e={})=>{if(typeof window>"u")return;const t=e.url??window.location?.href;if(!t)return;const n=e.includeTitle!==!1,r=e.includeReferrer!==!1,a=e.includeViewport!==!1,i=e.includeUserAgent===!0,o=n&&typeof document<"u"?document.title:void 0,s=r&&typeof document<"u"?document.referrer:void 0;let l;try{l=new URL(t)}catch{}const u={url:t,...l?{origin:l.origin,pathname:l.pathname,search:l.search,hash:l.hash}:{},...n&&o?{title:o}:{},...r&&s?{referrer:s}:{},...i&&typeof navigator<"u"?{userAgent:navigator.userAgent}:{},...typeof navigator<"u"&&navigator.language?{language:navigator.language}:{},...typeof Intl<"u"?{timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,locale:Intl.DateTimeFormat().resolvedOptions().locale}:{},...a&&typeof window<"u"?{viewport:{width:window.innerWidth,height:window.innerHeight,devicePixelRatio:window.devicePixelRatio}}:{},...e.extra?e.extra:{}},d=v7e(t)?!0:void 0;return po({kind:"pageContext",name:e.name??"Page context",url:t,title:o,data:u,summary:l?`${l.pathname}${l.search}${l.hash}`:void 0,source:{app:"browser",url:t,route:l?`${l.pathname}${l.search}${l.hash}`:void 0},...d?{security:{containsPII:!0,redactionsApplied:[]}}:{}})},f3=()=>{if(typeof window>"u"||typeof document>"u")return;const e=window.getSelection?.();if(!e||e.rangeCount===0)return;const t=e.getRangeAt(0),n=e.toString().trim();if(!n)return;const r=(t.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?t.commonAncestorContainer:t.commonAncestorContainer.parentElement)??void 0,a=r?_7e(r):void 0,i=r?.textContent??"",o=i.indexOf(n),s=o>=0?o:void 0,l=o>=0?o+n.length:void 0,u=o>=0?i.slice(Math.max(0,o-80),o).trim():void 0,d=o>=0?i.slice(o+n.length,o+n.length+80).trim():void 0;return{selectedText:n,target:{type:"text",exact:n,...u?{prefix:u}:{},...d?{suffix:d}:{},...a?{domPath:a}:{},...s!==void 0?{startOffset:s}:{},...l!==void 0?{endOffset:l}:{}}}},_7e=e=>{if(e.id)return`#${s2(e.id)}`;const t=[];let n=e;for(;n&&n.nodeType===1&&t.length<6;){const r=n.tagName.toLowerCase();if(n.id){t.unshift(`#${s2(n.id)}`);break}const a=n.parentElement;if(!a){t.unshift(r);break}const o=Array.from(a.children).filter(s=>s.tagName===n.tagName).indexOf(n)+1;t.unshift(`${r}:nth-of-type(${o})`),n=a}return t.join(" > ")},s2=e=>e.replace(/[^a-zA-Z0-9_-]/g,"\\$&");class g3{constructor(t){this.rawConfig=t,this.events=new EventTarget;const n=Wu.parse(t);this.config={...n,toolRenderers:t.toolRenderers,tools:t.tools,pageContext:t.pageContext?{...n.pageContext,...t.pageContext}:n.pageContext,translations:t.translations?{...Ni,...t.translations}:Ni,transport:t.transport.onError?{...n.transport,onError:t.transport.onError}:n.transport},this.transport=this.createTransport(this.config.transport),this.tools=new J7(this.config.tools),this.tools.bindInvoke(this.invokeTool.bind(this)),this.configureTransportAfterCreate(this.transport),Object.entries(t.toolRenderers??{}).forEach(([r,a])=>{a&&this.toolRendererMap.set(r,a)}),this.toolRendererMap.has("propose_form_values")||this.toolRendererMap.set("propose_form_values",h3),this.queryClient=new yt.QueryClient({defaultOptions:{queries:{staleTime:3e4,refetchOnWindowFocus:!1}}})}config;transport;tools;queryClient;events;socketClient=null;toolRendererMap=new Map;storeRef;pageContextProviders=new Set;createTransport(t){return t.mode==="proxy"?new Or(t):new $o(t)}configureTransportAfterCreate(t){this.config.transport.mode==="direct"&&t instanceof $o&&(t.setToolRegistry(this.tools),t.setContextKeys(this.config.contextKeys.map(n=>({key:n.key,tools:n.tools}))),this.config.models&&t.setModels(this.config.models),t.setUntitledChatText(this.config.translations.untitledChat))}updateTransportConfig(t){const n=Wu.parse({...this.rawConfig,transport:t}),r=this.config.transport,a=this.transport;this.rawConfig={...this.rawConfig,transport:t},this.config.transport=t.onError?{...n.transport,onError:t.onError}:n.transport;const i=this.config.transport.mode;if(r.mode!==i){a.cancelStream?.(),this.transport=this.createTransport(this.config.transport),this.configureTransportAfterCreate(this.transport),this.events.dispatchEvent(new CustomEvent("runtime:transport-config-changed",{detail:{previous:r,next:this.config.transport}}));return}i==="proxy"&&a instanceof Or?a.updateConfig(this.config.transport):i==="direct"&&a instanceof $o?(a.updateConfig(this.config.transport),this.configureTransportAfterCreate(a)):(a.cancelStream?.(),this.transport=this.createTransport(this.config.transport),this.configureTransportAfterCreate(this.transport)),this.events.dispatchEvent(new CustomEvent("runtime:transport-config-changed",{detail:{previous:r,next:this.config.transport}}))}setTransportHeaders(t){const n=this.config.transport;this.updateTransportConfig({...n,headers:t})}mergeTransportHeaders(t){const n=this.config.transport;this.updateTransportConfig({...n,headers:{...n.headers??{},...t}})}removeTransportHeaders(t){const n=this.config.transport;if(!n.headers||t.length===0)return;const r={...n.headers};for(const a of t)delete r[a];this.updateTransportConfig({...n,headers:Object.keys(r).length?r:void 0})}get defaultContextKey(){return this.config.defaultContextKey??this.config.contextKeys[0]?.key}get store(){if(!this.storeRef)throw new Error("AgentRuntime store has not been attached yet");return this.storeRef}attachStore(t){this.storeRef=t}get socket(){return this.socketClient}setSocketClient(t){this.socketClient!==t&&(this.socketClient=t,this.events.dispatchEvent(new CustomEvent("runtime:socket-changed",{detail:{socket:t}})))}registerTool(t){this.tools.register(t)}registerToolRenderer(t,n){this.toolRendererMap.set(t,n)}registerPageContextProvider(t){return this.pageContextProviders.add(t),()=>{this.pageContextProviders.delete(t)}}getPageContextInput(){if(typeof window>"u")return{};const t=window.location?.href;let n;if(t)try{const a=new URL(t);n=`${a.pathname}${a.search}${a.hash}`}catch{}const r=typeof document<"u"?document.title:void 0;return{url:t,route:n,title:r}}getPageContextData(t){const n=t??this.getPageContextInput(),r={};let a=!1;const i=this.config.pageContext?.getData;if(i)try{const o=i(n);o&&typeof o=="object"&&(Object.assign(r,o),a=!0)}catch{}for(const o of this.pageContextProviders)try{const s=o(n);s&&typeof s=="object"&&(Object.assign(r,s),a=!0)}catch{}return a?r:void 0}buildPageContextAttachment(){const t=this.config.pageContext,n=this.getPageContextData();return m3({...t?.includeUserAgent!==void 0?{includeUserAgent:t.includeUserAgent}:{},...t?.includeReferrer!==void 0?{includeReferrer:t.includeReferrer}:{},...t?.includeViewport!==void 0?{includeViewport:t.includeViewport}:{},...t?.includeTitle!==void 0?{includeTitle:t.includeTitle}:{},...t?.name?{name:t.name}:{},...n?{extra:n}:{}})}getToolRenderer(t){return this.toolRendererMap.get(t.name)}ensureStore(t){if(!this.storeRef)throw new Error(`Cannot ${t} before AgentRuntime is mounted`);return this.storeRef}resolveChatId(t){const r=this.ensureStore("invoke tools").getState(),a=t?.chatId??r.activeChatId;if(!a||!r.chats[a])throw new Error("Tool invocation requires an active chat. Select or create a chat first.");return a}buildToolContext(t){const n=this.ensureStore("create tool context");return{chatId:t,agentId:this.config.appId,workspaceId:this.config.workspaceId,appendSystemMessage:r=>{n.getState().appendSystemMessage(t,r)}}}writeToolCall(t,n){this.ensureStore("write tool call").getState().upsertToolCall(t,{...n})}async invokeTool(t,n={},r){const a=this.resolveChatId(r),i={id:_t.nanoid(),name:t,input:n,status:exports.AgentToolCallStatus.Running};this.writeToolCall(a,i);const o=this.buildToolContext(a);try{const s=await this.tools.execute(t,n,o,i);return this.writeToolCall(a,s),s}catch(s){const l={...i,status:exports.AgentToolCallStatus.Failed,error:s instanceof Error?s.message:"Unknown tool error"};throw this.writeToolCall(a,l),s}}}const w7e={background:"#050505",surface:"#0f0f11",text:"#f7f7f7",subtext:"#8f9baa",border:"#1f2229",accent:"#6c63ff",accentSoft:"rgba(108, 99, 255, 0.14)",warning:"#ffb347",danger:"#ff5f56",fontFamily:'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',radius:"12px",fontSize:"14px",colorMode:"light"},y3=e=>({...w7e,...e}),b3=V.createContext(y3()),x7e=e=>({"--mp-agents-bg":e.background,"--mp-agents-surface":e.surface,"--mp-agents-text":e.text,"--mp-agents-subtext":e.subtext,"--mp-agents-border":e.border,"--mp-agents-accent":e.accent,"--mp-agents-accent-soft":e.accentSoft,"--mp-agents-warning":e.warning,"--mp-agents-danger":e.danger,"--mp-agents-radius":e.radius,"--mp-agents-font-size":e.fontSize}),k3=({value:e,children:t})=>{const n=V.useMemo(()=>y3(e),[e]);return N.jsxs(b3.Provider,{value:n,children:[N.jsx("style",{children:`:root {
8291
8291
  ${Object.entries(x7e(n)).map(([r,a])=>`${r}: ${a};`).join(`
8292
8292
  `)}
8293
- }`}),t]})},v3=()=>V.useContext(b3),l2="mp-agent-selected-model",ta="__auto__";function _3(e){return e.mode==="direct"?`${l2}-${e.mode}-${e.provider}`:`${l2}-${e.mode}`}function c2(e,t){try{const n=_3(e);localStorage.setItem(n,t)}catch(n){console.warn("Failed to save selected model to localStorage:",n)}}function E7e(e){try{const t=_3(e);return localStorage.getItem(t)}catch(t){return console.warn("Failed to load selected model from localStorage:",t),null}}function w3(e,t){return!e||e.length===0?[]:t.mode==="direct"&&t.provider!=="custom"?e.filter(n=>n.provider?n.provider===t.provider:!0):e}function M7e(e,t,n){const r=E7e(t);if(r){if(r===ta)return;if(w3(e,t).some(i=>i.id===r))return r}}const S7e="mp-agents-last-active-chat";function x3(e){return`${S7e}-${e}`}function E3(e){return typeof e=="string"&&e.length>0&&e.length<256}function N7e(e){if(typeof window>"u")return null;try{const t=localStorage.getItem(x3(e));return t&&E3(t)?t:null}catch{return null}}function A7e(e,t){if(!(typeof window>"u"))try{const n=x3(e);t&&E3(t)?localStorage.setItem(n,t):localStorage.removeItem(n)}catch{}}const wn=Object.create(null);wn.open="0";wn.close="1";wn.ping="2";wn.pong="3";wn.message="4";wn.upgrade="5";wn.noop="6";const bi=Object.create(null);Object.keys(wn).forEach(e=>{bi[wn[e]]=e});const ed={type:"error",data:"parser error"},M3=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",S3=typeof ArrayBuffer=="function",N3=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ap=({type:e,data:t},n,r)=>M3&&t instanceof Blob?n?r(t):u2(t,r):S3&&(t instanceof ArrayBuffer||N3(t))?n?r(t):u2(new Blob([t]),r):r(wn[e]+(t||"")),u2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function d2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Xo;function T7e(e,t){if(M3&&e.data instanceof Blob)return e.data.arrayBuffer().then(d2).then(t);if(S3&&(e.data instanceof ArrayBuffer||N3(e.data)))return t(d2(e.data));ap(e,!1,n=>{Xo||(Xo=new TextEncoder),t(Xo.encode(n))})}const p2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",na=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<p2.length;e++)na[p2.charCodeAt(e)]=e;const C7e=e=>{let t=e.length*.75,n=e.length,r,a=0,i,o,s,l;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const u=new ArrayBuffer(t),d=new Uint8Array(u);for(r=0;r<n;r+=4)i=na[e.charCodeAt(r)],o=na[e.charCodeAt(r+1)],s=na[e.charCodeAt(r+2)],l=na[e.charCodeAt(r+3)],d[a++]=i<<2|o>>4,d[a++]=(o&15)<<4|s>>2,d[a++]=(s&3)<<6|l&63;return u},R7e=typeof ArrayBuffer=="function",ip=(e,t)=>{if(typeof e!="string")return{type:"message",data:A3(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:I7e(e.substring(1),t)}:bi[n]?e.length>1?{type:bi[n],data:e.substring(1)}:{type:bi[n]}:ed},I7e=(e,t)=>{if(R7e){const n=C7e(e);return A3(n,t)}else return{base64:!0,data:e}},A3=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},T3="",O7e=(e,t)=>{const n=e.length,r=new Array(n);let a=0;e.forEach((i,o)=>{ap(i,!1,s=>{r[o]=s,++a===n&&t(r.join(T3))})})},L7e=(e,t)=>{const n=e.split(T3),r=[];for(let a=0;a<n.length;a++){const i=ip(n[a],t);if(r.push(i),i.type==="error")break}return r};function D7e(){return new TransformStream({transform(e,t){T7e(e,n=>{const r=n.length;let a;if(r<126)a=new Uint8Array(1),new DataView(a.buffer).setUint8(0,r);else if(r<65536){a=new Uint8Array(3);const i=new DataView(a.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{a=new Uint8Array(9);const i=new DataView(a.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(a[0]|=128),t.enqueue(a),t.enqueue(n)})}})}let Qo;function Va(e){return e.reduce((t,n)=>t+n.length,0)}function Ga(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let a=0;a<t;a++)n[a]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function z7e(e,t){Qo||(Qo=new TextDecoder);const n=[];let r=0,a=-1,i=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(Va(n)<1)break;const l=Ga(n,1);i=(l[0]&128)===128,a=l[0]&127,a<126?r=3:a===126?r=1:r=2}else if(r===1){if(Va(n)<2)break;const l=Ga(n,2);a=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),r=3}else if(r===2){if(Va(n)<8)break;const l=Ga(n,8),u=new DataView(l.buffer,l.byteOffset,l.length),d=u.getUint32(0);if(d>Math.pow(2,21)-1){s.enqueue(ed);break}a=d*Math.pow(2,32)+u.getUint32(4),r=3}else{if(Va(n)<a)break;const l=Ga(n,a);s.enqueue(ip(i?l:Qo.decode(l),t)),r=0}if(a===0||a>e){s.enqueue(ed);break}}}})}const C3=4;function ct(e){if(e)return $7e(e)}function $7e(e){for(var t in ct.prototype)e[t]=ct.prototype[t];return e}ct.prototype.on=ct.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};ct.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};ct.prototype.off=ct.prototype.removeListener=ct.prototype.removeAllListeners=ct.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var r,a=0;a<n.length;a++)if(r=n[a],r===t||r.fn===t){n.splice(a,1);break}return n.length===0&&delete this._callbacks["$"+e],this};ct.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){n=n.slice(0);for(var r=0,a=n.length;r<a;++r)n[r].apply(this,t)}return this};ct.prototype.emitReserved=ct.prototype.emit;ct.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};ct.prototype.hasListeners=function(e){return!!this.listeners(e).length};const ho=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),Qt=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),F7e="arraybuffer";function R3(e,...t){return t.reduce((n,r)=>(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const P7e=Qt.setTimeout,q7e=Qt.clearTimeout;function mo(e,t){t.useNativeTimers?(e.setTimeoutFn=P7e.bind(Qt),e.clearTimeoutFn=q7e.bind(Qt)):(e.setTimeoutFn=Qt.setTimeout.bind(Qt),e.clearTimeoutFn=Qt.clearTimeout.bind(Qt))}const B7e=1.33;function U7e(e){return typeof e=="string"?H7e(e):Math.ceil((e.byteLength||e.size)*B7e)}function H7e(e){let t=0,n=0;for(let r=0,a=e.length;r<a;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}function I3(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function j7e(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function V7e(e){let t={},n=e.split("&");for(let r=0,a=n.length;r<a;r++){let i=n[r].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}class G7e extends Error{constructor(t,n,r){super(t),this.description=n,this.context=r,this.type="TransportError"}}class op extends ct{constructor(t){super(),this.writable=!1,mo(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,n,r){return super.emitReserved("error",new G7e(t,n,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const n=ip(t,this.socket.binaryType);this.onPacket(n)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,n={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(n)}_hostname(){const t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){const n=j7e(t);return n.length?"?"+n:""}}class W7e extends op{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const n=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let r=0;this._polling&&(r++,this.once("pollComplete",function(){--r||n()})),this.writable||(r++,this.once("drain",function(){--r||n()}))}else n()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};L7e(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,O7e(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=I3()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}}let O3=!1;try{O3=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const K7e=O3;function Y7e(){}class Z7e extends W7e{constructor(t){if(super(t),typeof location<"u"){const n=location.protocol==="https:";let r=location.port;r||(r=n?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||r!==t.port}}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(a,i)=>{this.onError("xhr post error",a,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,r)=>{this.onError("xhr poll error",n,r)}),this.pollXhr=t}}class _n extends ct{constructor(t,n,r){super(),this.createRequest=t,mo(this,r),this._opts=r,this._method=r.method||"GET",this._uri=n,this._data=r.data!==void 0?r.data:null,this._create()}_create(){var t;const n=R3(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this._opts.xd;const r=this._xhr=this.createRequest(n);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let a in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(a)&&r.setRequestHeader(a,this._opts.extraHeaders[a])}}catch{}if(this._method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(r),"withCredentials"in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var a;r.readyState===3&&((a=this._opts.cookieJar)===null||a===void 0||a.parseCookies(r.getResponseHeader("set-cookie"))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status=="number"?r.status:0)},0))},r.send(this._data)}catch(a){this.setTimeoutFn(()=>{this._onError(a)},0);return}typeof document<"u"&&(this._index=_n.requestsCount++,_n.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Y7e,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete _n.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}_n.requestsCount=0;_n.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",h2);else if(typeof addEventListener=="function"){const e="onpagehide"in Qt?"pagehide":"unload";addEventListener(e,h2,!1)}}function h2(){for(let e in _n.requests)_n.requests.hasOwnProperty(e)&&_n.requests[e].abort()}const X7e=function(){const e=L3({xdomain:!1});return e&&e.responseType!==null}();class Q7e extends Z7e{constructor(t){super(t);const n=t&&t.forceBase64;this.supportsBinary=X7e&&!n}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new _n(L3,this.uri(),t)}}function L3(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||K7e))return new XMLHttpRequest}catch{}if(!t)try{return new Qt[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const D3=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class J7e extends op{get name(){return"websocket"}doOpen(){const t=this.uri(),n=this.opts.protocols,r=D3?{}:R3(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,n,r)}catch(a){return this.emitReserved("error",a)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n<t.length;n++){const r=t[n],a=n===t.length-1;ap(r,this.supportsBinary,i=>{try{this.doWrite(r,i)}catch{}a&&ho(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=I3()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}}const Jo=Qt.WebSocket||Qt.MozWebSocket;class e_e extends J7e{createSocket(t,n,r){return D3?new Jo(t,n,r):n?new Jo(t,n):new Jo(t)}doWrite(t,n){this.ws.send(n)}}class t_e extends op{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const n=z7e(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),a=D7e();a.readable.pipeTo(t.writable),this._writer=a.writable.getWriter();const i=()=>{r.read().then(({done:s,value:l})=>{s||(this.onPacket(l),i())}).catch(s=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let n=0;n<t.length;n++){const r=t[n],a=n===t.length-1;this._writer.write(r).then(()=>{a&&ho(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const n_e={websocket:e_e,webtransport:t_e,polling:Q7e},r_e=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,a_e=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function td(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let a=r_e.exec(e||""),i={},o=14;for(;o--;)i[a_e[o]]=a[o]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=i_e(i,i.path),i.queryKey=o_e(i,i.query),i}function i_e(e,t){const n=/\/{2,9}/g,r=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&r.splice(0,1),t.slice(-1)=="/"&&r.splice(r.length-1,1),r}function o_e(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,a,i){a&&(n[a]=i)}),n}const nd=typeof addEventListener=="function"&&typeof removeEventListener=="function",ki=[];nd&&addEventListener("offline",()=>{ki.forEach(e=>e())},!1);class Qn extends ct{constructor(t,n){if(super(),this.binaryType=F7e,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(n=t,t=null),t){const r=td(t);n.hostname=r.host,n.secure=r.protocol==="https"||r.protocol==="wss",n.port=r.port,r.query&&(n.query=r.query)}else n.host&&(n.hostname=td(n.host).host);mo(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},n.transports.forEach(r=>{const a=r.prototype.name;this.transports.push(a),this._transportsByName[a]=r}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=V7e(this.opts.query)),nd&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},ki.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=C3,n.transport=t,this.id&&(n.sid=this.id);const r=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](r)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&Qn.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",n=>this._onClose("transport close",n))}onOpen(){this.readyState="open",Qn.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const n=new Error("server error");n.code=t.data,this._onError(n);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let r=0;r<this.writeBuffer.length;r++){const a=this.writeBuffer[r].data;if(a&&(n+=U7e(a)),r>0&&n>this._maxPayload)return this.writeBuffer.slice(0,r);n+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,ho(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,n,r){return this._sendPacket("message",t,n,r),this}send(t,n,r){return this._sendPacket("message",t,n,r),this}_sendPacket(t,n,r,a){if(typeof n=="function"&&(a=n,n=void 0),typeof r=="function"&&(a=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),a&&this.once("flush",a),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},r=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():t()}):this.upgrading?r():t()),this}_onError(t){if(Qn.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,n){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),nd&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const r=ki.indexOf(this._offlineEventListener);r!==-1&&ki.splice(r,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this._prevBufferLen=0}}}Qn.protocol=C3;class s_e extends Qn{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let n=this.createTransport(t),r=!1;Qn.priorWebsocketSuccess=!1;const a=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",p=>{if(!r)if(p.type==="pong"&&p.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;Qn.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(d(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const m=new Error("probe error");m.transport=n.name,this.emitReserved("upgradeError",m)}}))};function i(){r||(r=!0,d(),n.close(),n=null)}const o=p=>{const m=new Error("probe error: "+p);m.transport=n.name,i(),this.emitReserved("upgradeError",m)};function s(){o("transport closed")}function l(){o("socket closed")}function u(p){n&&p.name!==n.name&&i()}const d=()=>{n.removeListener("open",a),n.removeListener("error",o),n.removeListener("close",s),this.off("close",l),this.off("upgrading",u)};n.once("open",a),n.once("error",o),n.once("close",s),this.once("close",l),this.once("upgrading",u),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const n=[];for(let r=0;r<t.length;r++)~this.transports.indexOf(t[r])&&n.push(t[r]);return n}}let l_e=class extends s_e{constructor(t,n={}){const r=typeof t=="object"?t:n;(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(a=>n_e[a]).filter(a=>!!a)),super(t,r)}};function c_e(e,t="",n){let r=e;n=n||typeof location<"u"&&location,e==null&&(e=n.protocol+"//"+n.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=n.protocol+e:e=n.host+e),/^(https?|wss?):\/\//.test(e)||(typeof n<"u"?e=n.protocol+"//"+e:e="https://"+e),r=td(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const i=r.host.indexOf(":")!==-1?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+t,r.href=r.protocol+"://"+i+(n&&n.port===r.port?"":":"+r.port),r}const u_e=typeof ArrayBuffer=="function",d_e=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,z3=Object.prototype.toString,p_e=typeof Blob=="function"||typeof Blob<"u"&&z3.call(Blob)==="[object BlobConstructor]",h_e=typeof File=="function"||typeof File<"u"&&z3.call(File)==="[object FileConstructor]";function sp(e){return u_e&&(e instanceof ArrayBuffer||d_e(e))||p_e&&e instanceof Blob||h_e&&e instanceof File}function vi(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,r=e.length;n<r;n++)if(vi(e[n]))return!0;return!1}if(sp(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return vi(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&vi(e[n]))return!0;return!1}function m_e(e){const t=[],n=e.data,r=e;return r.data=rd(n,t),r.attachments=t.length,{packet:r,buffers:t}}function rd(e,t){if(!e)return e;if(sp(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}else if(Array.isArray(e)){const n=new Array(e.length);for(let r=0;r<e.length;r++)n[r]=rd(e[r],t);return n}else if(typeof e=="object"&&!(e instanceof Date)){const n={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=rd(e[r],t));return n}return e}function f_e(e,t){return e.data=ad(e.data,t),delete e.attachments,e}function ad(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}else if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=ad(e[n],t);else if(typeof e=="object")for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=ad(e[n],t));return e}const g_e=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],y_e=5;var Pe;(function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"})(Pe||(Pe={}));class b_e{constructor(t){this.replacer=t}encode(t){return(t.type===Pe.EVENT||t.type===Pe.ACK)&&vi(t)?this.encodeAsBinary({type:t.type===Pe.EVENT?Pe.BINARY_EVENT:Pe.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let n=""+t.type;return(t.type===Pe.BINARY_EVENT||t.type===Pe.BINARY_ACK)&&(n+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(n+=t.nsp+","),t.id!=null&&(n+=t.id),t.data!=null&&(n+=JSON.stringify(t.data,this.replacer)),n}encodeAsBinary(t){const n=m_e(t),r=this.encodeAsString(n.packet),a=n.buffers;return a.unshift(r),a}}function m2(e){return Object.prototype.toString.call(e)==="[object Object]"}class lp extends ct{constructor(t){super(),this.reviver=t}add(t){let n;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");n=this.decodeString(t);const r=n.type===Pe.BINARY_EVENT;r||n.type===Pe.BINARY_ACK?(n.type=r?Pe.EVENT:Pe.ACK,this.reconstructor=new k_e(n),n.attachments===0&&super.emitReserved("decoded",n)):super.emitReserved("decoded",n)}else if(sp(t)||t.base64)if(this.reconstructor)n=this.reconstructor.takeBinaryData(t),n&&(this.reconstructor=null,super.emitReserved("decoded",n));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let n=0;const r={type:Number(t.charAt(0))};if(Pe[r.type]===void 0)throw new Error("unknown packet type "+r.type);if(r.type===Pe.BINARY_EVENT||r.type===Pe.BINARY_ACK){const i=n+1;for(;t.charAt(++n)!=="-"&&n!=t.length;);const o=t.substring(i,n);if(o!=Number(o)||t.charAt(n)!=="-")throw new Error("Illegal attachments");r.attachments=Number(o)}if(t.charAt(n+1)==="/"){const i=n+1;for(;++n&&!(t.charAt(n)===","||n===t.length););r.nsp=t.substring(i,n)}else r.nsp="/";const a=t.charAt(n+1);if(a!==""&&Number(a)==a){const i=n+1;for(;++n;){const o=t.charAt(n);if(o==null||Number(o)!=o){--n;break}if(n===t.length)break}r.id=Number(t.substring(i,n+1))}if(t.charAt(++n)){const i=this.tryParse(t.substr(n));if(lp.isPayloadValid(r.type,i))r.data=i;else throw new Error("invalid payload")}return r}tryParse(t){try{return JSON.parse(t,this.reviver)}catch{return!1}}static isPayloadValid(t,n){switch(t){case Pe.CONNECT:return m2(n);case Pe.DISCONNECT:return n===void 0;case Pe.CONNECT_ERROR:return typeof n=="string"||m2(n);case Pe.EVENT:case Pe.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&g_e.indexOf(n[0])===-1);case Pe.ACK:case Pe.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class k_e{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const n=f_e(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const v_e=Object.freeze(Object.defineProperty({__proto__:null,Decoder:lp,Encoder:b_e,get PacketType(){return Pe},protocol:y_e},Symbol.toStringTag,{value:"Module"}));function cn(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const __e=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class $3 extends ct{constructor(t,n,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=n,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[cn(t,"open",this.onopen.bind(this)),cn(t,"packet",this.onpacket.bind(this)),cn(t,"error",this.onerror.bind(this)),cn(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...n){var r,a,i;if(__e.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(n.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(n),this;const o={type:Pe.EVENT,data:n};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const d=this.ids++,p=n.pop();this._registerAckCallback(d,p),o.id=d}const s=(a=(r=this.io.engine)===null||r===void 0?void 0:r.transport)===null||a===void 0?void 0:a.writable,l=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!s||(l?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(t,n){var r;const a=(r=this.flags.timeout)!==null&&r!==void 0?r:this._opts.ackTimeout;if(a===void 0){this.acks[t]=n;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let s=0;s<this.sendBuffer.length;s++)this.sendBuffer[s].id===t&&this.sendBuffer.splice(s,1);n.call(this,new Error("operation has timed out"))},a),o=(...s)=>{this.io.clearTimeoutFn(i),n.apply(this,s)};o.withError=!0,this.acks[t]=o}emitWithAck(t,...n){return new Promise((r,a)=>{const i=(o,s)=>o?a(o):r(s);i.withError=!0,n.push(i),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((a,...i)=>r!==this._queue[0]?void 0:(a!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(a)):(this._queue.shift(),n&&n(null,...i)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:Pe.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(r=>String(r.id)===t)){const r=this.acks[t];delete this.acks[t],r.withError&&r.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case Pe.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Pe.EVENT:case Pe.BINARY_EVENT:this.onevent(t);break;case Pe.ACK:case Pe.BINARY_ACK:this.onack(t);break;case Pe.DISCONNECT:this.ondisconnect();break;case Pe.CONNECT_ERROR:this.destroy();const r=new Error(t.data.message);r.data=t.data.data,this.emitReserved("connect_error",r);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const r of n)r.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let r=!1;return function(...a){r||(r=!0,n.packet({type:Pe.ACK,id:t,data:a}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(delete this.acks[t.id],n.withError&&t.data.unshift(null),n.apply(this,t.data))}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Pe.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let r=0;r<n.length;r++)if(t===n[r])return n.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const n=this._anyOutgoingListeners;for(let r=0;r<n.length;r++)if(t===n[r])return n.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const n=this._anyOutgoingListeners.slice();for(const r of n)r.apply(this,t.data)}}}function jr(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}jr.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0};jr.prototype.reset=function(){this.attempts=0};jr.prototype.setMin=function(e){this.ms=e};jr.prototype.setMax=function(e){this.max=e};jr.prototype.setJitter=function(e){this.jitter=e};class id extends ct{constructor(t,n){var r;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,mo(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((r=n.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new jr({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const a=n.parser||v_e;this.encoder=new a.Encoder,this.decoder=new a.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new l_e(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const a=cn(n,"open",function(){r.onopen(),t&&t()}),i=s=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",s),t?t(s):this.maybeReconnectOnOpen()},o=cn(n,"error",i);if(this._timeout!==!1){const s=this._timeout,l=this.setTimeoutFn(()=>{a(),i(new Error("timeout")),n.close()},s);this.opts.autoUnref&&l.unref(),this.subs.push(()=>{this.clearTimeoutFn(l)})}return this.subs.push(a),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(cn(t,"ping",this.onping.bind(this)),cn(t,"data",this.ondata.bind(this)),cn(t,"error",this.onerror.bind(this)),cn(t,"close",this.onclose.bind(this)),cn(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){ho(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let r=this.nsps[t];return r?this._autoConnect&&!r.active&&r.connect():(r=new $3(this,t,n),this.nsps[t]=r),r}_destroy(t){const n=Object.keys(this.nsps);for(const r of n)if(this.nsps[r].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let r=0;r<n.length;r++)this.engine.write(n[r],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,n){var r;this.cleanup(),(r=this.engine)===null||r===void 0||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(a=>{a?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",a)):t.onreconnect()}))},n);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Zr={};function _i(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=c_e(e,t.path||"/socket.io"),r=n.source,a=n.id,i=n.path,o=Zr[a]&&i in Zr[a].nsps,s=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let l;return s?l=new id(r,t):(Zr[a]||(Zr[a]=new id(r,t)),l=Zr[a]),n.query&&!t.query&&(t.query=n.queryKey),l.socket(n.path,t)}Object.assign(_i,{Manager:id,Socket:$3,io:_i,connect:_i});const w_e=V.createContext(null),x_e=({children:e})=>{const t=He(),n=be(v=>v.upsertChat),r=be(v=>v.upsertChatState),a=be(v=>v.contextKey),i=be(v=>v.activeChatId),o=V.useMemo(()=>t.config.user?.id??Hr(),[t.config.user?.id]),s=t.config.transport,[l,u]=V.useState(null),[d,p]=V.useState(void 0),m=V.useRef(a),h=V.useRef(n),g=V.useRef(r),f=V.useRef(void 0);V.useEffect(()=>{m.current=a,h.current=n,g.current=r},[a,n,r]),V.useEffect(()=>{if(s.mode!=="proxy"){u(null),p(void 0),t.setSocketClient(null),t.transport instanceof Or&&t.transport.setSocketId(void 0);return}const v=s.baseUrl,k=new URL(v,window.location.origin),_=`${k.protocol}//${k.host}`,E=s.socketNamespace,S=E?`${_}${E}`:_,x={},D=s;D.headers&&Object.assign(x,D.headers);const P={},C=D.apiKey&&`Bearer ${D.apiKey}`||D.headers?.Authorization;C&&(P.authorization=C,x.Authorization=C);const L=s.socketPath??Ai.Path,G=_i(S,{path:L,auth:P,transports:["websocket","polling"],withCredentials:!0,...Object.keys(x).length>0&&{extraHeaders:x}});t.setSocketClient(G),u(G);const X=()=>{p(G.id),t.transport instanceof Or&&t.transport.setSocketId(G.id)},J=()=>{p(void 0),t.transport instanceof Or&&t.transport.setSocketId(void 0)},K=H=>{if(H.contextKey===m.current){h.current(H);const z=t.store.getState(),j=$e(z,H.id);g.current(H.id,{...j,status:Di(H.status)})}},R=H=>{const z=t.store.getState(),j=$e(z,H.chat),A=j.messages.findIndex(Y=>Y.id===H.id);if(A>=0){const Y=[...j.messages];Y[A]=H,g.current(H.chat,{...j,messages:Y});return}g.current(H.chat,{...j,messages:[...j.messages,H]})},B=H=>{h.current(H);const z=t.store.getState(),j=$e(z,H.id);g.current(H.id,{...j,status:Di(H.status)})};return G.on("connect",X),G.on("disconnect",J),G.on("connect_error",H=>{console.error("Socket.IO connection error:",H.message)}),G.on(fi.ChatNew,K),G.on(fi.MessageNew,R),G.on(fi.ChatUpdate,B),()=>{t.transport instanceof Or&&t.transport.setSocketId(void 0),t.setSocketClient(null),p(void 0),u(null),G.disconnect()}},[t,t.transport,s.mode,s.mode==="proxy"?s.baseUrl:void 0,s.mode==="proxy"?s.apiKey:void 0,s.mode==="proxy"?s.socketPath:void 0,s.mode==="proxy"?s.socketNamespace:void 0,s.mode==="proxy"?JSON.stringify(s.headers??{}):"",o]),V.useEffect(()=>{if(!l)return;const v=f.current;v&&v!==i&&l.emit("chat:unsubscribe",{chatId:v}),i&&i!==v&&(l.emit("chat:subscribe",{chatId:i}),f.current=i),i||(f.current=void 0)},[l,i]);const w=V.useMemo(()=>({socket:l,socketId:d}),[l,d]);return N.jsx(w_e.Provider,{value:w,children:e})},cp=V.createContext(null),E_e=({config:e,children:t})=>{const n=V.useRef();n.current||(n.current=new g3(e));const[,r]=V.useState(0);V.useEffect(()=>{const o=n.current,s=()=>r(l=>l+1);return o.events.addEventListener("runtime:transport-config-changed",s),()=>{o.events.removeEventListener("runtime:transport-config-changed",s)}},[]);const a=V.useRef();if(!a.current){const o=n.current.defaultContextKey??n.current.config.contextKeys[0]?.key??"default";a.current=m7e(o),n.current.attachStore(a.current);const s=M7e(n.current.config.models,n.current.config.transport);a.current.getState().setComposerOptions({model:s})}const i=V.useMemo(()=>({runtime:n.current,store:a.current}),[]);return V.useEffect(()=>{const o=a.current;if(!o)return;let s=o.getState().activeChatId;return o.subscribe(()=>{const l=o.getState().activeChatId;if(l===s)return;s=l;const u=n.current?.config.user?.id??Hr();A7e(u,l)})},[]),N.jsx(cp.Provider,{value:i,children:N.jsx(yt.QueryClientProvider,{client:i.runtime.queryClient,children:N.jsx(k3,{value:i.runtime.config.theme,children:N.jsx(x_e,{children:t})})})})},He=()=>{const e=V.useContext(cp);if(!e)throw new Error("useAgentRuntime must be used inside <AgentProvider />");return e.runtime},be=e=>{const t=V.useContext(cp);if(!t)throw new Error("useAgentStore must be used inside <AgentProvider />");return r5.useStore(t.store,e)},M_e=({initialSystemPrompt:e,composerFormRef:t,multiUser:n=!1,participantIds:r=[]})=>{const a=He(),{composer:i,contextKey:o,activeChatId:s,draftChatKey:l,queuedMessages:u,activeChatStatus:d,upsertChat:p,setChatStatus:m,setActiveChat:h,setComposerError:g,moveChatKeyState:f,removeQueuedMessage:w,setPendingAssistant:v,enqueueQueuedMessage:k,appendMessagesToChat:_,commitPendingAssistant:E,setPageContextDismissed:S}=be(j=>{const A=j.activeChatId??j.draftChatKey,Y=$e(j,A);return{composer:j.composer,contextKey:j.contextKey,activeChatId:j.activeChatId,draftChatKey:j.draftChatKey,queuedMessages:Y.messageQueue,activeChatStatus:Y.status,upsertChat:j.upsertChat,setActiveChat:j.setActiveChat,setChatStatus:j.setChatStatus,setComposerError:j.setComposerError,moveChatKeyState:j.moveChatKeyState,setPendingAssistant:j.setPendingAssistant,removeQueuedMessage:j.removeQueuedMessage,enqueueQueuedMessage:j.enqueueQueuedMessage,appendMessagesToChat:j.appendMessagesToChat,commitPendingAssistant:j.commitPendingAssistant,setPageContextDismissed:j.setPageContextDismissed}}),x=V.useCallback(j=>!j||j.length===0?!1:j.some(A=>A.type===exports.AgentAttachmentType.Context&&A?.metadata?.kind==="pageContext"),[]),D=V.useRef(!1),P=V.useRef(!1),C=V.useRef(void 0),L=V.useRef(new Set),G=s??l,X=V.useCallback(async(j,A)=>{if(!a.transport.generateTitle)return;const Y=a.config.features?.titleGeneration==="llm"?"llm":"local";let ee;try{ee=await a.transport.generateTitle({userId:A,content:j,strategy:Y,contextKey:o})}catch{}return ee},[a.transport,a.config.features?.titleGeneration,o]),J=V.useCallback(async(j,A=[])=>{const Y=a.config.user?.id??"guest",ee=!s,O=s??l,se={current:O};C.current=O;const ge={value:j,attachments:A};g(se.current,void 0);let ke;if(ee){const ce=await X(j,Y);ce&&ce.trim().length>0&&(ke={...ke??{},title:ce})}const Te=a.store.getState(),qe=s?Te.chats[s]:void 0,re=(s?Te.chatState[s]:void 0)?.messages??[],_e=A.filter(ce=>F3(ce)?!S_e(re,ce):!0),Ge=qe?.model,We=i.model!==Ge;let Ce,Re=!1;We?(Ce=i.model,Re=!0):Ge?(Ce=Ge,Re=!1):(Ce=void 0,Re=!1);const Se=N_e(j),Be={userId:Y,content:j,metadata:ke,contextKey:o,...ee?{}:{chatId:s},...Re?{model:Ce??""}:{},..._e.length>0?{attachments:_e}:{},...n?{mentions:Se,participantIds:Array.from(new Set([Y,...r])),senderDisplayName:a.config.user?.displayName,senderAvatarUrl:a.config.user?.avatarUrl}:{}},de=()=>{v(se.current,void 0)},et=ce=>{if(ce?.name==="AbortError"){const Me=C.current??se.current;return L.current.has(Me)?(E(se.current),L.current.delete(Me)):(de(),t.current?.setDraft(ge)),{type:"aborted"}}throw ce},tt=async()=>{m(se.current,vt.Sending);try{if(!a.transport.sendMultiUserMessage)throw new Error("Multi-user chat requires a transport that supports sendMultiUserMessage");const ce=await a.transport.sendMultiUserMessage(Be);return p(ce.chat),ee&&(f(se.current,ce.chat.id),se.current=ce.chat.id,C.current=ce.chat.id,h(ce.chat.id)),_(ce.chat.id,[ce.message]),m(ce.chat.id,Di(ce.chat.status)),de(),{type:"success"}}catch(ce){return et(ce)}},je=async()=>{let ce=`pending-${Date.now()}`,Me="",ye;m(se.current,vt.Streaming),v(se.current,{id:ce,content:"",reasoning:"",toolCalls:[],attachments:[],chat:s||"",role:exports.MessageRole.Assistant,createdAt:new Date().toISOString()});try{let Fe=s;const q=ne=>{if(ne.type===exports.StreamChunkType.Chat&&ne.chat){p(ne.chat),Fe=ne.chat.id,ee&&(C.current=ne.chat.id,f(se.current,ne.chat.id),se.current=ne.chat.id,h(ne.chat.id));return}if(ne.type===exports.StreamChunkType.Reasoning&&ne.reasoning){Me+=ne.reasoning,ye={...ye??{id:ce,chat:Fe,role:exports.MessageRole.Assistant,content:"",createdAt:new Date().toISOString()},reasoning:Me},v(se.current,ye);return}if(ne.type===exports.StreamChunkType.Error&&ne.error)throw new Error(ne.error);if(ne.message&&ne.message.role===exports.MessageRole.User){_(ne.message.chat,[ne.message]);return}ne.message&&(ce=ne.message.id,ye={...ne.message,reasoning:Me||ne.message.reasoning},v(se.current,ye)),ne.done&&(ye&&_(se.current,[ye]),m(se.current,vt.Idle),de())},Z=await a.transport.streamMessage(Be,q,{streamKey:C.current});if(Z){const ne=Z.messages.map(De=>ye&&De.id===ye.id&&De.role===exports.MessageRole.Assistant?{...De,reasoning:Me}:De);_(Z.id,ne);const pe=a.store.getState();return(pe.activeChatId??pe.draftChatKey)===se.current&&h(Z.id),de(),{type:"success"}}return de(),{type:"success"}}catch(Fe){return et(Fe)}};try{const ce=await(n?tt():je());return ce.type==="success"&&(D.current=!1),ce}catch(ce){de();const Me=ce?.chat;Me&&(p(Me),h(Me.id));const ye=ce instanceof Error?ce:new Error("Failed to send message");return g(se.current,ye.message||"Failed to send message"),m(se.current,vt.Idle),t.current?.setDraft(ge),D.current=!1,{type:"error",error:ye}}finally{P.current=!1,n||m(se.current,vt.Idle),C.current=void 0}},[s,o,i.model,n,r,a.transport,a.config.user?.displayName,a.config.user?.avatarUrl,a.config.user?.id,p,h,v,m,X,e,f,t,g]),K=V.useCallback(async()=>{if(d!==vt.Idle||P.current||!u.length||D.current)return;const j=u[0];P.current=!0,w(G,j.id);try{await J(j.content,j.attachments)}finally{P.current=!1}},[d,u,G,J,w]);V.useEffect(()=>{K()},[K]);const R=V.useCallback(async j=>{if(P.current)return;const A=u.find(Y=>Y.id===j);if(A){D.current=!1,P.current=!0,w(G,j);try{await J(A.content,A.attachments)}finally{P.current=!1}}},[u,G,w,J]),B=V.useCallback(async j=>{const Y=t.current.getDraft().attachments;if(!n&&d!==vt.Idle){k(G,j,Y),t.current?.clearDraft();return}D.current=!1,t.current?.clearDraft(),await J(j,Y)},[d,n,k,G,J,t,x,S]),H=V.useCallback(()=>{D.current=!0;const j=C.current??G;L.current.add(j),a.transport.cancelStream?.(j),E(j),m(j,vt.Idle)},[G,a.transport,E,m]),z=V.useCallback(async j=>{d===vt.Streaming&&H(),await R(j)},[d,H,R]);return{pendingKey:G,queuedMessages:u,activeChatStatus:n?vt.Idle:d,activeChatId:s,removeQueuedMessage:w,handleSubmit:B,handleStop:H,handleQueuedClick:z}},S_e=(e,t)=>{const n=JSON.stringify(t.metadata?.data);let r;for(let a=e.length-1;a>=0;a--){const o=e[a].attachments?.find(F3);if(o){r=o;break}}return!r||r.url!==t.url?!1:JSON.stringify(r.metadata?.data)===n},F3=e=>e.type===exports.AgentAttachmentType.Context&&e.metadata?.kind==="pageContext",N_e=e=>{const t=e.matchAll(/(^|[\s([{])@([a-zA-Z0-9_.-]+)/g),n=new Set,r=[];for(const a of t){const i=a[2],o=i.toLowerCase();n.has(o)||(n.add(o),r.push({type:o==="agent"?"agent":"user",name:i}))}return r.length>0?r:void 0},A_e=({queuedMessages:e,onSendQueued:t,onRemoveQueued:n})=>e.length?N.jsxs("div",{className:"mp-agent-composer-queue",children:[N.jsx("div",{className:"mp-agent-composer-queue-header",children:N.jsxs("span",{children:[e.length," message",e.length>1?"s":""," queued"]})}),N.jsx("div",{className:"mp-agent-composer-queue-items",children:e.map(r=>N.jsxs("div",{className:"mp-agent-composer-queue-item",children:[N.jsxs("span",{className:"mp-agent-composer-queue-item-text",children:[r.content,r.attachments?.length?N.jsxs("span",{style:{marginLeft:8,opacity:.7,display:"inline-flex",alignItems:"center",gap:4},children:[N.jsx(Qi,{size:12}),r.attachments.length]}):null]}),N.jsxs("div",{className:"mp-agent-composer-queue-item-actions",children:[N.jsx("button",{type:"button",className:"mp-agent-composer-queue-button",onClick:()=>t(r.id),"aria-label":"Send queued message",children:N.jsx(Dd,{size:12})}),N.jsx("button",{type:"button",className:"mp-agent-composer-queue-button",onClick:()=>n(r.id),"aria-label":"Remove queued message",children:N.jsx(v5,{size:12})})]})]},r.id))})]}):null;function T_e(e,t){return e.size>t.maxFileSize?{type:"size",message:`File "${e.name}" exceeds maximum size of ${up(t.maxFileSize)}`,fileName:e.name}:null}function C_e(e,t,n){if(e.length+t.filter(s=>s.type==="file").length>n.maxFilesPerMessage)return{type:"count",message:`Maximum ${n.maxFilesPerMessage} files per message allowed`};for(const s of e){const l=T_e(s,n);if(l)return l}const a=t.filter(s=>s.type==="file").reduce((s,l)=>{const u=l.metadata?.size||l.size||0;return s+u},0),i=e.reduce((s,l)=>s+l.size,0);return a+i>n.maxTotalAttachmentsSize?{type:"totalSize",message:`Total attachment size exceeds maximum of ${up(n.maxTotalAttachmentsSize)}`}:null}function up(e){if(e===0)return"0 Bytes";const t=1024,n=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return Math.round(e/Math.pow(t,r)*100)/100+" "+n[r]}function R_e(){return{maxFileSize:10*1024*1024,maxTotalAttachmentsSize:50*1024*1024,maxFilesPerMessage:10,allowedMimeTypes:void 0}}const P3=e=>{switch(e.type){case exports.AgentAttachmentType.Link:return N.jsx(g5,{size:12});case exports.AgentAttachmentType.Artifact:return N.jsx(Qi,{size:12});case exports.AgentAttachmentType.Context:switch(e?.metadata?.kind){case"pageContext":return N.jsx($d,{size:12});case"formSnapshot":case"formField":return N.jsx(f5,{size:12});default:return N.jsx(Fd,{size:12})}case exports.AgentAttachmentType.File:default:return N.jsx(m5,{size:12})}},I_e=({attachments:e})=>!e||e.length===0?null:N.jsx("div",{className:"mp-agent-message-attachments","aria-label":"Message attachments",children:e.map((t,n)=>{const r=N.jsxs(N.Fragment,{children:[N.jsx("span",{className:"mp-agent-message-attachment-icon",children:P3(t)}),N.jsx("span",{className:"mp-agent-message-attachment-name",children:t.name})]});return t.url?N.jsx("a",{className:"mp-agent-message-attachment",href:t.url,target:"_blank",rel:"noreferrer",title:t.url,children:r},t.id||n):N.jsx("span",{className:"mp-agent-message-attachment",title:t.mimeType??t.name,children:r},t.id||n)})}),O_e=({attachments:e,onRemove:t,uploadProgress:n,uploadErrors:r})=>{const a=Wt();return!e||e.length===0?null:N.jsx("div",{className:"mp-agent-composer-attachments","aria-label":a.attachments,children:e.map(i=>{const o=n?.get(i.id),s=r?.get(i.name),l=i.metadata?.size||i.size,u=l?` (${up(l)})`:"";return N.jsxs("span",{className:`mp-agent-attachment-chip ${s?"mp-agent-attachment-chip-error":""} ${o?.status==="uploading"?"mp-agent-attachment-chip-uploading":""}`,title:s||i.name,children:[N.jsx("span",{className:"mp-agent-attachment-chip-icon",children:P3(i)}),N.jsxs("span",{className:"mp-agent-attachment-chip-name",title:i.name,children:[i.name,u]}),o?.status==="uploading"&&N.jsxs("span",{className:"mp-agent-attachment-chip-progress",children:[o.progress,"%"]}),s&&N.jsx("span",{className:"mp-agent-attachment-chip-error-text",title:s,children:"⚠"}),t?N.jsx(nn,{size:"sm",icon:"X",type:"button",onClick:d=>{d.preventDefault(),d.stopPropagation(),t(i.id)},"aria-label":`Remove attachment ${i.name}`}):null]},i.id)})})},L_e=e=>{const t=e.trim();if(!t||/\s/.test(t))return;const n=i=>i.replace(/[)\].,;:!?]+$/,"");if(!/^https?:\/\//i.test(t))return;const r=i=>{try{const o=new URL(i);return o.protocol!=="http:"&&o.protocol!=="https:"?void 0:o.toString()}catch{return}},a=n(t);return r(a)},D_e=e=>{try{const t=new URL(e);return t.hostname+(t.pathname&&t.pathname!=="/"?t.pathname:"")}catch{return e}},od="mp-agent:locationchange",f2="__mp_agent_history_patched__",g2=()=>{try{window.dispatchEvent(new Event(od))}catch{}},z_e=()=>{if(typeof window>"u")return;const e=window;if(!e[f2]){e[f2]=!0;try{const t=history.pushState;history.pushState=function(...n){const r=t.apply(this,n);return g2(),r}}catch{}try{const t=history.replaceState;history.replaceState=function(...n){const r=t.apply(this,n);return g2(),r}}catch{}}},$_e=e=>{if(typeof window>"u")return()=>{};z_e();const t=()=>e();return window.addEventListener("popstate",t),window.addEventListener("hashchange",t),window.addEventListener(od,t),()=>{window.removeEventListener("popstate",t),window.removeEventListener("hashchange",t),window.removeEventListener(od,t)}};async function F_e(e,t,n,r){const a=await fetch(r.presignedUrlEndpoint,{method:"POST",headers:{"Content-Type":"application/json",...r.getAuthHeaders?.()||{}},body:JSON.stringify({filename:e.name,mimeType:e.type||"application/octet-stream",size:e.size,chatId:t,userId:n})});if(!a.ok){const o=await a.text();throw new Error(`Failed to get presigned URL: ${a.status} ${o}`)}const i=await a.json();return{url:i.url,key:i.key}}async function P_e(e,t,n){return new Promise((r,a)=>{const i=new XMLHttpRequest;i.upload.addEventListener("progress",o=>{if(o.lengthComputable&&n){const s=Math.round(o.loaded/o.total*100);n(s)}}),i.addEventListener("load",()=>{i.status>=200&&i.status<300?r():a(new Error(`Upload failed: ${i.status} ${i.statusText}`))}),i.addEventListener("error",()=>{a(new Error("Upload failed: network error"))}),i.addEventListener("abort",()=>{a(new Error("Upload aborted"))}),i.open("PUT",t),i.setRequestHeader("Content-Type",e.type||"application/octet-stream"),i.send(e)})}async function q_e(e,t,n){const r=_t.nanoid(),a={fileId:r,fileName:e.name,progress:0,status:"pending"};try{n.onProgress?.({...a,status:"uploading",progress:0});const{url:i,key:o}=await F_e(e,n.chatId,n.userId,t);return await P_e(e,i,s=>{n.onProgress?.({...a,status:"uploading",progress:s})}),n.onProgress?.({...a,status:"completed",progress:100}),{id:r,type:exports.AgentAttachmentType.File,name:e.name,mimeType:e.type||void 0,size:e.size,metadata:{uploadedAt:new Date().toISOString(),s3Key:o,processingStatus:"pending",size:e.size,lastModified:e.lastModified}}}catch(i){const o=i instanceof Error?i.message:"Unknown error";throw n.onProgress?.({...a,status:"error",error:o}),i}}async function B_e(e,t,n){const r=await Promise.allSettled(e.map(o=>q_e(o,t,n))),a=[],i=[];if(r.forEach((o,s)=>{o.status==="fulfilled"?a.push(o.value):i.push(new Error(`Failed to process ${e[s].name}: ${o.reason}`))}),i.length>0&&a.length===0)throw i[0];return i.length>0&&console.warn("Some files failed to upload:",i),a}const U_e=({options:e,value:t,onChange:n,placeholder:r="Select...",disabled:a=!1,className:i="",triggerClassName:o="",placement:s="bottom-start",searchable:l=!1,searchPlaceholder:u="Search...",searchFilter:d})=>{const[p,m]=V.useState(!1),[h,g]=V.useState(null),[f,w]=V.useState(""),v=V.useRef([]),k=V.useRef(null),{refs:_,floatingStyles:E,context:S,isPositioned:x}=Zd({open:p,onOpenChange:m,placement:s,strategy:"absolute",whileElementsMounted:jd,middleware:[Vd(8),Wd({fallbackPlacements:["top-start","bottom-start","top-end","bottom-end"]}),Gd({padding:8})]}),D=Y5(S,{enabled:!a}),P=Yd(S),C=Qd(S),G=a7e(S,{listRef:v,activeIndex:h,onNavigate:g,enabled:p&&!l,virtual:!1}),{getReferenceProps:X,getFloatingProps:J,getItemProps:K}=Xd(l?[D,P,C]:[D,P,C,G]),R=e.findIndex(Y=>Y.value===t),B=R>=0?e[R]:void 0,H=V.useMemo(()=>{const Y=f.trim().toLowerCase();if(!l||!Y)return e;const O=d?se=>d(se,Y):se=>`${se.label} ${se.description??""}`.toLowerCase().includes(Y);return e.filter(O)},[e,f,l,d]);V.useEffect(()=>{if(!p){g(null),w("");return}l&&setTimeout(()=>k.current?.focus(),0);const Y=H.findIndex(ee=>ee.value===t);g(Y>=0?Y:0)},[p,l,t,H]),V.useEffect(()=>{p&&g(H.length>0?0:null)},[f,H.length,p]);const z=Y=>H.length===0?null:Y<0?H.length-1:Y>=H.length?0:Y,j=Y=>{Y!=null&&v.current[Y]?.scrollIntoView({block:"nearest"})},A=Y=>{n(Y),m(!1),g(null),w("")};return N.jsxs("div",{className:`mp-agent-dropdown ${i}`,children:[N.jsxs("button",{ref:_.setReference,type:"button",className:`mp-agent-dropdown-trigger ${o}`,disabled:a,"aria-expanded":p,"aria-haspopup":"listbox",...X(),children:[N.jsx("span",{className:"mp-agent-dropdown-trigger-content",children:B?N.jsxs(N.Fragment,{children:[B.icon&&N.jsx("span",{className:"mp-agent-dropdown-trigger-icon",children:B.icon}),N.jsx("span",{className:"mp-agent-dropdown-trigger-label",children:B.label})]}):N.jsx("span",{className:"mp-agent-dropdown-trigger-placeholder",children:r})}),N.jsx(zd,{size:16,className:`mp-agent-dropdown-chevron ${p?"open":""}`})]}),p&&N.jsxs("div",{role:"listbox",ref:_.setFloating,style:{...E,opacity:x?1:0,pointerEvents:x?"auto":"none",transition:x?"opacity 0.15s ease-out":"none"},className:"mp-agent-dropdown-menu",...J(),children:[l&&N.jsx("div",{className:"mp-agent-dropdown-search",onKeyDown:Y=>Y.stopPropagation(),children:N.jsx("input",{ref:k,className:"mp-agent-dropdown-search-input",value:f,placeholder:u,onChange:Y=>w(Y.target.value),onKeyDown:Y=>{if(Y.key==="Escape"){Y.preventDefault(),m(!1),w("");return}if(Y.key==="ArrowDown"||Y.key==="ArrowUp"){Y.preventDefault();const ee=Y.key==="ArrowDown"?1:-1,O=h??(ee>0?-1:0),se=z(O+ee);g(se),j(se);return}if(Y.key==="Enter"){if(h==null)return;const ee=H[h];if(!ee)return;Y.preventDefault(),A(ee.value)}}})}),N.jsxs("div",{className:"mp-agent-dropdown-list",children:[H.map((Y,ee)=>N.jsxs("button",{ref:O=>{v.current[ee]=O},type:"button",className:`mp-agent-dropdown-item ${t===Y.value?"selected":""} ${h===ee?"active":""}`,role:"option","aria-selected":t===Y.value,...K({onClick:()=>A(Y.value),onMouseEnter:()=>{g(ee)},onKeyDown:O=>{(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),A(Y.value))}}),children:[Y.icon&&N.jsx("span",{className:"mp-agent-dropdown-item-icon",children:Y.icon}),N.jsxs("span",{className:"mp-agent-dropdown-item-content",children:[N.jsx("span",{className:"mp-agent-dropdown-item-label",children:Y.label}),Y.description&&N.jsx("span",{className:"mp-agent-dropdown-item-description",children:Y.description})]})]},Y.value)),l&&H.length===0&&N.jsx("div",{className:"mp-agent-dropdown-empty","aria-label":"No results",children:"No results"})]})]})]})},H_e=V.memo(()=>{const e=He(),t=be(p=>p.composer),n=be(p=>p.contextKey),r=be(p=>p.setComposerOptions),a=e.config.models,{data:i,isLoading:o}=a3(),s=V.useMemo(()=>{const p=i&&i.length>0?i:a;return w3(p,e.config.transport).filter(h=>!h.contexts?.length||h.contexts.includes(n))},[i,a,e.config.transport,n]),l=V.useMemo(()=>{const p=s.slice().sort((m,h)=>m.label.localeCompare(h.label,void 0,{sensitivity:"base"})).map(m=>({value:m.id,label:m.label}));return[{value:ta,label:"Auto"},...p]},[s]),u=V.useMemo(()=>t.model!==void 0?t.model:ta,[t.model]),d=V.useCallback(p=>{p===ta?(r({model:void 0}),c2(e.config.transport,ta)):(r({model:p}),c2(e.config.transport,p))},[r,e.config.transport]);return o&&!a?.length||l.length===0?null:N.jsx(U_e,{options:l,value:u,onChange:d,placeholder:"Select model...",searchable:!0,searchPlaceholder:"Search models...",placement:"top-start",triggerClassName:"mp-agent-model-selector-trigger"})}),j_e=e=>{if(!e)return"";let t=e.replace(/[_-]+/g," ");return t=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2"),t=t.trim().replace(/\s+/g," "),t?t.charAt(0).toUpperCase()+t.slice(1):""},V_e=({checked:e,disabled:t,onChange:n,className:r="",...a})=>{const i=o=>{o.preventDefault(),!t&&n(!e)};return N.jsx("button",{type:"button",role:"switch","aria-checked":e,disabled:t,className:`mp-agent-switch ${e?"on":"off"} ${r}`.trim(),onClick:i,...a,children:N.jsx("span",{className:"mp-agent-switch-thumb"})})},y2=e=>e.reduce((t,n)=>(t[n.agentName]={...n.tools},t),{}),q3=({preferences:e,disabled:t})=>{const n=Wt(),{upsertSingle:r}=u3(),[a,i]=V.useState(()=>y2(e)),[o,s]=V.useState({});V.useEffect(()=>{i(y2(e))},[e]);const l=r.error?.message,u=V.useMemo(()=>e.some(p=>Object.keys(p.tools).length>0),[e]),d=(p,m,h)=>{i(g=>{const f=g[p]??{},w=f,v={...f,[m]:h},k={...g,[p]:v};return s(_=>({..._,[p]:{..._[p]??{},[m]:!0}})),r.mutate({agentName:p,input:{tools:v}},{onError:()=>{i(_=>({..._,[p]:w}))},onSettled:()=>{s(_=>{const E={..._[p]??{}};if(delete E[m],Object.keys(E).length===0){const{[p]:S,...x}=_;return x}return{..._,[p]:E}})}}),k})};return N.jsxs("div",{className:"mp-agent-preferences-panel",children:[!u&&N.jsx("div",{className:"mp-agent-preferences-empty",children:n.agentSettingsNoConfigurableTools}),e.map(p=>{const m=a[p.agentName]??{},h=Object.entries(m);return N.jsxs("div",{className:"mp-agent-preferences-agent",children:[N.jsx("div",{className:"mp-agent-preferences-agent-header",children:N.jsx("strong",{children:p.agentName})}),h.length===0?N.jsx("div",{className:"mp-agent-preferences-empty",children:n.agentSettingsNoToolsForAgent}):N.jsx("div",{className:"mp-agent-preferences-tools",children:h.map(([g,f])=>{const w=!!o[p.agentName]?.[g];return N.jsxs("label",{className:"mp-agent-preferences-tool",children:[N.jsx("span",{className:"mp-agent-preferences-tool-label",children:j_e(g)}),N.jsx(V_e,{checked:f,onChange:v=>d(p.agentName,g,v),disabled:!!t||w})]},`${p.agentName}:${g}`)})})]},p.agentName)}),l&&N.jsx("div",{className:"mp-agent-preferences-error",children:l})]})};function G_e(e){return e.map(t=>{const n=(t.tools??[]).reduce((r,a)=>(a.userConfigurable&&(r[a.title]=!a.disabledByDefault),r),{});return{agentName:t.name,tools:n}})}const W_e=()=>{const e=Wt(),t=He(),n=be(l=>l.contextKey),{data:r,isLoading:a,isError:i}=s3(n),o=V.useMemo(()=>G_e(r??[]),[r]),s=!!t.transport.upsertAgentPreferences&&!!t.transport.upsertAgentPreferencesBatch;return a?N.jsx(N.Fragment,{children:e.agentSettingsLoading}):i?N.jsx(N.Fragment,{children:e.agentSettingsError}):N.jsx(q3,{preferences:o,disabled:!s})},K_e=()=>{const[e,t]=V.useState(!1),n=Wt(),{refs:r,floatingStyles:a,context:i,isPositioned:o}=Zd({open:e,onOpenChange:t,placement:"top-start",strategy:"absolute",whileElementsMounted:jd,middleware:[Vd(8),Wd({fallbackPlacements:["bottom-start","top-end","bottom-end"]}),Gd({padding:8})]}),s=Y5(i),l=Yd(i),u=Qd(i),{getReferenceProps:d,getFloatingProps:p}=Xd([s,l,u]);return N.jsxs("div",{className:"mp-agent-tool-config-dropdown",children:[N.jsx(bn,{content:n.agentSettingsTooltip,children:N.jsx("button",{ref:r.setReference,type:"button",className:"mp-agent-composer-button mp-agent-composer-tool-button","aria-label":n.agentSettingsTooltip,...d(),children:N.jsx(y5,{size:16})})}),e&&N.jsx("div",{ref:r.setFloating,style:{...a,opacity:o?1:0,pointerEvents:o?"auto":"none",transition:o?"opacity 0.15s ease-out":"none"},className:"mp-agent-tool-config-panel",...p(),children:N.jsx(W_e,{})})]})},Y_e=V.forwardRef(({autoFocus:e,activeChatId:t,status:n,onStop:r,onSubmit:a},i)=>{const o=Wt(),s=He(),l=V.useRef(null),u=V.useRef(null),d=be(re=>re.activeChatId??re.draftChatKey),p=be(re=>$e(re,d).composerDraft),m=be(re=>$e(re,d).composerError),h=be(re=>$e(re,d).pageContextDismissed),g=be(re=>re.setComposerValue),f=be(re=>re.setComposerDraft),w=be(re=>re.clearComposerDraft),v=be(re=>re.setComposerError),k=be(re=>re.addComposerAttachments),_=be(re=>re.removeComposerAttachment),E=be(re=>re.setPageContextDismissed),S=p.value,x=p.attachments,[D,P]=V.useState(new Map),[C,L]=V.useState(new Map),G=V.useRef(S),X=V.useRef(x),J=V.useRef(h),K=s.config.features?.pageContextAttachments!==!1,R=re=>re.type===exports.AgentAttachmentType.Context&&re?.metadata?.kind==="pageContext",B=x.some(R),H=()=>{if(K)return s.buildPageContextAttachment()};V.useEffect(()=>{X.current=x},[x]),V.useEffect(()=>{G.current=S},[S]),V.useEffect(()=>{J.current=h},[h]),V.useEffect(()=>{if(!K||h||B)return;const re=H();re&&k(d,[re])},[K,h,B,d,k]),V.useEffect(()=>{if(K&&!(typeof window>"u"))return $_e(()=>{if(J.current)return;const re=X.current,_e=re.find(R);if(!_e)return;const Ge=H();if(!Ge)return;const We={...Ge,id:_e.id},Ce=re.map(Re=>Re.id===_e.id?We:Re);f(d,{value:G.current,attachments:Ce})})},[K,d,f]),V.useImperativeHandle(i,()=>({setValue:re=>{g(d,re)},getDraft:()=>({value:S,attachments:x}),setDraft:re=>{f(d,{value:re.value,attachments:re.attachments??[]})},clearDraft:()=>{w(d)},buildPageContextAttachment:()=>H()})),V.useEffect(()=>{const re=l.current;re&&(re.style.height="auto",re.style.height=`${Math.min(re.scrollHeight,200)}px`)},[S]);const z=async re=>{if(!re||re.length===0)return;const _e=Array.from(re),Ge=R_e(),We=C_e(_e,x,Ge);if(We){L(Ce=>{const Re=new Map(Ce);return _e.forEach(Se=>{Re.set(Se.name,We.message)}),Re});return}L(Ce=>{const Re=new Map(Ce);return _e.forEach(Se=>Re.delete(Se.name)),Re});try{const Ce=s.config.transport;if(Ce.mode!=="proxy")throw new Error("File uploads are only supported with proxy transport");const Re={presignedUrlEndpoint:`${Ce.baseUrl}/files/upload/presigned`,getAuthHeaders:()=>{const Be={};return Ce.headers?Ce.headers:(Ce.apiKey&&(Be.Authorization=`Bearer ${Ce.apiKey}`),Be)}},Se=await B_e(_e,Re,{chatId:t,userId:s.config.user?.id,onProgress:Be=>{P(de=>{const et=new Map(de);return et.set(Be.fileId,Be),et})}});k(d,Se),setTimeout(()=>{P(Be=>{const de=new Map(Be);return Se.forEach(et=>de.delete(et.id)),de})},2e3)}catch(Ce){const Re=Ce instanceof Error?Ce.message:"Failed to upload files";L(Se=>{const Be=new Map(Se);return _e.forEach(de=>{Be.set(de.name,Re)}),Be})}},j=()=>{u.current?.click()},A=re=>{const _e=L_e(re);if(!_e)return!1;if(x.some(Ce=>Ce.type===exports.AgentAttachmentType.Link&&Ce.url===_e))return!0;const Ge=D_e(_e),We={id:_t.nanoid(),url:_e,name:Ge,type:exports.AgentAttachmentType.Link};return k(d,[We]),!0},Y=async re=>{await z(re.target.files),re.target.value=""},ee=re=>{const _e=x.find(Ge=>Ge.id===re);_e&&R(_e)&&E(d,!0),_(d,re)},O=()=>{if(typeof window>"u"||typeof document>"u")return!1;const re=f3(),_e=re?.selectedText??window.getSelection?.()?.toString()?.trim()??"";if(!_e)return!1;const Ge=window.location?.href,We=_e.slice(0,20),Ce=_e.length>20?We+"...":_e,Re=po({kind:"webSnippet",url:Ge,title:Ce,selectedText:_e,source:{app:"browser",url:Ge},...re?.target?{target:re.target}:{}});return k(d,[Re]),!0},se=re=>{re.preventDefault();const _e=S.trim();_e&&(v(d,void 0),a(_e))},ge=re=>{re.key==="Enter"&&!re.shiftKey&&(re.preventDefault(),se(re))},ke=re=>{m&&v(d,void 0),g(d,re.target.value)},Te=re=>{if(re.nativeEvent.shiftKey)return;const _e=re.clipboardData?.getData("text/plain")??"";if(!_e)return;A(_e)&&re.preventDefault()},Ke=!!S.trim();return N.jsxs(N.Fragment,{children:[N.jsxs("form",{onSubmit:se,className:"mp-agent-composer-input-wrapper",id:"composer-form",children:[N.jsx("input",{ref:u,type:"file",multiple:!0,style:{display:"none"},onChange:Y}),N.jsx(O_e,{attachments:x,onRemove:ee,uploadProgress:D,uploadErrors:C}),N.jsx("textarea",{rows:2,name:"message",ref:l,value:S,autoFocus:e,className:"mp-agent-composer-textarea",placeholder:t?o.followUp:o.newChat,onChange:ke,onKeyDown:ge,onPaste:Te})]}),N.jsxs("div",{className:"mp-agent-composer-actions",children:[N.jsxs("div",{className:"mp-agent-composer-actions-left",children:[s.config.features?.modelSwitching&&N.jsx(H_e,{}),s.config.features?.toolConfiguration&&N.jsx(K_e,{}),N.jsx(bn,{content:o.attachFiles,children:N.jsx("button",{type:"button",className:"mp-agent-composer-button mp-agent-composer-tool-button",onClick:j,"aria-label":o.attachFiles,children:N.jsx(Qi,{size:16})})}),N.jsx(bn,{content:o.attachSelectionToContext,children:N.jsx("button",{type:"button",className:"mp-agent-composer-button mp-agent-composer-tool-button",onClick:()=>{O()},"aria-label":o.attachSelectionToContext,children:N.jsx(Fd,{size:16})})}),K&&!B&&N.jsx(bn,{content:"Attach page context",children:N.jsx("button",{type:"button",className:"mp-agent-composer-button mp-agent-composer-tool-button",onClick:()=>{E(d,!1);const re=H();re&&k(d,[re])},"aria-label":"Attach page context",children:N.jsx($d,{size:16})})})]}),N.jsx("div",{className:"mp-agent-composer-actions-right",children:n===vt.Streaming&&!Ke?N.jsx(bn,{content:o.stopStreaming,children:N.jsx("button",{type:"button",onClick:r,"aria-label":o.stopStreaming,className:"mp-agent-composer-button mp-agent-composer-send-button",children:N.jsx(k5,{size:12})})}):N.jsx(bn,{content:Ke?o.sendMessage:o.typeMessageToSend,children:N.jsx("button",{type:"submit",form:"composer-form",disabled:!Ke,"aria-label":o.sendMessage,className:"mp-agent-composer-button mp-agent-composer-send-button",children:N.jsx(Dd,{size:16})})})})]})]})}),B3=({autoFocus:e,multiUser:t=!1,participantIds:n})=>{const r=V.useRef({setValue:()=>{},getDraft:()=>({value:"",attachments:[]}),setDraft:()=>{},clearDraft:()=>{}}),{pendingKey:a,queuedMessages:i,activeChatStatus:o,activeChatId:s,handleSubmit:l,handleStop:u,handleQueuedClick:d,removeQueuedMessage:p}=M_e({composerFormRef:r,multiUser:t,participantIds:n});return N.jsx("div",{className:"mp-agent-composer-wrapper",children:N.jsxs("div",{className:"mp-agent-composer",children:[N.jsx(A_e,{queuedMessages:i,onSendQueued:d,onRemoveQueued:m=>p(a,m)}),N.jsx(Y_e,{status:o,ref:r,autoFocus:e,activeChatId:s,onStop:u,onSubmit:l})]})})};function xr(e,t,n){let r=n.initialDeps??[],a,i=!0;function o(){var s,l,u;let d;n.key&&((s=n.debug)!=null&&s.call(n))&&(d=Date.now());const p=e();if(!(p.length!==r.length||p.some((g,f)=>r[f]!==g)))return a;r=p;let h;if(n.key&&((l=n.debug)!=null&&l.call(n))&&(h=Date.now()),a=t(...p),n.key&&((u=n.debug)!=null&&u.call(n))){const g=Math.round((Date.now()-d)*100)/100,f=Math.round((Date.now()-h)*100)/100,w=f/16,v=(k,_)=>{for(k=String(k);k.length<_;)k=" "+k;return k};console.info(`%c⏱ ${v(f,5)} /${v(g,5)} ms`,`
8293
+ }`}),t]})},v3=()=>V.useContext(b3),l2="mp-agent-selected-model",ta="__auto__";function _3(e){return e.mode==="direct"?`${l2}-${e.mode}-${e.provider}`:`${l2}-${e.mode}`}function c2(e,t){try{const n=_3(e);localStorage.setItem(n,t)}catch(n){console.warn("Failed to save selected model to localStorage:",n)}}function E7e(e){try{const t=_3(e);return localStorage.getItem(t)}catch(t){return console.warn("Failed to load selected model from localStorage:",t),null}}function w3(e,t){return!e||e.length===0?[]:t.mode==="direct"&&t.provider!=="custom"?e.filter(n=>n.provider?n.provider===t.provider:!0):e}function M7e(e,t,n){const r=E7e(t);if(r){if(r===ta)return;if(w3(e,t).some(i=>i.id===r))return r}}const S7e="mp-agents-last-active-chat";function x3(e){return`${S7e}-${e}`}function E3(e){return typeof e=="string"&&e.length>0&&e.length<256}function N7e(e){if(typeof window>"u")return null;try{const t=localStorage.getItem(x3(e));return t&&E3(t)?t:null}catch{return null}}function A7e(e,t){if(!(typeof window>"u"))try{const n=x3(e);t&&E3(t)?localStorage.setItem(n,t):localStorage.removeItem(n)}catch{}}const wn=Object.create(null);wn.open="0";wn.close="1";wn.ping="2";wn.pong="3";wn.message="4";wn.upgrade="5";wn.noop="6";const bi=Object.create(null);Object.keys(wn).forEach(e=>{bi[wn[e]]=e});const ed={type:"error",data:"parser error"},M3=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",S3=typeof ArrayBuffer=="function",N3=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ap=({type:e,data:t},n,r)=>M3&&t instanceof Blob?n?r(t):u2(t,r):S3&&(t instanceof ArrayBuffer||N3(t))?n?r(t):u2(new Blob([t]),r):r(wn[e]+(t||"")),u2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function d2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Xo;function T7e(e,t){if(M3&&e.data instanceof Blob)return e.data.arrayBuffer().then(d2).then(t);if(S3&&(e.data instanceof ArrayBuffer||N3(e.data)))return t(d2(e.data));ap(e,!1,n=>{Xo||(Xo=new TextEncoder),t(Xo.encode(n))})}const p2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",na=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<p2.length;e++)na[p2.charCodeAt(e)]=e;const C7e=e=>{let t=e.length*.75,n=e.length,r,a=0,i,o,s,l;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const u=new ArrayBuffer(t),d=new Uint8Array(u);for(r=0;r<n;r+=4)i=na[e.charCodeAt(r)],o=na[e.charCodeAt(r+1)],s=na[e.charCodeAt(r+2)],l=na[e.charCodeAt(r+3)],d[a++]=i<<2|o>>4,d[a++]=(o&15)<<4|s>>2,d[a++]=(s&3)<<6|l&63;return u},R7e=typeof ArrayBuffer=="function",ip=(e,t)=>{if(typeof e!="string")return{type:"message",data:A3(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:I7e(e.substring(1),t)}:bi[n]?e.length>1?{type:bi[n],data:e.substring(1)}:{type:bi[n]}:ed},I7e=(e,t)=>{if(R7e){const n=C7e(e);return A3(n,t)}else return{base64:!0,data:e}},A3=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},T3="",O7e=(e,t)=>{const n=e.length,r=new Array(n);let a=0;e.forEach((i,o)=>{ap(i,!1,s=>{r[o]=s,++a===n&&t(r.join(T3))})})},L7e=(e,t)=>{const n=e.split(T3),r=[];for(let a=0;a<n.length;a++){const i=ip(n[a],t);if(r.push(i),i.type==="error")break}return r};function D7e(){return new TransformStream({transform(e,t){T7e(e,n=>{const r=n.length;let a;if(r<126)a=new Uint8Array(1),new DataView(a.buffer).setUint8(0,r);else if(r<65536){a=new Uint8Array(3);const i=new DataView(a.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{a=new Uint8Array(9);const i=new DataView(a.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(a[0]|=128),t.enqueue(a),t.enqueue(n)})}})}let Qo;function Va(e){return e.reduce((t,n)=>t+n.length,0)}function Ga(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let a=0;a<t;a++)n[a]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function z7e(e,t){Qo||(Qo=new TextDecoder);const n=[];let r=0,a=-1,i=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(Va(n)<1)break;const l=Ga(n,1);i=(l[0]&128)===128,a=l[0]&127,a<126?r=3:a===126?r=1:r=2}else if(r===1){if(Va(n)<2)break;const l=Ga(n,2);a=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),r=3}else if(r===2){if(Va(n)<8)break;const l=Ga(n,8),u=new DataView(l.buffer,l.byteOffset,l.length),d=u.getUint32(0);if(d>Math.pow(2,21)-1){s.enqueue(ed);break}a=d*Math.pow(2,32)+u.getUint32(4),r=3}else{if(Va(n)<a)break;const l=Ga(n,a);s.enqueue(ip(i?l:Qo.decode(l),t)),r=0}if(a===0||a>e){s.enqueue(ed);break}}}})}const C3=4;function ct(e){if(e)return $7e(e)}function $7e(e){for(var t in ct.prototype)e[t]=ct.prototype[t];return e}ct.prototype.on=ct.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};ct.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};ct.prototype.off=ct.prototype.removeListener=ct.prototype.removeAllListeners=ct.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var r,a=0;a<n.length;a++)if(r=n[a],r===t||r.fn===t){n.splice(a,1);break}return n.length===0&&delete this._callbacks["$"+e],this};ct.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){n=n.slice(0);for(var r=0,a=n.length;r<a;++r)n[r].apply(this,t)}return this};ct.prototype.emitReserved=ct.prototype.emit;ct.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};ct.prototype.hasListeners=function(e){return!!this.listeners(e).length};const ho=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),Qt=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),F7e="arraybuffer";function R3(e,...t){return t.reduce((n,r)=>(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const P7e=Qt.setTimeout,q7e=Qt.clearTimeout;function mo(e,t){t.useNativeTimers?(e.setTimeoutFn=P7e.bind(Qt),e.clearTimeoutFn=q7e.bind(Qt)):(e.setTimeoutFn=Qt.setTimeout.bind(Qt),e.clearTimeoutFn=Qt.clearTimeout.bind(Qt))}const B7e=1.33;function U7e(e){return typeof e=="string"?H7e(e):Math.ceil((e.byteLength||e.size)*B7e)}function H7e(e){let t=0,n=0;for(let r=0,a=e.length;r<a;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}function I3(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function j7e(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function V7e(e){let t={},n=e.split("&");for(let r=0,a=n.length;r<a;r++){let i=n[r].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}class G7e extends Error{constructor(t,n,r){super(t),this.description=n,this.context=r,this.type="TransportError"}}class op extends ct{constructor(t){super(),this.writable=!1,mo(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,n,r){return super.emitReserved("error",new G7e(t,n,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const n=ip(t,this.socket.binaryType);this.onPacket(n)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,n={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(n)}_hostname(){const t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){const n=j7e(t);return n.length?"?"+n:""}}class W7e extends op{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const n=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let r=0;this._polling&&(r++,this.once("pollComplete",function(){--r||n()})),this.writable||(r++,this.once("drain",function(){--r||n()}))}else n()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};L7e(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,O7e(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=I3()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}}let O3=!1;try{O3=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const K7e=O3;function Y7e(){}class Z7e extends W7e{constructor(t){if(super(t),typeof location<"u"){const n=location.protocol==="https:";let r=location.port;r||(r=n?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||r!==t.port}}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(a,i)=>{this.onError("xhr post error",a,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,r)=>{this.onError("xhr poll error",n,r)}),this.pollXhr=t}}class _n extends ct{constructor(t,n,r){super(),this.createRequest=t,mo(this,r),this._opts=r,this._method=r.method||"GET",this._uri=n,this._data=r.data!==void 0?r.data:null,this._create()}_create(){var t;const n=R3(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this._opts.xd;const r=this._xhr=this.createRequest(n);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let a in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(a)&&r.setRequestHeader(a,this._opts.extraHeaders[a])}}catch{}if(this._method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(r),"withCredentials"in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var a;r.readyState===3&&((a=this._opts.cookieJar)===null||a===void 0||a.parseCookies(r.getResponseHeader("set-cookie"))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status=="number"?r.status:0)},0))},r.send(this._data)}catch(a){this.setTimeoutFn(()=>{this._onError(a)},0);return}typeof document<"u"&&(this._index=_n.requestsCount++,_n.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Y7e,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete _n.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}_n.requestsCount=0;_n.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",h2);else if(typeof addEventListener=="function"){const e="onpagehide"in Qt?"pagehide":"unload";addEventListener(e,h2,!1)}}function h2(){for(let e in _n.requests)_n.requests.hasOwnProperty(e)&&_n.requests[e].abort()}const X7e=function(){const e=L3({xdomain:!1});return e&&e.responseType!==null}();class Q7e extends Z7e{constructor(t){super(t);const n=t&&t.forceBase64;this.supportsBinary=X7e&&!n}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new _n(L3,this.uri(),t)}}function L3(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||K7e))return new XMLHttpRequest}catch{}if(!t)try{return new Qt[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const D3=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class J7e extends op{get name(){return"websocket"}doOpen(){const t=this.uri(),n=this.opts.protocols,r=D3?{}:R3(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,n,r)}catch(a){return this.emitReserved("error",a)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n<t.length;n++){const r=t[n],a=n===t.length-1;ap(r,this.supportsBinary,i=>{try{this.doWrite(r,i)}catch{}a&&ho(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=I3()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}}const Jo=Qt.WebSocket||Qt.MozWebSocket;class e_e extends J7e{createSocket(t,n,r){return D3?new Jo(t,n,r):n?new Jo(t,n):new Jo(t)}doWrite(t,n){this.ws.send(n)}}class t_e extends op{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const n=z7e(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),a=D7e();a.readable.pipeTo(t.writable),this._writer=a.writable.getWriter();const i=()=>{r.read().then(({done:s,value:l})=>{s||(this.onPacket(l),i())}).catch(s=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let n=0;n<t.length;n++){const r=t[n],a=n===t.length-1;this._writer.write(r).then(()=>{a&&ho(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const n_e={websocket:e_e,webtransport:t_e,polling:Q7e},r_e=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,a_e=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function td(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let a=r_e.exec(e||""),i={},o=14;for(;o--;)i[a_e[o]]=a[o]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=i_e(i,i.path),i.queryKey=o_e(i,i.query),i}function i_e(e,t){const n=/\/{2,9}/g,r=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&r.splice(0,1),t.slice(-1)=="/"&&r.splice(r.length-1,1),r}function o_e(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,a,i){a&&(n[a]=i)}),n}const nd=typeof addEventListener=="function"&&typeof removeEventListener=="function",ki=[];nd&&addEventListener("offline",()=>{ki.forEach(e=>e())},!1);class Qn extends ct{constructor(t,n){if(super(),this.binaryType=F7e,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(n=t,t=null),t){const r=td(t);n.hostname=r.host,n.secure=r.protocol==="https"||r.protocol==="wss",n.port=r.port,r.query&&(n.query=r.query)}else n.host&&(n.hostname=td(n.host).host);mo(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},n.transports.forEach(r=>{const a=r.prototype.name;this.transports.push(a),this._transportsByName[a]=r}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=V7e(this.opts.query)),nd&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},ki.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=C3,n.transport=t,this.id&&(n.sid=this.id);const r=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](r)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&Qn.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",n=>this._onClose("transport close",n))}onOpen(){this.readyState="open",Qn.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const n=new Error("server error");n.code=t.data,this._onError(n);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let r=0;r<this.writeBuffer.length;r++){const a=this.writeBuffer[r].data;if(a&&(n+=U7e(a)),r>0&&n>this._maxPayload)return this.writeBuffer.slice(0,r);n+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,ho(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,n,r){return this._sendPacket("message",t,n,r),this}send(t,n,r){return this._sendPacket("message",t,n,r),this}_sendPacket(t,n,r,a){if(typeof n=="function"&&(a=n,n=void 0),typeof r=="function"&&(a=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),a&&this.once("flush",a),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},r=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():t()}):this.upgrading?r():t()),this}_onError(t){if(Qn.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,n){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),nd&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const r=ki.indexOf(this._offlineEventListener);r!==-1&&ki.splice(r,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this._prevBufferLen=0}}}Qn.protocol=C3;class s_e extends Qn{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let n=this.createTransport(t),r=!1;Qn.priorWebsocketSuccess=!1;const a=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",p=>{if(!r)if(p.type==="pong"&&p.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;Qn.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(d(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const m=new Error("probe error");m.transport=n.name,this.emitReserved("upgradeError",m)}}))};function i(){r||(r=!0,d(),n.close(),n=null)}const o=p=>{const m=new Error("probe error: "+p);m.transport=n.name,i(),this.emitReserved("upgradeError",m)};function s(){o("transport closed")}function l(){o("socket closed")}function u(p){n&&p.name!==n.name&&i()}const d=()=>{n.removeListener("open",a),n.removeListener("error",o),n.removeListener("close",s),this.off("close",l),this.off("upgrading",u)};n.once("open",a),n.once("error",o),n.once("close",s),this.once("close",l),this.once("upgrading",u),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const n=[];for(let r=0;r<t.length;r++)~this.transports.indexOf(t[r])&&n.push(t[r]);return n}}let l_e=class extends s_e{constructor(t,n={}){const r=typeof t=="object"?t:n;(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(a=>n_e[a]).filter(a=>!!a)),super(t,r)}};function c_e(e,t="",n){let r=e;n=n||typeof location<"u"&&location,e==null&&(e=n.protocol+"//"+n.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=n.protocol+e:e=n.host+e),/^(https?|wss?):\/\//.test(e)||(typeof n<"u"?e=n.protocol+"//"+e:e="https://"+e),r=td(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const i=r.host.indexOf(":")!==-1?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+t,r.href=r.protocol+"://"+i+(n&&n.port===r.port?"":":"+r.port),r}const u_e=typeof ArrayBuffer=="function",d_e=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,z3=Object.prototype.toString,p_e=typeof Blob=="function"||typeof Blob<"u"&&z3.call(Blob)==="[object BlobConstructor]",h_e=typeof File=="function"||typeof File<"u"&&z3.call(File)==="[object FileConstructor]";function sp(e){return u_e&&(e instanceof ArrayBuffer||d_e(e))||p_e&&e instanceof Blob||h_e&&e instanceof File}function vi(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,r=e.length;n<r;n++)if(vi(e[n]))return!0;return!1}if(sp(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return vi(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&vi(e[n]))return!0;return!1}function m_e(e){const t=[],n=e.data,r=e;return r.data=rd(n,t),r.attachments=t.length,{packet:r,buffers:t}}function rd(e,t){if(!e)return e;if(sp(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}else if(Array.isArray(e)){const n=new Array(e.length);for(let r=0;r<e.length;r++)n[r]=rd(e[r],t);return n}else if(typeof e=="object"&&!(e instanceof Date)){const n={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=rd(e[r],t));return n}return e}function f_e(e,t){return e.data=ad(e.data,t),delete e.attachments,e}function ad(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}else if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=ad(e[n],t);else if(typeof e=="object")for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=ad(e[n],t));return e}const g_e=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],y_e=5;var Pe;(function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"})(Pe||(Pe={}));class b_e{constructor(t){this.replacer=t}encode(t){return(t.type===Pe.EVENT||t.type===Pe.ACK)&&vi(t)?this.encodeAsBinary({type:t.type===Pe.EVENT?Pe.BINARY_EVENT:Pe.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let n=""+t.type;return(t.type===Pe.BINARY_EVENT||t.type===Pe.BINARY_ACK)&&(n+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(n+=t.nsp+","),t.id!=null&&(n+=t.id),t.data!=null&&(n+=JSON.stringify(t.data,this.replacer)),n}encodeAsBinary(t){const n=m_e(t),r=this.encodeAsString(n.packet),a=n.buffers;return a.unshift(r),a}}function m2(e){return Object.prototype.toString.call(e)==="[object Object]"}class lp extends ct{constructor(t){super(),this.reviver=t}add(t){let n;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");n=this.decodeString(t);const r=n.type===Pe.BINARY_EVENT;r||n.type===Pe.BINARY_ACK?(n.type=r?Pe.EVENT:Pe.ACK,this.reconstructor=new k_e(n),n.attachments===0&&super.emitReserved("decoded",n)):super.emitReserved("decoded",n)}else if(sp(t)||t.base64)if(this.reconstructor)n=this.reconstructor.takeBinaryData(t),n&&(this.reconstructor=null,super.emitReserved("decoded",n));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let n=0;const r={type:Number(t.charAt(0))};if(Pe[r.type]===void 0)throw new Error("unknown packet type "+r.type);if(r.type===Pe.BINARY_EVENT||r.type===Pe.BINARY_ACK){const i=n+1;for(;t.charAt(++n)!=="-"&&n!=t.length;);const o=t.substring(i,n);if(o!=Number(o)||t.charAt(n)!=="-")throw new Error("Illegal attachments");r.attachments=Number(o)}if(t.charAt(n+1)==="/"){const i=n+1;for(;++n&&!(t.charAt(n)===","||n===t.length););r.nsp=t.substring(i,n)}else r.nsp="/";const a=t.charAt(n+1);if(a!==""&&Number(a)==a){const i=n+1;for(;++n;){const o=t.charAt(n);if(o==null||Number(o)!=o){--n;break}if(n===t.length)break}r.id=Number(t.substring(i,n+1))}if(t.charAt(++n)){const i=this.tryParse(t.substr(n));if(lp.isPayloadValid(r.type,i))r.data=i;else throw new Error("invalid payload")}return r}tryParse(t){try{return JSON.parse(t,this.reviver)}catch{return!1}}static isPayloadValid(t,n){switch(t){case Pe.CONNECT:return m2(n);case Pe.DISCONNECT:return n===void 0;case Pe.CONNECT_ERROR:return typeof n=="string"||m2(n);case Pe.EVENT:case Pe.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&g_e.indexOf(n[0])===-1);case Pe.ACK:case Pe.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class k_e{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const n=f_e(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const v_e=Object.freeze(Object.defineProperty({__proto__:null,Decoder:lp,Encoder:b_e,get PacketType(){return Pe},protocol:y_e},Symbol.toStringTag,{value:"Module"}));function cn(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const __e=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class $3 extends ct{constructor(t,n,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=n,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[cn(t,"open",this.onopen.bind(this)),cn(t,"packet",this.onpacket.bind(this)),cn(t,"error",this.onerror.bind(this)),cn(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...n){var r,a,i;if(__e.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(n.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(n),this;const o={type:Pe.EVENT,data:n};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const d=this.ids++,p=n.pop();this._registerAckCallback(d,p),o.id=d}const s=(a=(r=this.io.engine)===null||r===void 0?void 0:r.transport)===null||a===void 0?void 0:a.writable,l=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!s||(l?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(t,n){var r;const a=(r=this.flags.timeout)!==null&&r!==void 0?r:this._opts.ackTimeout;if(a===void 0){this.acks[t]=n;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let s=0;s<this.sendBuffer.length;s++)this.sendBuffer[s].id===t&&this.sendBuffer.splice(s,1);n.call(this,new Error("operation has timed out"))},a),o=(...s)=>{this.io.clearTimeoutFn(i),n.apply(this,s)};o.withError=!0,this.acks[t]=o}emitWithAck(t,...n){return new Promise((r,a)=>{const i=(o,s)=>o?a(o):r(s);i.withError=!0,n.push(i),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((a,...i)=>r!==this._queue[0]?void 0:(a!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(a)):(this._queue.shift(),n&&n(null,...i)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:Pe.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(r=>String(r.id)===t)){const r=this.acks[t];delete this.acks[t],r.withError&&r.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case Pe.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Pe.EVENT:case Pe.BINARY_EVENT:this.onevent(t);break;case Pe.ACK:case Pe.BINARY_ACK:this.onack(t);break;case Pe.DISCONNECT:this.ondisconnect();break;case Pe.CONNECT_ERROR:this.destroy();const r=new Error(t.data.message);r.data=t.data.data,this.emitReserved("connect_error",r);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const r of n)r.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let r=!1;return function(...a){r||(r=!0,n.packet({type:Pe.ACK,id:t,data:a}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(delete this.acks[t.id],n.withError&&t.data.unshift(null),n.apply(this,t.data))}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Pe.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let r=0;r<n.length;r++)if(t===n[r])return n.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const n=this._anyOutgoingListeners;for(let r=0;r<n.length;r++)if(t===n[r])return n.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const n=this._anyOutgoingListeners.slice();for(const r of n)r.apply(this,t.data)}}}function jr(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}jr.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0};jr.prototype.reset=function(){this.attempts=0};jr.prototype.setMin=function(e){this.ms=e};jr.prototype.setMax=function(e){this.max=e};jr.prototype.setJitter=function(e){this.jitter=e};class id extends ct{constructor(t,n){var r;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,mo(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((r=n.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new jr({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const a=n.parser||v_e;this.encoder=new a.Encoder,this.decoder=new a.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new l_e(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const a=cn(n,"open",function(){r.onopen(),t&&t()}),i=s=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",s),t?t(s):this.maybeReconnectOnOpen()},o=cn(n,"error",i);if(this._timeout!==!1){const s=this._timeout,l=this.setTimeoutFn(()=>{a(),i(new Error("timeout")),n.close()},s);this.opts.autoUnref&&l.unref(),this.subs.push(()=>{this.clearTimeoutFn(l)})}return this.subs.push(a),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(cn(t,"ping",this.onping.bind(this)),cn(t,"data",this.ondata.bind(this)),cn(t,"error",this.onerror.bind(this)),cn(t,"close",this.onclose.bind(this)),cn(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){ho(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let r=this.nsps[t];return r?this._autoConnect&&!r.active&&r.connect():(r=new $3(this,t,n),this.nsps[t]=r),r}_destroy(t){const n=Object.keys(this.nsps);for(const r of n)if(this.nsps[r].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let r=0;r<n.length;r++)this.engine.write(n[r],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,n){var r;this.cleanup(),(r=this.engine)===null||r===void 0||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(a=>{a?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",a)):t.onreconnect()}))},n);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Zr={};function _i(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=c_e(e,t.path||"/socket.io"),r=n.source,a=n.id,i=n.path,o=Zr[a]&&i in Zr[a].nsps,s=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let l;return s?l=new id(r,t):(Zr[a]||(Zr[a]=new id(r,t)),l=Zr[a]),n.query&&!t.query&&(t.query=n.queryKey),l.socket(n.path,t)}Object.assign(_i,{Manager:id,Socket:$3,io:_i,connect:_i});const w_e=V.createContext(null),x_e=({children:e})=>{const t=He(),n=be(v=>v.upsertChat),r=be(v=>v.upsertChatState),a=be(v=>v.contextKey),i=be(v=>v.activeChatId),o=V.useMemo(()=>t.config.user?.id??Hr(),[t.config.user?.id]),s=t.config.transport,[l,u]=V.useState(null),[d,p]=V.useState(void 0),m=V.useRef(a),h=V.useRef(n),g=V.useRef(r),f=V.useRef(void 0);V.useEffect(()=>{m.current=a,h.current=n,g.current=r},[a,n,r]),V.useEffect(()=>{if(s.mode!=="proxy"){u(null),p(void 0),t.setSocketClient(null),t.transport instanceof Or&&t.transport.setSocketId(void 0);return}const v=s.baseUrl,k=new URL(v,window.location.origin),_=`${k.protocol}//${k.host}`,E=s.socketNamespace,S=E?`${_}${E}`:_,x={},D=s;D.headers&&Object.assign(x,D.headers);const P={},C=D.apiKey&&`Bearer ${D.apiKey}`||D.headers?.Authorization;C&&(P.authorization=C,x.Authorization=C);const L=s.socketPath??Ai.Path,G=_i(S,{path:L,auth:P,transports:["websocket","polling"],withCredentials:!0,...Object.keys(x).length>0&&{extraHeaders:x}});t.setSocketClient(G),u(G);const X=()=>{p(G.id),t.transport instanceof Or&&t.transport.setSocketId(G.id)},J=()=>{p(void 0),t.transport instanceof Or&&t.transport.setSocketId(void 0)},K=H=>{if(H.contextKey===m.current){h.current(H);const z=t.store.getState(),j=$e(z,H.id);g.current(H.id,{...j,status:Di(H.status)})}},R=H=>{const z=t.store.getState(),j=$e(z,H.chat),A=j.messages.findIndex(Y=>Y.id===H.id);if(A>=0){const Y=[...j.messages];Y[A]=H,g.current(H.chat,{...j,messages:Y});return}g.current(H.chat,{...j,messages:[...j.messages,H]})},B=H=>{h.current(H);const z=t.store.getState(),j=$e(z,H.id);g.current(H.id,{...j,status:Di(H.status)})};return G.on("connect",X),G.on("disconnect",J),G.on("connect_error",H=>{console.error("Socket.IO connection error:",H.message)}),G.on(fi.ChatNew,K),G.on(fi.MessageNew,R),G.on(fi.ChatUpdate,B),()=>{t.transport instanceof Or&&t.transport.setSocketId(void 0),t.setSocketClient(null),p(void 0),u(null),G.disconnect()}},[t,t.transport,s.mode,s.mode==="proxy"?s.baseUrl:void 0,s.mode==="proxy"?s.apiKey:void 0,s.mode==="proxy"?s.socketPath:void 0,s.mode==="proxy"?s.socketNamespace:void 0,s.mode==="proxy"?JSON.stringify(s.headers??{}):"",o]),V.useEffect(()=>{if(!l)return;const v=f.current;v&&v!==i&&l.emit("chat:unsubscribe",{chatId:v}),i&&i!==v&&(l.emit("chat:subscribe",{chatId:i}),f.current=i),i||(f.current=void 0)},[l,i]);const w=V.useMemo(()=>({socket:l,socketId:d}),[l,d]);return N.jsx(w_e.Provider,{value:w,children:e})},cp=V.createContext(null),E_e=({config:e,children:t})=>{const n=V.useRef();n.current||(n.current=new g3(e));const[,r]=V.useState(0);V.useEffect(()=>{const o=n.current,s=()=>r(l=>l+1);return o.events.addEventListener("runtime:transport-config-changed",s),()=>{o.events.removeEventListener("runtime:transport-config-changed",s)}},[]);const a=V.useRef();if(!a.current){const o=n.current.defaultContextKey??n.current.config.contextKeys[0]?.key??"default";a.current=m7e(o),n.current.attachStore(a.current);const s=M7e(n.current.config.models,n.current.config.transport);a.current.getState().setComposerOptions({model:s})}const i=V.useMemo(()=>({runtime:n.current,store:a.current}),[]);return V.useEffect(()=>{const o=a.current;if(!o)return;let s=o.getState().activeChatId;return o.subscribe(()=>{const l=o.getState().activeChatId;if(l===s)return;s=l;const u=n.current?.config.user?.id??Hr();A7e(u,l)})},[]),N.jsx(cp.Provider,{value:i,children:N.jsx(yt.QueryClientProvider,{client:i.runtime.queryClient,children:N.jsx(k3,{value:i.runtime.config.theme,children:N.jsx(x_e,{children:t})})})})},He=()=>{const e=V.useContext(cp);if(!e)throw new Error("useAgentRuntime must be used inside <AgentProvider />");return e.runtime},be=e=>{const t=V.useContext(cp);if(!t)throw new Error("useAgentStore must be used inside <AgentProvider />");return r5.useStore(t.store,e)},M_e=({initialSystemPrompt:e,composerFormRef:t,multiUser:n=!1,participantIds:r=[]})=>{const a=He(),{composer:i,contextKey:o,activeChatId:s,draftChatKey:l,queuedMessages:u,activeChatStatus:d,upsertChat:p,setChatStatus:m,setActiveChat:h,setComposerError:g,moveChatKeyState:f,removeQueuedMessage:w,setPendingAssistant:v,enqueueQueuedMessage:k,appendMessagesToChat:_,commitPendingAssistant:E,setPageContextDismissed:S}=be(j=>{const A=j.activeChatId??j.draftChatKey,Y=$e(j,A);return{composer:j.composer,contextKey:j.contextKey,activeChatId:j.activeChatId,draftChatKey:j.draftChatKey,queuedMessages:Y.messageQueue,activeChatStatus:Y.status,upsertChat:j.upsertChat,setActiveChat:j.setActiveChat,setChatStatus:j.setChatStatus,setComposerError:j.setComposerError,moveChatKeyState:j.moveChatKeyState,setPendingAssistant:j.setPendingAssistant,removeQueuedMessage:j.removeQueuedMessage,enqueueQueuedMessage:j.enqueueQueuedMessage,appendMessagesToChat:j.appendMessagesToChat,commitPendingAssistant:j.commitPendingAssistant,setPageContextDismissed:j.setPageContextDismissed}}),x=V.useCallback(j=>!j||j.length===0?!1:j.some(A=>A.type===exports.AgentAttachmentType.Context&&A?.metadata?.kind==="pageContext"),[]),D=V.useRef(!1),P=V.useRef(!1),C=V.useRef(void 0),L=V.useRef(new Set),G=s??l,X=V.useCallback(async(j,A)=>{if(!a.transport.generateTitle)return;const Y=a.config.features?.titleGeneration==="llm"?"llm":"local";let ee;try{ee=await a.transport.generateTitle({userId:A,content:j,strategy:Y,contextKey:o})}catch{}return ee},[a.transport,a.config.features?.titleGeneration,o]),J=V.useCallback(async(j,A=[])=>{const Y=a.config.user?.id??"guest",ee=!s,O=s??l,se={current:O};C.current=O;const ge={value:j,attachments:A};g(se.current,void 0);let ke;if(ee){const ce=await X(j,Y);ce&&ce.trim().length>0&&(ke={...ke??{},title:ce})}const Te=a.store.getState(),qe=s?Te.chats[s]:void 0,re=(s?Te.chatState[s]:void 0)?.messages??[],_e=A.filter(ce=>F3(ce)?!S_e(re,ce):!0),Ge=qe?.model,We=i.model!==Ge;let Ce,Re=!1;We?(Ce=i.model,Re=!0):Ge?(Ce=Ge,Re=!1):(Ce=void 0,Re=!1);const Se=N_e(j),Be={userId:Y,content:j,metadata:ke,contextKey:o,...ee?{}:{chatId:s},...Re?{model:Ce??""}:{},..._e.length>0?{attachments:_e}:{},...n?{mentions:Se,participantIds:Array.from(new Set([Y,...r])),senderDisplayName:a.config.user?.displayName,senderAvatarUrl:a.config.user?.avatarUrl}:{}},de=()=>{v(se.current,void 0)},et=ce=>{if(ce?.name==="AbortError"){const Me=C.current??se.current;return L.current.has(Me)?(E(se.current),L.current.delete(Me)):(de(),t.current?.setDraft(ge)),{type:"aborted"}}throw ce},tt=async()=>{m(se.current,vt.Sending);try{if(!a.transport.sendMultiUserMessage)throw new Error("Multi-user chat requires a transport that supports sendMultiUserMessage");const ce=await a.transport.sendMultiUserMessage(Be);return p(ce.chat),ee&&(f(se.current,ce.chat.id),se.current=ce.chat.id,C.current=ce.chat.id,h(ce.chat.id)),_(ce.chat.id,[ce.message]),m(ce.chat.id,Di(ce.chat.status)),de(),{type:"success"}}catch(ce){return et(ce)}},je=async()=>{let ce=`pending-${Date.now()}`,Me="",ye;m(se.current,vt.Streaming),v(se.current,{id:ce,content:"",reasoning:"",toolCalls:[],attachments:[],chat:s||"",role:exports.MessageRole.Assistant,createdAt:new Date().toISOString()});try{let Fe=s;const q=ne=>{if(ne.type===exports.StreamChunkType.Chat&&ne.chat){p(ne.chat),Fe=ne.chat.id,ee&&(C.current=ne.chat.id,f(se.current,ne.chat.id),se.current=ne.chat.id,h(ne.chat.id));return}if(ne.type===exports.StreamChunkType.Reasoning&&ne.reasoning){Me+=ne.reasoning,ye={...ye??{id:ce,chat:Fe,role:exports.MessageRole.Assistant,content:"",createdAt:new Date().toISOString()},reasoning:Me},v(se.current,ye);return}if(ne.type===exports.StreamChunkType.Error&&ne.error)throw new Error(ne.error);if(ne.message&&ne.message.role===exports.MessageRole.User){_(ne.message.chat,[ne.message]);return}ne.message&&(ce=ne.message.id,ye={...ne.message,reasoning:Me||ne.message.reasoning},v(se.current,ye)),ne.done&&(ye&&_(se.current,[ye]),m(se.current,vt.Idle),de())},Z=await a.transport.streamMessage(Be,q,{streamKey:C.current});if(Z){const ne=Z.messages.map(De=>ye&&De.id===ye.id&&De.role===exports.MessageRole.Assistant?{...De,reasoning:Me}:De);_(Z.id,ne);const pe=a.store.getState();return(pe.activeChatId??pe.draftChatKey)===se.current&&h(Z.id),de(),{type:"success"}}return de(),{type:"success"}}catch(Fe){return et(Fe)}};try{const ce=await(n?tt():je());return ce.type==="success"&&(D.current=!1),ce}catch(ce){de();const Me=ce?.chat;Me&&(p(Me),h(Me.id));const ye=ce instanceof Error?ce:new Error("Failed to send message");return g(se.current,ye.message||"Failed to send message"),m(se.current,vt.Idle),t.current?.setDraft(ge),D.current=!1,{type:"error",error:ye}}finally{P.current=!1,n||m(se.current,vt.Idle),C.current=void 0}},[s,o,i.model,n,r,a.transport,a.config.user?.displayName,a.config.user?.avatarUrl,a.config.user?.id,p,h,v,m,X,e,f,t,g]),K=V.useCallback(async()=>{if(d!==vt.Idle||P.current||!u.length||D.current)return;const j=u[0];P.current=!0,w(G,j.id);try{await J(j.content,j.attachments)}finally{P.current=!1}},[d,u,G,J,w]);V.useEffect(()=>{K()},[K]);const R=V.useCallback(async j=>{if(P.current)return;const A=u.find(Y=>Y.id===j);if(A){D.current=!1,P.current=!0,w(G,j);try{await J(A.content,A.attachments)}finally{P.current=!1}}},[u,G,w,J]),B=V.useCallback(async j=>{const Y=t.current.getDraft().attachments;if(!n&&d!==vt.Idle){k(G,j,Y),t.current?.clearDraft();return}D.current=!1,t.current?.clearDraft(),await J(j,Y)},[d,n,k,G,J,t,x,S]),H=V.useCallback(()=>{D.current=!0;const j=C.current??G;L.current.add(j),a.transport.cancelStream?.(j),E(j),m(j,vt.Idle)},[G,a.transport,E,m]),z=V.useCallback(async j=>{d===vt.Streaming&&H(),await R(j)},[d,H,R]);return{pendingKey:G,queuedMessages:u,activeChatStatus:n?vt.Idle:d,activeChatId:s,removeQueuedMessage:w,handleSubmit:B,handleStop:H,handleQueuedClick:z}},S_e=(e,t)=>{const n=JSON.stringify(t.metadata?.data);let r;for(let a=e.length-1;a>=0;a--){const o=e[a].attachments?.find(F3);if(o){r=o;break}}return!r||r.url!==t.url?!1:JSON.stringify(r.metadata?.data)===n},F3=e=>e.type===exports.AgentAttachmentType.Context&&e.metadata?.kind==="pageContext",N_e=e=>{const t=e.matchAll(/(^|[\s([{])@([a-zA-Z0-9_.-]+)/g),n=new Set,r=[];for(const a of t){const i=a[2],o=i.toLowerCase();n.has(o)||(n.add(o),r.push({type:o==="agent"?"agent":"user",name:i}))}return r.length>0?r:void 0},A_e=({queuedMessages:e,onSendQueued:t,onRemoveQueued:n})=>e.length?N.jsxs("div",{className:"mp-agent-composer-queue",children:[N.jsx("div",{className:"mp-agent-composer-queue-header",children:N.jsxs("span",{children:[e.length," message",e.length>1?"s":""," queued"]})}),N.jsx("div",{className:"mp-agent-composer-queue-items",children:e.map(r=>N.jsxs("div",{className:"mp-agent-composer-queue-item",children:[N.jsxs("span",{className:"mp-agent-composer-queue-item-text",children:[r.content,r.attachments?.length?N.jsxs("span",{style:{marginLeft:8,opacity:.7,display:"inline-flex",alignItems:"center",gap:4},children:[N.jsx(Qi,{size:12}),r.attachments.length]}):null]}),N.jsxs("div",{className:"mp-agent-composer-queue-item-actions",children:[N.jsx("button",{type:"button",className:"mp-agent-composer-queue-button",onClick:()=>t(r.id),"aria-label":"Send queued message",children:N.jsx(Dd,{size:12})}),N.jsx("button",{type:"button",className:"mp-agent-composer-queue-button",onClick:()=>n(r.id),"aria-label":"Remove queued message",children:N.jsx(v5,{size:12})})]})]},r.id))})]}):null;function T_e(e,t){return e.size>t.maxFileSize?{type:"size",message:`File "${e.name}" exceeds maximum size of ${up(t.maxFileSize)}`,fileName:e.name}:null}function C_e(e,t,n){if(e.length+t.filter(s=>s.type==="file").length>n.maxFilesPerMessage)return{type:"count",message:`Maximum ${n.maxFilesPerMessage} files per message allowed`};for(const s of e){const l=T_e(s,n);if(l)return l}const a=t.filter(s=>s.type==="file").reduce((s,l)=>{const u=l.metadata?.size||l.size||0;return s+u},0),i=e.reduce((s,l)=>s+l.size,0);return a+i>n.maxTotalAttachmentsSize?{type:"totalSize",message:`Total attachment size exceeds maximum of ${up(n.maxTotalAttachmentsSize)}`}:null}function up(e){if(e===0)return"0 Bytes";const t=1024,n=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return Math.round(e/Math.pow(t,r)*100)/100+" "+n[r]}function R_e(){return{maxFileSize:10*1024*1024,maxTotalAttachmentsSize:50*1024*1024,maxFilesPerMessage:10,allowedMimeTypes:void 0}}const P3=e=>{switch(e.type){case exports.AgentAttachmentType.Link:return N.jsx(g5,{size:12});case exports.AgentAttachmentType.Artifact:return N.jsx(Qi,{size:12});case exports.AgentAttachmentType.Context:switch(e?.metadata?.kind){case"pageContext":return N.jsx($d,{size:12});case"formSnapshot":case"formField":return N.jsx(f5,{size:12});default:return N.jsx(Fd,{size:12})}case exports.AgentAttachmentType.File:default:return N.jsx(m5,{size:12})}},I_e=({attachments:e})=>!e||e.length===0?null:N.jsx("div",{className:"mp-agent-message-attachments","aria-label":"Message attachments",children:e.map((t,n)=>{const r=N.jsxs(N.Fragment,{children:[N.jsx("span",{className:"mp-agent-message-attachment-icon",children:P3(t)}),N.jsx("span",{className:"mp-agent-message-attachment-name",children:t.name})]});return t.url?N.jsx("a",{className:"mp-agent-message-attachment",href:t.url,target:"_blank",rel:"noreferrer",title:t.url,children:r},t.id||n):N.jsx("span",{className:"mp-agent-message-attachment",title:t.mimeType??t.name,children:r},t.id||n)})}),O_e=({attachments:e,onRemove:t,uploadProgress:n,uploadErrors:r})=>{const a=Wt();return!e||e.length===0?null:N.jsx("div",{className:"mp-agent-composer-attachments","aria-label":a.attachments,children:e.map(i=>{const o=n?.get(i.id),s=r?.get(i.name),l=i.metadata?.size||i.size,u=l?` (${up(l)})`:"";return N.jsxs("span",{className:`mp-agent-attachment-chip ${s?"mp-agent-attachment-chip-error":""} ${o?.status==="uploading"?"mp-agent-attachment-chip-uploading":""}`,title:s||i.name,children:[N.jsx("span",{className:"mp-agent-attachment-chip-icon",children:P3(i)}),N.jsxs("span",{className:"mp-agent-attachment-chip-name",title:i.name,children:[i.name,u]}),o?.status==="uploading"&&N.jsxs("span",{className:"mp-agent-attachment-chip-progress",children:[o.progress,"%"]}),s&&N.jsx("span",{className:"mp-agent-attachment-chip-error-text",title:s,children:"⚠"}),t?N.jsx(nn,{size:"sm",icon:"X",type:"button",onClick:d=>{d.preventDefault(),d.stopPropagation(),t(i.id)},"aria-label":`Remove attachment ${i.name}`}):null]},i.id)})})},L_e=e=>{const t=e.trim();if(!t||/\s/.test(t))return;const n=i=>i.replace(/[)\].,;:!?]+$/,"");if(!/^https?:\/\//i.test(t))return;const r=i=>{try{const o=new URL(i);return o.protocol!=="http:"&&o.protocol!=="https:"?void 0:o.toString()}catch{return}},a=n(t);return r(a)},D_e=e=>{try{const t=new URL(e);return t.hostname+(t.pathname&&t.pathname!=="/"?t.pathname:"")}catch{return e}},od="mp-agent:locationchange",f2="__mp_agent_history_patched__",g2=()=>{try{window.dispatchEvent(new Event(od))}catch{}},z_e=()=>{if(typeof window>"u")return;const e=window;if(!e[f2]){e[f2]=!0;try{const t=history.pushState;history.pushState=function(...n){const r=t.apply(this,n);return g2(),r}}catch{}try{const t=history.replaceState;history.replaceState=function(...n){const r=t.apply(this,n);return g2(),r}}catch{}}},$_e=e=>{if(typeof window>"u")return()=>{};z_e();const t=()=>e();return window.addEventListener("popstate",t),window.addEventListener("hashchange",t),window.addEventListener(od,t),()=>{window.removeEventListener("popstate",t),window.removeEventListener("hashchange",t),window.removeEventListener(od,t)}};async function F_e(e,t,n,r){const a=await fetch(r.presignedUrlEndpoint,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...r.getAuthHeaders?.()||{}},body:JSON.stringify({filename:e.name,mimeType:e.type||"application/octet-stream",size:e.size,chatId:t,userId:n})});if(!a.ok){const o=await a.text();throw new Error(`Failed to get presigned URL: ${a.status} ${o}`)}const i=await a.json();return{url:i.url,key:i.key}}async function P_e(e,t,n){return new Promise((r,a)=>{const i=new XMLHttpRequest;i.upload.addEventListener("progress",o=>{if(o.lengthComputable&&n){const s=Math.round(o.loaded/o.total*100);n(s)}}),i.addEventListener("load",()=>{i.status>=200&&i.status<300?r():a(new Error(`Upload failed: ${i.status} ${i.statusText}`))}),i.addEventListener("error",()=>{a(new Error("Upload failed: network error"))}),i.addEventListener("abort",()=>{a(new Error("Upload aborted"))}),i.open("PUT",t),i.setRequestHeader("Content-Type",e.type||"application/octet-stream"),i.send(e)})}async function q_e(e,t,n){const r=_t.nanoid(),a={fileId:r,fileName:e.name,progress:0,status:"pending"};try{n.onProgress?.({...a,status:"uploading",progress:0});const{url:i,key:o}=await F_e(e,n.chatId,n.userId,t);return await P_e(e,i,s=>{n.onProgress?.({...a,status:"uploading",progress:s})}),n.onProgress?.({...a,status:"completed",progress:100}),{id:r,type:exports.AgentAttachmentType.File,name:e.name,mimeType:e.type||void 0,size:e.size,metadata:{uploadedAt:new Date().toISOString(),s3Key:o,processingStatus:"pending",size:e.size,lastModified:e.lastModified}}}catch(i){const o=i instanceof Error?i.message:"Unknown error";throw n.onProgress?.({...a,status:"error",error:o}),i}}async function B_e(e,t,n){const r=await Promise.allSettled(e.map(o=>q_e(o,t,n))),a=[],i=[];if(r.forEach((o,s)=>{o.status==="fulfilled"?a.push(o.value):i.push(new Error(`Failed to process ${e[s].name}: ${o.reason}`))}),i.length>0&&a.length===0)throw i[0];return i.length>0&&console.warn("Some files failed to upload:",i),a}const U_e=({options:e,value:t,onChange:n,placeholder:r="Select...",disabled:a=!1,className:i="",triggerClassName:o="",placement:s="bottom-start",searchable:l=!1,searchPlaceholder:u="Search...",searchFilter:d})=>{const[p,m]=V.useState(!1),[h,g]=V.useState(null),[f,w]=V.useState(""),v=V.useRef([]),k=V.useRef(null),{refs:_,floatingStyles:E,context:S,isPositioned:x}=Zd({open:p,onOpenChange:m,placement:s,strategy:"absolute",whileElementsMounted:jd,middleware:[Vd(8),Wd({fallbackPlacements:["top-start","bottom-start","top-end","bottom-end"]}),Gd({padding:8})]}),D=Y5(S,{enabled:!a}),P=Yd(S),C=Qd(S),G=a7e(S,{listRef:v,activeIndex:h,onNavigate:g,enabled:p&&!l,virtual:!1}),{getReferenceProps:X,getFloatingProps:J,getItemProps:K}=Xd(l?[D,P,C]:[D,P,C,G]),R=e.findIndex(Y=>Y.value===t),B=R>=0?e[R]:void 0,H=V.useMemo(()=>{const Y=f.trim().toLowerCase();if(!l||!Y)return e;const O=d?se=>d(se,Y):se=>`${se.label} ${se.description??""}`.toLowerCase().includes(Y);return e.filter(O)},[e,f,l,d]);V.useEffect(()=>{if(!p){g(null),w("");return}l&&setTimeout(()=>k.current?.focus(),0);const Y=H.findIndex(ee=>ee.value===t);g(Y>=0?Y:0)},[p,l,t,H]),V.useEffect(()=>{p&&g(H.length>0?0:null)},[f,H.length,p]);const z=Y=>H.length===0?null:Y<0?H.length-1:Y>=H.length?0:Y,j=Y=>{Y!=null&&v.current[Y]?.scrollIntoView({block:"nearest"})},A=Y=>{n(Y),m(!1),g(null),w("")};return N.jsxs("div",{className:`mp-agent-dropdown ${i}`,children:[N.jsxs("button",{ref:_.setReference,type:"button",className:`mp-agent-dropdown-trigger ${o}`,disabled:a,"aria-expanded":p,"aria-haspopup":"listbox",...X(),children:[N.jsx("span",{className:"mp-agent-dropdown-trigger-content",children:B?N.jsxs(N.Fragment,{children:[B.icon&&N.jsx("span",{className:"mp-agent-dropdown-trigger-icon",children:B.icon}),N.jsx("span",{className:"mp-agent-dropdown-trigger-label",children:B.label})]}):N.jsx("span",{className:"mp-agent-dropdown-trigger-placeholder",children:r})}),N.jsx(zd,{size:16,className:`mp-agent-dropdown-chevron ${p?"open":""}`})]}),p&&N.jsxs("div",{role:"listbox",ref:_.setFloating,style:{...E,opacity:x?1:0,pointerEvents:x?"auto":"none",transition:x?"opacity 0.15s ease-out":"none"},className:"mp-agent-dropdown-menu",...J(),children:[l&&N.jsx("div",{className:"mp-agent-dropdown-search",onKeyDown:Y=>Y.stopPropagation(),children:N.jsx("input",{ref:k,className:"mp-agent-dropdown-search-input",value:f,placeholder:u,onChange:Y=>w(Y.target.value),onKeyDown:Y=>{if(Y.key==="Escape"){Y.preventDefault(),m(!1),w("");return}if(Y.key==="ArrowDown"||Y.key==="ArrowUp"){Y.preventDefault();const ee=Y.key==="ArrowDown"?1:-1,O=h??(ee>0?-1:0),se=z(O+ee);g(se),j(se);return}if(Y.key==="Enter"){if(h==null)return;const ee=H[h];if(!ee)return;Y.preventDefault(),A(ee.value)}}})}),N.jsxs("div",{className:"mp-agent-dropdown-list",children:[H.map((Y,ee)=>N.jsxs("button",{ref:O=>{v.current[ee]=O},type:"button",className:`mp-agent-dropdown-item ${t===Y.value?"selected":""} ${h===ee?"active":""}`,role:"option","aria-selected":t===Y.value,...K({onClick:()=>A(Y.value),onMouseEnter:()=>{g(ee)},onKeyDown:O=>{(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),A(Y.value))}}),children:[Y.icon&&N.jsx("span",{className:"mp-agent-dropdown-item-icon",children:Y.icon}),N.jsxs("span",{className:"mp-agent-dropdown-item-content",children:[N.jsx("span",{className:"mp-agent-dropdown-item-label",children:Y.label}),Y.description&&N.jsx("span",{className:"mp-agent-dropdown-item-description",children:Y.description})]})]},Y.value)),l&&H.length===0&&N.jsx("div",{className:"mp-agent-dropdown-empty","aria-label":"No results",children:"No results"})]})]})]})},H_e=V.memo(()=>{const e=He(),t=be(p=>p.composer),n=be(p=>p.contextKey),r=be(p=>p.setComposerOptions),a=e.config.models,{data:i,isLoading:o}=a3(),s=V.useMemo(()=>{const p=i&&i.length>0?i:a;return w3(p,e.config.transport).filter(h=>!h.contexts?.length||h.contexts.includes(n))},[i,a,e.config.transport,n]),l=V.useMemo(()=>{const p=s.slice().sort((m,h)=>m.label.localeCompare(h.label,void 0,{sensitivity:"base"})).map(m=>({value:m.id,label:m.label}));return[{value:ta,label:"Auto"},...p]},[s]),u=V.useMemo(()=>t.model!==void 0?t.model:ta,[t.model]),d=V.useCallback(p=>{p===ta?(r({model:void 0}),c2(e.config.transport,ta)):(r({model:p}),c2(e.config.transport,p))},[r,e.config.transport]);return o&&!a?.length||l.length===0?null:N.jsx(U_e,{options:l,value:u,onChange:d,placeholder:"Select model...",searchable:!0,searchPlaceholder:"Search models...",placement:"top-start",triggerClassName:"mp-agent-model-selector-trigger"})}),j_e=e=>{if(!e)return"";let t=e.replace(/[_-]+/g," ");return t=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2"),t=t.trim().replace(/\s+/g," "),t?t.charAt(0).toUpperCase()+t.slice(1):""},V_e=({checked:e,disabled:t,onChange:n,className:r="",...a})=>{const i=o=>{o.preventDefault(),!t&&n(!e)};return N.jsx("button",{type:"button",role:"switch","aria-checked":e,disabled:t,className:`mp-agent-switch ${e?"on":"off"} ${r}`.trim(),onClick:i,...a,children:N.jsx("span",{className:"mp-agent-switch-thumb"})})},y2=e=>e.reduce((t,n)=>(t[n.agentName]={...n.tools},t),{}),q3=({preferences:e,disabled:t})=>{const n=Wt(),{upsertSingle:r}=u3(),[a,i]=V.useState(()=>y2(e)),[o,s]=V.useState({});V.useEffect(()=>{i(y2(e))},[e]);const l=r.error?.message,u=V.useMemo(()=>e.some(p=>Object.keys(p.tools).length>0),[e]),d=(p,m,h)=>{i(g=>{const f=g[p]??{},w=f,v={...f,[m]:h},k={...g,[p]:v};return s(_=>({..._,[p]:{..._[p]??{},[m]:!0}})),r.mutate({agentName:p,input:{tools:v}},{onError:()=>{i(_=>({..._,[p]:w}))},onSettled:()=>{s(_=>{const E={..._[p]??{}};if(delete E[m],Object.keys(E).length===0){const{[p]:S,...x}=_;return x}return{..._,[p]:E}})}}),k})};return N.jsxs("div",{className:"mp-agent-preferences-panel",children:[!u&&N.jsx("div",{className:"mp-agent-preferences-empty",children:n.agentSettingsNoConfigurableTools}),e.map(p=>{const m=a[p.agentName]??{},h=Object.entries(m);return N.jsxs("div",{className:"mp-agent-preferences-agent",children:[N.jsx("div",{className:"mp-agent-preferences-agent-header",children:N.jsx("strong",{children:p.agentName})}),h.length===0?N.jsx("div",{className:"mp-agent-preferences-empty",children:n.agentSettingsNoToolsForAgent}):N.jsx("div",{className:"mp-agent-preferences-tools",children:h.map(([g,f])=>{const w=!!o[p.agentName]?.[g];return N.jsxs("label",{className:"mp-agent-preferences-tool",children:[N.jsx("span",{className:"mp-agent-preferences-tool-label",children:j_e(g)}),N.jsx(V_e,{checked:f,onChange:v=>d(p.agentName,g,v),disabled:!!t||w})]},`${p.agentName}:${g}`)})})]},p.agentName)}),l&&N.jsx("div",{className:"mp-agent-preferences-error",children:l})]})};function G_e(e){return e.map(t=>{const n=(t.tools??[]).reduce((r,a)=>(a.userConfigurable&&(r[a.title]=!a.disabledByDefault),r),{});return{agentName:t.name,tools:n}})}const W_e=()=>{const e=Wt(),t=He(),n=be(l=>l.contextKey),{data:r,isLoading:a,isError:i}=s3(n),o=V.useMemo(()=>G_e(r??[]),[r]),s=!!t.transport.upsertAgentPreferences&&!!t.transport.upsertAgentPreferencesBatch;return a?N.jsx(N.Fragment,{children:e.agentSettingsLoading}):i?N.jsx(N.Fragment,{children:e.agentSettingsError}):N.jsx(q3,{preferences:o,disabled:!s})},K_e=()=>{const[e,t]=V.useState(!1),n=Wt(),{refs:r,floatingStyles:a,context:i,isPositioned:o}=Zd({open:e,onOpenChange:t,placement:"top-start",strategy:"absolute",whileElementsMounted:jd,middleware:[Vd(8),Wd({fallbackPlacements:["bottom-start","top-end","bottom-end"]}),Gd({padding:8})]}),s=Y5(i),l=Yd(i),u=Qd(i),{getReferenceProps:d,getFloatingProps:p}=Xd([s,l,u]);return N.jsxs("div",{className:"mp-agent-tool-config-dropdown",children:[N.jsx(bn,{content:n.agentSettingsTooltip,children:N.jsx("button",{ref:r.setReference,type:"button",className:"mp-agent-composer-button mp-agent-composer-tool-button","aria-label":n.agentSettingsTooltip,...d(),children:N.jsx(y5,{size:16})})}),e&&N.jsx("div",{ref:r.setFloating,style:{...a,opacity:o?1:0,pointerEvents:o?"auto":"none",transition:o?"opacity 0.15s ease-out":"none"},className:"mp-agent-tool-config-panel",...p(),children:N.jsx(W_e,{})})]})},Y_e=V.forwardRef(({autoFocus:e,activeChatId:t,status:n,onStop:r,onSubmit:a},i)=>{const o=Wt(),s=He(),l=V.useRef(null),u=V.useRef(null),d=be(re=>re.activeChatId??re.draftChatKey),p=be(re=>$e(re,d).composerDraft),m=be(re=>$e(re,d).composerError),h=be(re=>$e(re,d).pageContextDismissed),g=be(re=>re.setComposerValue),f=be(re=>re.setComposerDraft),w=be(re=>re.clearComposerDraft),v=be(re=>re.setComposerError),k=be(re=>re.addComposerAttachments),_=be(re=>re.removeComposerAttachment),E=be(re=>re.setPageContextDismissed),S=p.value,x=p.attachments,[D,P]=V.useState(new Map),[C,L]=V.useState(new Map),G=V.useRef(S),X=V.useRef(x),J=V.useRef(h),K=s.config.features?.pageContextAttachments!==!1,R=re=>re.type===exports.AgentAttachmentType.Context&&re?.metadata?.kind==="pageContext",B=x.some(R),H=()=>{if(K)return s.buildPageContextAttachment()};V.useEffect(()=>{X.current=x},[x]),V.useEffect(()=>{G.current=S},[S]),V.useEffect(()=>{J.current=h},[h]),V.useEffect(()=>{if(!K||h||B)return;const re=H();re&&k(d,[re])},[K,h,B,d,k]),V.useEffect(()=>{if(K&&!(typeof window>"u"))return $_e(()=>{if(J.current)return;const re=X.current,_e=re.find(R);if(!_e)return;const Ge=H();if(!Ge)return;const We={...Ge,id:_e.id},Ce=re.map(Re=>Re.id===_e.id?We:Re);f(d,{value:G.current,attachments:Ce})})},[K,d,f]),V.useImperativeHandle(i,()=>({setValue:re=>{g(d,re)},getDraft:()=>({value:S,attachments:x}),setDraft:re=>{f(d,{value:re.value,attachments:re.attachments??[]})},clearDraft:()=>{w(d)},buildPageContextAttachment:()=>H()})),V.useEffect(()=>{const re=l.current;re&&(re.style.height="auto",re.style.height=`${Math.min(re.scrollHeight,200)}px`)},[S]);const z=async re=>{if(!re||re.length===0)return;const _e=Array.from(re),Ge=R_e(),We=C_e(_e,x,Ge);if(We){L(Ce=>{const Re=new Map(Ce);return _e.forEach(Se=>{Re.set(Se.name,We.message)}),Re});return}L(Ce=>{const Re=new Map(Ce);return _e.forEach(Se=>Re.delete(Se.name)),Re});try{const Ce=s.config.transport;if(Ce.mode!=="proxy")throw new Error("File uploads are only supported with proxy transport");const Re={presignedUrlEndpoint:`${Ce.baseUrl}/files/upload/presigned`,getAuthHeaders:()=>{const Be={};return Ce.headers?Ce.headers:(Ce.apiKey&&(Be.Authorization=`Bearer ${Ce.apiKey}`),Be)}},Se=await B_e(_e,Re,{chatId:t,userId:s.config.user?.id,onProgress:Be=>{P(de=>{const et=new Map(de);return et.set(Be.fileId,Be),et})}});k(d,Se),setTimeout(()=>{P(Be=>{const de=new Map(Be);return Se.forEach(et=>de.delete(et.id)),de})},2e3)}catch(Ce){const Re=Ce instanceof Error?Ce.message:"Failed to upload files";L(Se=>{const Be=new Map(Se);return _e.forEach(de=>{Be.set(de.name,Re)}),Be})}},j=()=>{u.current?.click()},A=re=>{const _e=L_e(re);if(!_e)return!1;if(x.some(Ce=>Ce.type===exports.AgentAttachmentType.Link&&Ce.url===_e))return!0;const Ge=D_e(_e),We={id:_t.nanoid(),url:_e,name:Ge,type:exports.AgentAttachmentType.Link};return k(d,[We]),!0},Y=async re=>{await z(re.target.files),re.target.value=""},ee=re=>{const _e=x.find(Ge=>Ge.id===re);_e&&R(_e)&&E(d,!0),_(d,re)},O=()=>{if(typeof window>"u"||typeof document>"u")return!1;const re=f3(),_e=re?.selectedText??window.getSelection?.()?.toString()?.trim()??"";if(!_e)return!1;const Ge=window.location?.href,We=_e.slice(0,20),Ce=_e.length>20?We+"...":_e,Re=po({kind:"webSnippet",url:Ge,title:Ce,selectedText:_e,source:{app:"browser",url:Ge},...re?.target?{target:re.target}:{}});return k(d,[Re]),!0},se=re=>{re.preventDefault();const _e=S.trim();_e&&(v(d,void 0),a(_e))},ge=re=>{re.key==="Enter"&&!re.shiftKey&&(re.preventDefault(),se(re))},ke=re=>{m&&v(d,void 0),g(d,re.target.value)},Te=re=>{if(re.nativeEvent.shiftKey)return;const _e=re.clipboardData?.getData("text/plain")??"";if(!_e)return;A(_e)&&re.preventDefault()},Ke=!!S.trim();return N.jsxs(N.Fragment,{children:[N.jsxs("form",{onSubmit:se,className:"mp-agent-composer-input-wrapper",id:"composer-form",children:[N.jsx("input",{ref:u,type:"file",multiple:!0,style:{display:"none"},onChange:Y}),N.jsx(O_e,{attachments:x,onRemove:ee,uploadProgress:D,uploadErrors:C}),N.jsx("textarea",{rows:2,name:"message",ref:l,value:S,autoFocus:e,className:"mp-agent-composer-textarea",placeholder:t?o.followUp:o.newChat,onChange:ke,onKeyDown:ge,onPaste:Te})]}),N.jsxs("div",{className:"mp-agent-composer-actions",children:[N.jsxs("div",{className:"mp-agent-composer-actions-left",children:[s.config.features?.modelSwitching&&N.jsx(H_e,{}),s.config.features?.toolConfiguration&&N.jsx(K_e,{}),N.jsx(bn,{content:o.attachFiles,children:N.jsx("button",{type:"button",className:"mp-agent-composer-button mp-agent-composer-tool-button",onClick:j,"aria-label":o.attachFiles,children:N.jsx(Qi,{size:16})})}),N.jsx(bn,{content:o.attachSelectionToContext,children:N.jsx("button",{type:"button",className:"mp-agent-composer-button mp-agent-composer-tool-button",onClick:()=>{O()},"aria-label":o.attachSelectionToContext,children:N.jsx(Fd,{size:16})})}),K&&!B&&N.jsx(bn,{content:"Attach page context",children:N.jsx("button",{type:"button",className:"mp-agent-composer-button mp-agent-composer-tool-button",onClick:()=>{E(d,!1);const re=H();re&&k(d,[re])},"aria-label":"Attach page context",children:N.jsx($d,{size:16})})})]}),N.jsx("div",{className:"mp-agent-composer-actions-right",children:n===vt.Streaming&&!Ke?N.jsx(bn,{content:o.stopStreaming,children:N.jsx("button",{type:"button",onClick:r,"aria-label":o.stopStreaming,className:"mp-agent-composer-button mp-agent-composer-send-button",children:N.jsx(k5,{size:12})})}):N.jsx(bn,{content:Ke?o.sendMessage:o.typeMessageToSend,children:N.jsx("button",{type:"submit",form:"composer-form",disabled:!Ke,"aria-label":o.sendMessage,className:"mp-agent-composer-button mp-agent-composer-send-button",children:N.jsx(Dd,{size:16})})})})]})]})}),B3=({autoFocus:e,multiUser:t=!1,participantIds:n})=>{const r=V.useRef({setValue:()=>{},getDraft:()=>({value:"",attachments:[]}),setDraft:()=>{},clearDraft:()=>{}}),{pendingKey:a,queuedMessages:i,activeChatStatus:o,activeChatId:s,handleSubmit:l,handleStop:u,handleQueuedClick:d,removeQueuedMessage:p}=M_e({composerFormRef:r,multiUser:t,participantIds:n});return N.jsx("div",{className:"mp-agent-composer-wrapper",children:N.jsxs("div",{className:"mp-agent-composer",children:[N.jsx(A_e,{queuedMessages:i,onSendQueued:d,onRemoveQueued:m=>p(a,m)}),N.jsx(Y_e,{status:o,ref:r,autoFocus:e,activeChatId:s,onStop:u,onSubmit:l})]})})};function xr(e,t,n){let r=n.initialDeps??[],a,i=!0;function o(){var s,l,u;let d;n.key&&((s=n.debug)!=null&&s.call(n))&&(d=Date.now());const p=e();if(!(p.length!==r.length||p.some((g,f)=>r[f]!==g)))return a;r=p;let h;if(n.key&&((l=n.debug)!=null&&l.call(n))&&(h=Date.now()),a=t(...p),n.key&&((u=n.debug)!=null&&u.call(n))){const g=Math.round((Date.now()-d)*100)/100,f=Math.round((Date.now()-h)*100)/100,w=f/16,v=(k,_)=>{for(k=String(k);k.length<_;)k=" "+k;return k};console.info(`%c⏱ ${v(f,5)} /${v(g,5)} ms`,`
8294
8294
  font-size: .6rem;
8295
8295
  font-weight: bold;
8296
8296
  color: hsl(${Math.max(0,Math.min(120-120*w,120))}deg 100% 31%);`,n?.key)}return n?.onChange&&!(i&&n.skipInitialOnChange)&&n.onChange(a),i=!1,a}return o.updateDeps=s=>{r=s},o}function b2(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const Z_e=(e,t)=>Math.abs(e-t)<1.01,X_e=(e,t,n)=>{let r;return function(...a){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,a),n)}},k2=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},Q_e=e=>e,J_e=e=>{const t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1),r=[];for(let a=t;a<=n;a++)r.push(a);return r},ewe=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const a=o=>{const{width:s,height:l}=o;t({width:Math.round(s),height:Math.round(l)})};if(a(k2(n)),!r.ResizeObserver)return()=>{};const i=new r.ResizeObserver(o=>{const s=()=>{const l=o[0];if(l?.borderBoxSize){const u=l.borderBoxSize[0];if(u){a({width:u.inlineSize,height:u.blockSize});return}}a(k2(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(s):s()});return i.observe(n,{box:"border-box"}),()=>{i.unobserve(n)}},v2={passive:!0},_2=typeof window>"u"?!0:"onscrollend"in window,twe=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;let a=0;const i=e.options.useScrollendEvent&&_2?()=>{}:X_e(r,()=>{t(a,!1)},e.options.isScrollingResetDelay),o=d=>()=>{const{horizontal:p,isRtl:m}=e.options;a=p?n.scrollLeft*(m&&-1||1):n.scrollTop,i(),t(a,d)},s=o(!0),l=o(!1);n.addEventListener("scroll",s,v2);const u=e.options.useScrollendEvent&&_2;return u&&n.addEventListener("scrollend",l,v2),()=>{n.removeEventListener("scroll",s),u&&n.removeEventListener("scrollend",l)}},nwe=(e,t,n)=>{if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},rwe=(e,{adjustments:t=0,behavior:n},r)=>{var a,i;const o=e+t;(i=(a=r.scrollElement)==null?void 0:a.scrollTo)==null||i.call(a,{[r.options.horizontal?"left":"top"]:o,behavior:n})};class awe{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var n,r,a;return((a=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:a.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(a=>{a.forEach(i=>{const o=()=>{const s=i.target,l=this.indexFromElement(s);if(!s.isConnected){this.observer.unobserve(s);return}this.shouldMeasureDuringScroll(l)&&this.resizeItem(l,this.options.measureElement(s,i,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()})}));return{disconnect:()=>{var a;(a=r())==null||a.disconnect(),n=null},observe:a=>{var i;return(i=r())==null?void 0:i.observe(a,{box:"border-box"})},unobserve:a=>{var i;return(i=r())==null?void 0:i.unobserve(a)}}})(),this.range=null,this.setOptions=n=>{Object.entries(n).forEach(([r,a])=>{typeof a>"u"&&delete n[r]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:Q_e,rangeExtractor:J_e,onChange:()=>{},measureElement:nwe,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,...n}},this.notify=n=>{var r,a;(a=(r=this.options).onChange)==null||a.call(r,this,n)},this.maybeNotify=xr(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:process.env.NODE_ENV!=="production"&&"maybeNotify",debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(a=>{this.observer.observe(a)}),this.unsubs.push(this.options.observeElementRect(this,a=>{this.scrollRect=a,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(a,i)=>{this.scrollAdjustments=0,this.scrollDirection=i?this.getScrollOffset()<a?"forward":"backward":null,this.scrollOffset=a,this.isScrolling=i,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(n,r)=>{const a=new Map,i=new Map;for(let o=r-1;o>=0;o--){const s=n[o];if(a.has(s.lane))continue;const l=i.get(s.lane);if(l==null||s.end>l.end?i.set(s.lane,s):s.end<l.end&&a.set(s.lane,!0),a.size===this.options.lanes)break}return i.size===this.options.lanes?Array.from(i.values()).sort((o,s)=>o.end===s.end?o.index-s.index:o.end-s.end)[0]:void 0},this.getMeasurementOptions=xr(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes],(n,r,a,i,o,s)=>(this.prevLanes!==void 0&&this.prevLanes!==s&&(this.lanesChangedFlag=!0),this.prevLanes=s,this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:r,scrollMargin:a,getItemKey:i,enabled:o,lanes:s}),{key:!1}),this.getMeasurements=xr(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:r,scrollMargin:a,getItemKey:i,enabled:o,lanes:s},l)=>{if(!o)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const m of this.laneAssignments.keys())m>=n&&this.laneAssignments.delete(m);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(m=>{this.itemSizeCache.set(m.key,m.size)}));const u=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1);const d=this.measurementsCache.slice(0,u),p=new Array(s).fill(void 0);for(let m=0;m<u;m++){const h=d[m];h&&(p[h.lane]=m)}for(let m=u;m<n;m++){const h=i(m),g=this.laneAssignments.get(m);let f,w;if(g!==void 0&&this.options.lanes>1){f=g;const E=p[f],S=E!==void 0?d[E]:void 0;w=S?S.end+this.options.gap:r+a}else{const E=this.options.lanes===1?d[m-1]:this.getFurthestMeasurement(d,m);w=E?E.end+this.options.gap:r+a,f=E?E.lane:m%this.options.lanes,this.options.lanes>1&&this.laneAssignments.set(m,f)}const v=l.get(h),k=typeof v=="number"?v:this.options.estimateSize(m),_=w+k;d[m]={index:m,start:w,size:k,end:_,key:h,lane:f},p[f]=m}return this.measurementsCache=d,d},{key:process.env.NODE_ENV!=="production"&&"getMeasurements",debug:()=>this.options.debug}),this.calculateRange=xr(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,a,i)=>this.range=n.length>0&&r>0?iwe({measurements:n,outerSize:r,scrollOffset:a,lanes:i}):null,{key:process.env.NODE_ENV!=="production"&&"calculateRange",debug:()=>this.options.debug}),this.getVirtualIndexes=xr(()=>{let n=null,r=null;const a=this.calculateRange();return a&&(n=a.startIndex,r=a.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,a,i,o)=>i===null||o===null?[]:n({startIndex:i,endIndex:o,overscan:r,count:a}),{key:process.env.NODE_ENV!=="production"&&"getVirtualIndexes",debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,a=n.getAttribute(r);return a?parseInt(a,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const a=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(a!==void 0&&this.range){const i=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),o=Math.max(0,a-i),s=Math.min(this.options.count-1,a+i);return n>=o&&n<=s}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((o,s)=>{o.isConnected||(this.observer.unobserve(o),this.elementsCache.delete(s))});return}const r=this.indexFromElement(n),a=this.options.getItemKey(r),i=this.elementsCache.get(a);i!==n&&(i&&this.observer.unobserve(i),this.observer.observe(n),this.elementsCache.set(a,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var a;const i=this.measurementsCache[n];if(!i)return;const o=this.itemSizeCache.get(i.key)??i.size,s=r-o;s!==0&&(((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(i,s,this):i.start<this.getScrollOffset()+this.scrollAdjustments)&&(process.env.NODE_ENV!=="production"&&this.options.debug&&console.info("correction",s),this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=s,behavior:void 0})),this.pendingMeasuredCacheIndexes.push(i.index),this.itemSizeCache=new Map(this.itemSizeCache.set(i.key,r)),this.notify(!1))},this.getVirtualItems=xr(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const a=[];for(let i=0,o=n.length;i<o;i++){const s=n[i],l=r[s];a.push(l)}return a},{key:process.env.NODE_ENV!=="production"&&"getVirtualItems",debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length!==0)return b2(r[U3(0,r.length-1,a=>b2(r[a]).start,n)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(n,r,a=0)=>{if(!this.scrollElement)return 0;const i=this.getSize(),o=this.getScrollOffset();r==="auto"&&(r=n>=o+i?"end":"start"),r==="center"?n+=(a-i)/2:r==="end"&&(n-=i);const s=this.getMaxScrollOffset();return Math.max(Math.min(s,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const a=this.getSize(),i=this.getScrollOffset(),o=this.measurementsCache[n];if(!o)return;if(r==="auto")if(o.end>=i+a-this.options.scrollPaddingEnd)r="end";else if(o.start<=i+this.options.scrollPaddingStart)r="start";else return[i,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const s=r==="end"?o.end+this.options.scrollPaddingEnd:o.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(s,r,o.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:a="auto"}={})=>{const i=this.getOffsetForAlignment(n,r),o=this.now();this.scrollState={index:null,align:r,behavior:a,startedAt:o,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:a="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getOffsetForIndex(n,r);if(!i)return;const[o,s]=i,l=this.now();this.scrollState={index:n,align:s,behavior:a,startedAt:l,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const a=this.getScrollOffset()+n,i=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:i,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let a;if(r.length===0)a=this.options.paddingStart;else if(this.options.lanes===1)a=((n=r[r.length-1])==null?void 0:n.end)??0;else{const i=Array(this.options.lanes).fill(null);let o=r.length-1;for(;o>=0&&i.some(s=>s===null);){const s=r[o];i[s.lane]===null&&(i[s.lane]=s.end),o--}a=Math.max(...i.filter(s=>s!==null))}return Math.max(a-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(n,{adjustments:r,behavior:a})=>{this.options.scrollToFn(n,{behavior:a,adjustments:r},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(t)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,a=r?r[0]:this.scrollState.lastTargetOffset,i=1,o=a!==this.scrollState.lastTargetOffset;if(!o&&Z_e(a,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=i){this.scrollState=null;return}}else this.scrollState.stableFrames=0,o&&(this.scrollState.lastTargetOffset=a,this.scrollState.behavior="auto",this._scrollToOffset(a,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const U3=(e,t,n,r)=>{for(;e<=t;){const a=(e+t)/2|0,i=n(a);if(i<r)e=a+1;else if(i>r)t=a-1;else return a}return e>0?e-1:0};function iwe({measurements:e,outerSize:t,scrollOffset:n,lanes:r}){const a=e.length-1,i=l=>e[l].start;if(e.length<=r)return{startIndex:0,endIndex:a};let o=U3(0,a,i,n),s=o;if(r===1)for(;s<a&&e[s].end<n+t;)s++;else if(r>1){const l=Array(r).fill(0);for(;s<a&&l.some(d=>d<n+t);){const d=e[s];l[d.lane]=d.end,s++}const u=Array(r).fill(n+t);for(;o>=0&&u.some(d=>d>=n);){const d=e[o];u[d.lane]=d.start,o--}o=Math.max(0,o-o%r),s=Math.min(a,s+(r-1-s%r))}return{startIndex:o,endIndex:s}}const w2=typeof document<"u"?te.useLayoutEffect:te.useEffect;function owe({useFlushSync:e=!0,...t}){const n=te.useReducer(()=>({}),{})[1],r={...t,onChange:(i,o)=>{var s;e&&o?a5.flushSync(n):n(),(s=t.onChange)==null||s.call(t,i,o)}},[a]=te.useState(()=>new awe(r));return a.setOptions(r),w2(()=>a._didMount(),[]),w2(()=>a._willUpdate()),a}function swe(e){return owe({observeElementRect:ewe,observeElementOffset:twe,scrollToFn:rwe,...e})}const H3=V.memo(()=>{const e=be(n=>n.activeChatId??n.draftChatKey),t=be(n=>$e(n,e).composerError);return t?N.jsx("div",{className:"mp-agent-composer-error",children:t}):null});H3.displayName="ComposerError";const lwe=(e,t)=>{switch(e.status){case exports.AgentToolCallStatus.Running:return`Running ${t}...`;case exports.AgentToolCallStatus.Succeeded:return`Completed ${t}`;case exports.AgentToolCallStatus.Failed:return`Failed to run ${t}`;case exports.AgentToolCallStatus.Pending:return`Preparing ${t}...`;default:return`Running ${t}...`}},es=e=>{if(e===void 0)return"undefined";try{return JSON.stringify(e,null,2)??"undefined"}catch{try{return String(e)}catch{return"[unserializable]"}}},x2=({call:e})=>He().config.debug?N.jsxs("details",{className:"mp-agent-tool-debug-details",children:[N.jsx("summary",{className:"mp-agent-tool-debug-summary",children:"Details"}),N.jsxs("div",{className:"mp-agent-tool-debug-body",children:[N.jsxs("div",{className:"mp-agent-tool-debug-row",children:[N.jsx("div",{className:"mp-agent-tool-debug-label",children:"Tool"}),N.jsx("div",{className:"mp-agent-tool-debug-value",children:e.name})]}),N.jsxs("div",{className:"mp-agent-tool-debug-row",children:[N.jsx("div",{className:"mp-agent-tool-debug-label",children:"Status"}),N.jsx("div",{className:"mp-agent-tool-debug-value",children:e.status})]}),N.jsxs("details",{className:"mp-agent-tool-debug-section",children:[N.jsx("summary",{className:"mp-agent-tool-debug-section-summary",children:"Input"}),N.jsx("pre",{className:"mp-agent-tool-debug-code",children:N.jsx("code",{children:es(e.input)})})]}),N.jsxs("details",{className:"mp-agent-tool-debug-section",children:[N.jsx("summary",{className:"mp-agent-tool-debug-section-summary",children:"Output"}),N.jsx("pre",{className:"mp-agent-tool-debug-code",children:N.jsx("code",{children:es(e.output)})})]}),e.error&&N.jsxs("details",{className:"mp-agent-tool-debug-section",children:[N.jsx("summary",{className:"mp-agent-tool-debug-section-summary",children:"Error"}),N.jsx("pre",{className:"mp-agent-tool-debug-code",children:N.jsx("code",{children:es(e.error)})})]})]})]}):null,E2=({call:e,isExpandable:t=!1,isExpanded:n=!1,onToggleExpand:r})=>{const a=He(),i=V.useRef(!1),o=e.status===exports.AgentToolCallStatus.Succeeded||e.status===exports.AgentToolCallStatus.Failed,s=t||a.config.debug&&!o,l=s||t;if(V.useEffect(()=>{!t||o||n||i.current||(i.current=!0,r?.())},[t,o,n,r]),!l)return null;const d=a.tools.get(e.name)?.label??e.name,p=lwe(e,d);return N.jsxs("div",{className:"mp-agent-tool-header",children:[s&&N.jsx("div",{className:"mp-agent-tool-simple-message",children:p}),t&&N.jsx("button",{className:"mp-agent-subagent-preview-toggle",type:"button",onClick:r,"aria-expanded":n,children:n?N.jsx(h5,{size:14}):N.jsx(zd,{size:14})})]})},j3=({call:e})=>e.approved===void 0?null:N.jsx("div",{className:"mp-agent-tool-approval-status-inline",children:e.approved?N.jsx("span",{className:"mp-agent-tool-approved",children:"✓ Approved"}):N.jsx("span",{className:"mp-agent-tool-denied",children:"✗ Denied"})}),cwe=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e.question,n=e.selectionMode,r=e.options,a=e.allowFreeText;if(typeof t!="string"||t.trim().length<1||n!=="single"&&n!=="multiple"||!Array.isArray(r)||r.length<2||r.length>6)return null;const i=r.map(o=>{if(!o||typeof o!="object"||Array.isArray(o))return null;const s=o.id,l=o.label,u=o.description;return typeof s!="string"||s.trim().length<1||typeof l!="string"||l.trim().length<1||u!==void 0&&typeof u!="string"?null:{id:s,label:l,...typeof u=="string"?{description:u}:{}}}).filter(o=>o!==null);return i.length!==r.length?null:{question:t,selectionMode:n,options:i,allowFreeText:typeof a=="boolean"?a:!1}},uwe=({callId:e,input:t,isSubmitting:n,onSubmit:r})=>{const[a,i]=V.useState([]),[o,s]=V.useState(""),[l,u]=V.useState(void 0),d=V.useMemo(()=>cwe(t),[t]);V.useEffect(()=>{i([]),s(""),u(void 0)},[e,t]);const p=h=>{if(d){if(u(void 0),d.selectionMode==="single"){i([h]);return}i(g=>g.includes(h)?g.filter(f=>f!==h):[...g,h])}},m=async()=>{if(!d)return;const h=o.trim(),g=a.length>0,f=d.allowFreeText&&h.length>0;if(!g&&!f){u(d.allowFreeText?"Select at least one option or provide a custom response.":"Select at least one option before submitting.");return}const w=d.options.filter(k=>a.includes(k.id)).map(({id:k,label:_,description:E})=>({id:k,label:_,...E?{description:E}:{}})),v={question:d.question,selectionMode:d.selectionMode,selectedOptionIds:a,selectedOptions:w,...h?{freeText:h}:{}};await r(JSON.stringify(v))};return d?N.jsxs("div",{className:"mp-agent-tool-user-action-form",children:[N.jsx("div",{className:"mp-agent-tool-user-action-question",children:d.question}),N.jsx("div",{className:"mp-agent-tool-user-action-options",children:d.options.map(h=>{const g=`${e}-${h.id}`,f=a.includes(h.id);return N.jsxs("label",{htmlFor:g,className:"mp-agent-tool-user-action-option",children:[N.jsx("input",{id:g,type:d.selectionMode==="single"?"radio":"checkbox",name:`mp-agent-tool-user-action-${e}`,checked:f,onChange:()=>p(h.id),disabled:n}),N.jsxs("span",{className:"mp-agent-tool-user-action-option-content",children:[N.jsx("span",{className:"mp-agent-tool-user-action-option-label",children:h.label}),h.description?N.jsx("span",{className:"mp-agent-tool-user-action-option-description",children:h.description}):null]})]},h.id)})}),d.allowFreeText?N.jsx("textarea",{className:"mp-agent-tool-user-action-free-text",value:o,onChange:h=>{s(h.target.value),l&&u(void 0)},placeholder:"Optional custom response",rows:3,disabled:n}):null,l?N.jsx("div",{className:"mp-agent-tool-input-error",children:l}):null,N.jsx("div",{className:"mp-agent-tool-approval-actions",children:N.jsx("button",{className:"mp-agent-tool-approve-button",onClick:m,disabled:n,children:n?"Submitting...":"Submit response"})})]}):N.jsx("div",{className:"mp-agent-tool-user-action-form",children:N.jsx("div",{className:"mp-agent-tool-input-error",children:"Invalid user action input schema in tool call."})})},dwe=({call:e,messageId:t,chatId:n,onApprovalSent:r})=>{const a=He(),i=a.tools.get(e.name)?.label??e.name,o=be(D=>D.appendMessagesToChat),[s,l]=V.useState(!1),[u,d]=V.useState(!1),[p,m]=V.useState(!1),[h,g]=V.useState(JSON.stringify(e.input??{},null,2)),[f,w]=V.useState(void 0),v=a.config.user?.id??"guest",k=e.requiresUserAction;V.useEffect(()=>{u||(g(JSON.stringify(e.input??{},null,2)),w(void 0))},[e.id,e.input,u]);const _=()=>{g(JSON.stringify(e.input??{},null,2)),w(void 0),d(!0)},E=()=>{g(JSON.stringify(e.input??{},null,2)),w(void 0),d(!1)},S=async()=>{if(!(!a.transport.updateToolCall||p||s)){w(void 0),m(!0);try{const D=JSON.parse(h);if(!D||typeof D!="object"||Array.isArray(D))throw new Error("Tool input must be a JSON object.");const P=await a.transport.updateToolCall({chatId:n,messageId:t,toolCallId:e.id,input:D});o(n,[P]),d(!1)}catch(D){w(D instanceof Error?D.message:"Failed to update tool input.")}finally{m(!1)}}},x=async(D,P)=>{if(!(!e.approvalId||s||p||u)){l(!0);try{const C={chatId:n,messageId:t,approvalId:e.approvalId,approved:D,...P?{userResponse:P}:{},userId:v},L=await a.transport.streamMessage(C,G=>{G.type===exports.StreamChunkType.Message&&G.message&&o(n,[G.message])},{streamKey:n});L?o(L.id,L.messages):r()}catch(C){console.error("Failed to send approval:",C)}finally{l(!1)}}};return e.approved!==void 0?N.jsx(j3,{call:e}):k?N.jsx(uwe,{callId:e.id,input:e.input,isSubmitting:s,onSubmit:D=>x(!0,D)}):N.jsxs("div",{className:"mp-agent-tool-approval-buttons",children:[N.jsxs("div",{className:"mp-agent-tool-approval-request-message",children:["Agent wants to execute tool ",i,"."]}),N.jsxs("div",{className:"mp-agent-tool-input-card",children:[N.jsxs("div",{className:"mp-agent-tool-input-card-header",children:[N.jsx("span",{className:"mp-agent-tool-input-card-title",children:"Tool input"}),u?N.jsxs("div",{className:"mp-agent-tool-input-actions",children:[N.jsx(nn,{icon:"Check",size:"sm",tooltip:"Save tool input",onClick:S,disabled:p||s,"aria-label":"Save tool input"}),N.jsx(nn,{icon:"X",size:"sm",tooltip:"Cancel input edit",onClick:E,disabled:p||s,"aria-label":"Cancel tool input edit"})]}):N.jsx(nn,{icon:"Pencil",size:"sm",tooltip:"Edit tool input",onClick:_,disabled:s||p,"aria-label":"Edit tool input"})]}),u?N.jsx("textarea",{className:"mp-agent-tool-input-editor",value:h,onChange:D=>{g(D.target.value),f&&w(void 0)},rows:8,spellCheck:!1,disabled:p||s}):N.jsx("pre",{className:"mp-agent-tool-input-preview",children:JSON.stringify(e.input??{},null,2)}),f&&N.jsx("div",{className:"mp-agent-tool-input-error",children:f})]}),N.jsxs("div",{className:"mp-agent-tool-approval-actions",children:[N.jsx("button",{className:"mp-agent-tool-approve-button",onClick:()=>x(!0),disabled:s||u||p,children:s?"Processing...":"Approve"}),N.jsx("button",{className:"mp-agent-tool-deny-button",onClick:()=>x(!1),disabled:s||p,children:s?"Processing...":"Deny"})]})]})},M2=({call:e,messageId:t,chatId:n})=>{const r=He(),a=be(d=>d.upsertChat),i=r.config.debug&&!!e.approvalId,o=e.requiresConfirmation&&e.approvalId||i,s=o&&e.approved===void 0,l=o&&e.approved!==void 0,u=async()=>{try{const d=await r.transport.getChat(n);a(d)}catch(d){console.error("Failed to refresh chat after approval:",d)}};return!s&&!l?null:N.jsxs("div",{className:"mp-agent-tool-approval",children:[s&&N.jsx(dwe,{call:e,messageId:t,chatId:n,onApprovalSent:u}),l&&N.jsx(j3,{call:e})]})},S2=({chatId:e,isExpanded:t})=>{const n=He(),r=be(l=>$e(l,e).messages),a=be(l=>$e(l,e).pendingAssistant),i=be(l=>l.chats[e]?.contextKey??l.contextKey),o=np(e),s=V.useMemo(()=>{const l=[...r].sort((d,p)=>d.createdAt.localeCompare(p.createdAt));if(n.config.debug)return l;const u=l.findIndex(d=>d.role===exports.MessageRole.User);return u===-1?l:l.filter((d,p)=>p!==u)},[r,n.config.debug]);return N.jsx("div",{className:"mp-agent-subagent-preview",children:t&&N.jsx("div",{className:"mp-agent-subagent-preview-body",children:s.length===0&&!a?N.jsx("div",{className:"mp-agent-subagent-preview-empty",children:o.isLoading?"Loading subagent chat...":"Subagent chat started."}):N.jsxs(N.Fragment,{children:[s.map(l=>N.jsx(Zi,{message:l,contextKey:i},l.id)),a&&N.jsx(Zi,{message:a,contextKey:i,isStreaming:!0})]})})})},pwe=({call:e,contextKey:t,messageId:n,chatId:r})=>{const a=He(),i=e.subagentChatId||(typeof e.input?.subagentChatId=="string"?e.input.subagentChatId:void 0),[o,s]=V.useState(!1),l=V.useMemo(()=>a.getToolRenderer(e),[a,e]);return l?N.jsxs("div",{className:"mp-agent-tool-panel",children:[i&&N.jsx(E2,{call:e,isExpandable:!0,isExpanded:o,onToggleExpand:()=>s(u=>!u)}),N.jsx(l,{call:e,contextKey:t,chatId:r}),N.jsx(M2,{call:e,messageId:n,chatId:r}),i&&N.jsx(S2,{chatId:i,isExpanded:o}),!i&&N.jsx(x2,{call:e})]}):N.jsxs("div",{className:"mp-agent-tool-panel",children:[N.jsx(E2,{call:e,isExpandable:!!i,isExpanded:o,onToggleExpand:()=>s(u=>!u)}),N.jsx(M2,{call:e,messageId:n,chatId:r}),i&&N.jsx(S2,{chatId:i,isExpanded:o}),!i&&N.jsx(x2,{call:e})]})},hwe=e=>{const t=e.sender?.displayName||e.sender?.id||e.agentName;if(!t)return e.role===exports.MessageRole.User?"You":"AI";const n=t.split(/\s+/).filter(Boolean);return n.length>=2?`${n[0][0]}${n[1][0]}`.toUpperCase():t.slice(0,2).toUpperCase()},dp=V.memo(({message:e,isGrouped:t})=>{if(t)return N.jsx("div",{className:"mp-agent-message-avatar-spacer"});const n=e.role===exports.MessageRole.User;return N.jsx("div",{className:`mp-agent-message-avatar ${n?"mp-agent-message-avatar-user":""}`,children:e.sender?.avatarUrl?N.jsx("img",{className:"mp-agent-message-avatar-image",src:e.sender.avatarUrl,alt:""}):N.jsx("div",{className:"mp-agent-message-avatar-icon",children:hwe(e)})})});dp.displayName="MessageAvatar";const mwe=e=>e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"}):"",fwe=e=>e.sender?.displayName?e.sender.displayName:e.sender?.id&&e.sender.id!=="guest"?e.sender.id:e.agentName?e.agentName:e.role===exports.MessageRole.User?"You":"Assistant",pp=V.memo(({message:e,isGrouped:t})=>{if(t)return null;const n=fwe(e);return N.jsxs("div",{className:"mp-agent-message-header",children:[N.jsx("span",{className:"mp-agent-message-role",children:n}),N.jsx("span",{className:"mp-agent-message-time",children:mwe(e.createdAt)})]})});pp.displayName="MessageHeader";function N2(e){const t=[],n=String(e||"");let r=n.indexOf(","),a=0,i=!1;for(;!i;){r===-1&&(r=n.length,i=!0);const o=n.slice(a,r).trim();(o||!i)&&t.push(o),a=r+1,r=n.indexOf(",",a)}return t}function gwe(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const ywe=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,bwe=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,kwe={};function A2(e,t){return(kwe.jsx?bwe:ywe).test(e)}const vwe=/[ \t\n\f\r]/g;function _we(e){return typeof e=="object"?e.type==="text"?T2(e.value):!1:T2(e)}function T2(e){return e.replace(vwe,"")===""}let Ia=class{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}};Ia.prototype.normal={};Ia.prototype.property={};Ia.prototype.space=void 0;function V3(e,t){const n={},r={};for(const a of e)Object.assign(n,a.property),Object.assign(r,a.normal);return new Ia(n,r,t)}function ya(e){return e.toLowerCase()}let Ft=class{constructor(t,n){this.attribute=n,this.property=t}};Ft.prototype.attribute="";Ft.prototype.booleanish=!1;Ft.prototype.boolean=!1;Ft.prototype.commaOrSpaceSeparated=!1;Ft.prototype.commaSeparated=!1;Ft.prototype.defined=!1;Ft.prototype.mustUseProperty=!1;Ft.prototype.number=!1;Ft.prototype.overloadedBoolean=!1;Ft.prototype.property="";Ft.prototype.spaceSeparated=!1;Ft.prototype.space=void 0;let wwe=0;const Ie=yr(),lt=yr(),sd=yr(),le=yr(),Xe=yr(),$r=yr(),Ut=yr();function yr(){return 2**++wwe}const ld=Object.freeze(Object.defineProperty({__proto__:null,boolean:Ie,booleanish:lt,commaOrSpaceSeparated:Ut,commaSeparated:$r,number:le,overloadedBoolean:sd,spaceSeparated:Xe},Symbol.toStringTag,{value:"Module"})),ts=Object.keys(ld);let hp=class extends Ft{constructor(t,n,r,a){let i=-1;if(super(t,n),C2(this,"space",a),typeof r=="number")for(;++i<ts.length;){const o=ts[i];C2(this,ts[i],(r&ld[o])===ld[o])}}};hp.prototype.defined=!0;function C2(e,t,n){n&&(e[t]=n)}function Vr(e){const t={},n={};for(const[r,a]of Object.entries(e.properties)){const i=new hp(r,e.transform(e.attributes||{},r),a,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(i.mustUseProperty=!0),t[r]=i,n[ya(r)]=r,n[ya(i.attribute)]=r}return new Ia(t,n,e.space)}const G3=Vr({properties:{ariaActiveDescendant:null,ariaAtomic:lt,ariaAutoComplete:null,ariaBusy:lt,ariaChecked:lt,ariaColCount:le,ariaColIndex:le,ariaColSpan:le,ariaControls:Xe,ariaCurrent:null,ariaDescribedBy:Xe,ariaDetails:null,ariaDisabled:lt,ariaDropEffect:Xe,ariaErrorMessage:null,ariaExpanded:lt,ariaFlowTo:Xe,ariaGrabbed:lt,ariaHasPopup:null,ariaHidden:lt,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Xe,ariaLevel:le,ariaLive:null,ariaModal:lt,ariaMultiLine:lt,ariaMultiSelectable:lt,ariaOrientation:null,ariaOwns:Xe,ariaPlaceholder:null,ariaPosInSet:le,ariaPressed:lt,ariaReadOnly:lt,ariaRelevant:null,ariaRequired:lt,ariaRoleDescription:Xe,ariaRowCount:le,ariaRowIndex:le,ariaRowSpan:le,ariaSelected:lt,ariaSetSize:le,ariaSort:null,ariaValueMax:le,ariaValueMin:le,ariaValueNow:le,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function W3(e,t){return t in e?e[t]:t}function K3(e,t){return W3(e,t.toLowerCase())}const xwe=Vr({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:$r,acceptCharset:Xe,accessKey:Xe,action:null,allow:null,allowFullScreen:Ie,allowPaymentRequest:Ie,allowUserMedia:Ie,alt:null,as:null,async:Ie,autoCapitalize:null,autoComplete:Xe,autoFocus:Ie,autoPlay:Ie,blocking:Xe,capture:null,charSet:null,checked:Ie,cite:null,className:Xe,cols:le,colSpan:null,content:null,contentEditable:lt,controls:Ie,controlsList:Xe,coords:le|$r,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Ie,defer:Ie,dir:null,dirName:null,disabled:Ie,download:sd,draggable:lt,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Ie,formTarget:null,headers:Xe,height:le,hidden:sd,high:le,href:null,hrefLang:null,htmlFor:Xe,httpEquiv:Xe,id:null,imageSizes:null,imageSrcSet:null,inert:Ie,inputMode:null,integrity:null,is:null,isMap:Ie,itemId:null,itemProp:Xe,itemRef:Xe,itemScope:Ie,itemType:Xe,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Ie,low:le,manifest:null,max:null,maxLength:le,media:null,method:null,min:null,minLength:le,multiple:Ie,muted:Ie,name:null,nonce:null,noModule:Ie,noValidate:Ie,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:Ie,optimum:le,pattern:null,ping:Xe,placeholder:null,playsInline:Ie,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Ie,referrerPolicy:null,rel:Xe,required:Ie,reversed:Ie,rows:le,rowSpan:le,sandbox:Xe,scope:null,scoped:Ie,seamless:Ie,selected:Ie,shadowRootClonable:Ie,shadowRootDelegatesFocus:Ie,shadowRootMode:null,shape:null,size:le,sizes:null,slot:null,span:le,spellCheck:lt,src:null,srcDoc:null,srcLang:null,srcSet:null,start:le,step:null,style:null,tabIndex:le,target:null,title:null,translate:null,type:null,typeMustMatch:Ie,useMap:null,value:lt,width:le,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Xe,axis:null,background:null,bgColor:null,border:le,borderColor:null,bottomMargin:le,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Ie,declare:Ie,event:null,face:null,frame:null,frameBorder:null,hSpace:le,leftMargin:le,link:null,longDesc:null,lowSrc:null,marginHeight:le,marginWidth:le,noResize:Ie,noHref:Ie,noShade:Ie,noWrap:Ie,object:null,profile:null,prompt:null,rev:null,rightMargin:le,rules:null,scheme:null,scrolling:lt,standby:null,summary:null,text:null,topMargin:le,valueType:null,version:null,vAlign:null,vLink:null,vSpace:le,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Ie,disableRemotePlayback:Ie,prefix:null,property:null,results:le,security:null,unselectable:null},space:"html",transform:K3}),Ewe=Vr({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Ut,accentHeight:le,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:le,amplitude:le,arabicForm:null,ascent:le,attributeName:null,attributeType:null,azimuth:le,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:le,by:null,calcMode:null,capHeight:le,className:Xe,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:le,diffuseConstant:le,direction:null,display:null,dur:null,divisor:le,dominantBaseline:null,download:Ie,dx:null,dy:null,edgeMode:null,editable:null,elevation:le,enableBackground:null,end:null,event:null,exponent:le,externalResourcesRequired:null,fill:null,fillOpacity:le,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:$r,g2:$r,glyphName:$r,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:le,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:le,horizOriginX:le,horizOriginY:le,id:null,ideographic:le,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:le,k:le,k1:le,k2:le,k3:le,k4:le,kernelMatrix:Ut,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:le,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:le,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:le,overlineThickness:le,paintOrder:null,panose1:null,path:null,pathLength:le,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Xe,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:le,pointsAtY:le,pointsAtZ:le,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Ut,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Ut,rev:Ut,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Ut,requiredFeatures:Ut,requiredFonts:Ut,requiredFormats:Ut,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:le,specularExponent:le,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:le,strikethroughThickness:le,string:null,stroke:null,strokeDashArray:Ut,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:le,strokeOpacity:le,strokeWidth:null,style:null,surfaceScale:le,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Ut,tabIndex:le,tableValues:null,target:null,targetX:le,targetY:le,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Ut,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:le,underlineThickness:le,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:le,values:null,vAlphabetic:le,vMathematical:le,vectorEffect:null,vHanging:le,vIdeographic:le,version:null,vertAdvY:le,vertOriginX:le,vertOriginY:le,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:le,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:W3}),Y3=Vr({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),Z3=Vr({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:K3}),X3=Vr({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),Mwe={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},Swe=/[A-Z]/g,R2=/-[a-z]/g,Nwe=/^data[-\w.:]+$/i;function Q3(e,t){const n=ya(t);let r=t,a=Ft;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&Nwe.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(R2,Twe);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!R2.test(i)){let o=i.replace(Swe,Awe);o.charAt(0)!=="-"&&(o="-"+o),t="data"+o}}a=hp}return new a(r,t)}function Awe(e){return"-"+e.toLowerCase()}function Twe(e){return e.charAt(1).toUpperCase()}const J3=V3([G3,xwe,Y3,Z3,X3],"html"),fo=V3([G3,Ewe,Y3,Z3,X3],"svg");function I2(e){const t=String(e||"").trim();return t?t.split(/[ \t\n\r\f]+/g):[]}function Cwe(e){return e.join(" ").trim()}var Jn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function go(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var mp={},O2=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,Rwe=/\n/g,Iwe=/^\s*/,Owe=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,Lwe=/^:\s*/,Dwe=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,zwe=/^[;\s]*/,$we=/^\s+|\s+$/g,Fwe=`