@multiplayer-app/ai-agent-react 0.1.0-beta.52 → 0.1.0-beta.53
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.
|
@@ -8319,7 +8319,7 @@ React keys must be passed directly to JSX without using spread:
|
|
|
8319
8319
|
*/var G6e=["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])"],md=G6e.join(","),L5=typeof Element>"u",Ca=L5?function(){}:Element.prototype.matches||Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector,Zi=!L5&&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},Ra=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&&Ra(t.parentNode);return o},W6e=function(t){var n,r=t==null||(n=t.getAttribute)===null||n===void 0?void 0:n.call(t,"contenteditable");return r===""||r==="true"},K6e=function(t,n,r){if(Ra(t))return[];var a=Array.prototype.slice.apply(t.querySelectorAll(md));return n&&Ca.call(t,md)&&a.unshift(t),a=a.filter(r),a},fd=function(t,n,r){for(var a=[],i=Array.from(t);i.length;){var o=i.shift();if(!Ra(o,!1))if(o.tagName==="SLOT"){var s=o.assignedElements(),l=s.length?s:o.children,u=fd(l,!0,r);r.flatten?a.push.apply(a,u):a.push({scopeParent:o,candidates:u})}else{var d=Ca.call(o,md);d&&r.filter(o)&&(n||!t.includes(o))&&a.push(o);var p=o.shadowRoot||typeof r.getShadowRoot=="function"&&r.getShadowRoot(o),m=!Ra(p,!1)&&(!r.shadowRootFilter||r.shadowRootFilter(o));if(p&&m){var h=fd(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},D5=function(t){return!isNaN(parseInt(t.getAttribute("tabindex"),10))},z5=function(t){if(!t)throw new Error("No node provided");return t.tabIndex<0&&(/^(AUDIO|VIDEO|DETAILS)$/.test(t.tagName)||W6e(t))&&!D5(t)?0:t.tabIndex},Y6e=function(t,n){var r=z5(t);return r<0&&n&&!D5(t)?0:r},Z6e=function(t,n){return t.tabIndex===n.tabIndex?t.documentOrder-n.documentOrder:t.tabIndex-n.tabIndex},$5=function(t){return t.tagName==="INPUT"},X6e=function(t){return $5(t)&&t.type==="hidden"},Q6e=function(t){var n=t.tagName==="DETAILS"&&Array.prototype.slice.apply(t.children).some(function(r){return r.tagName==="SUMMARY"});return n},J6e=function(t,n){for(var r=0;r<t.length;r++)if(t[r].checked&&t[r].form===n)return t[r]},e8e=function(t){if(!t.name)return!0;var n=t.form||Zi(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=J6e(a,t.form);return!i||i===t},t8e=function(t){return $5(t)&&t.type==="radio"},n8e=function(t){return t8e(t)&&!e8e(t)},r8e=function(t){var n,r=t&&Zi(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=Zi(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},Jh=function(t){var n=t.getBoundingClientRect(),r=n.width,a=n.height;return r===0&&a===0},a8e=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=Ca.call(t,"details>summary:first-of-type"),s=o?t.parentElement:t;if(Ca.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=Zi(t);if(u&&!u.shadowRoot&&a(u)===!0)return Jh(t);t.assignedSlot?t=t.assignedSlot:!u&&d!==t.ownerDocument?t=d.host:t=u}t=l}if(r8e(t))return!t.getClientRects().length;if(r!=="legacy-full")return!0}else if(r==="non-zero-area")return Jh(t);return!1},i8e=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 Ca.call(n,"fieldset[disabled] *")?!0:!a.contains(t)}return!0}n=n.parentElement}return!1},o8e=function(t,n){return!(n.disabled||Ra(n)||X6e(n)||a8e(n,t)||Q6e(n)||i8e(n))},e2=function(t,n){return!(n8e(n)||z5(n)<0||!o8e(t,n))},s8e=function(t){var n=parseInt(t.getAttribute("tabindex"),10);return!!(isNaN(n)||n>=0)},F5=function(t){var n=[],r=[];return t.forEach(function(a,i){var o=!!a.scopeParent,s=o?a.scopeParent:a,l=Y6e(s,o),u=o?F5(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(Z6e).reduce(function(a,i){return i.isScope?a.push.apply(a,i.content):a.push(i.content),a},[]).concat(n)},P5=function(t,n){n=n||{};var r;return n.getShadowRoot?r=fd([t],n.includeContainer,{filter:e2.bind(null,n),flatten:!1,getShadowRoot:n.getShadowRoot,shadowRootFilter:s8e}):r=K6e(t,n.includeContainer,e2.bind(null,n)),F5(r)};function q5(){const e=navigator.userAgentData;return e!=null&&e.platform?e.platform:navigator.platform}function B5(){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 U5(){return/apple/i.test(navigator.vendor)}function gd(){const e=/android/i;return e.test(q5())||e.test(B5())}function l8e(){return q5().toLowerCase().startsWith("mac")&&!navigator.maxTouchPoints}function H5(){return B5().includes("jsdom/")}const t2="data-floating-ui-focusable",c8e="input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])",ts="ArrowLeft",ns="ArrowRight",u8e="ArrowUp",d8e="ArrowDown";function Ia(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 Cr(e,t){if(!e||!t)return!1;const n=t.getRootNode==null?void 0:t.getRootNode();if(e.contains(t))return!0;if(n&&dd(n)){let r=t;for(;r;){if(e===r)return!0;r=r.parentNode||r.host}}return!1}function jr(e){return"composedPath"in e?e.composedPath()[0]:e.target}function rs(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 p8e(e){return e.matches("html,body")}function wn(e){return e?.ownerDocument||document}function rp(e){return Ot(e)&&e.matches(c8e)}function h8e(e){return e?e.getAttribute("role")==="combobox"&&rp(e):!1}function m8e(e){if(!e||H5())return!0;try{return e.matches(":focus-visible")}catch{return!0}}function j5(e){return e?e.hasAttribute(t2)?e:e.querySelector("["+t2+"]")||e:null}function Ea(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,...Ea(e,a.id,n)])}function f8e(e,t){let n,r=-1;function a(i,o){o>r&&(n=i,r=o),Ea(e,i).forEach(l=>{a(l.id,o+1)})}return a(t,0),e.find(i=>i.id===n)}function ln(e){e.preventDefault(),e.stopPropagation()}function g8e(e){return"nativeEvent"in e}function y8e(e){return e.mozInputSource===0&&e.isTrusted?!0:gd()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function b8e(e){return H5()?!1:!gd()&&e.width===0&&e.height===0||gd()&&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 Oa(e,t){const n=["mouse","pen"];return t||n.push("",void 0),n.includes(e)}var k8e=typeof document<"u",v8e=function(){},Tt=k8e?K.useLayoutEffect:v8e;const _8e={...ne};function Gn(e){const t=ne.useRef(e);return Tt(()=>{t.current=e}),t}const w8e=_8e.useInsertionEffect,x8e=w8e||(e=>e());function tn(e){const t=ne.useRef(()=>{if(process.env.NODE_ENV!=="production")throw new Error("Cannot call an event handler while rendering.")});return x8e(()=>{t.current=e}),ne.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 ii(e,t,n){return Math.floor(e/t)!==n}function Ma(e,t){return t<0||t>=e.current.length}function as(e,t){return Ct(e,{disabledIndices:t})}function n2(e,t){return Ct(e,{decrement:!0,startingIndex:e.current.length,disabledIndices:t})}function Ct(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&&Oi(e,o,a));return o}function E8e(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===u8e){if(p&&ln(n),d===-1)m=u;else if(m=Ct(e,{startingIndex:m,amount:o,decrement:!0,disabledIndices:s}),a&&(d-o<l||m<0)){const h=d%o,f=u%o,y=u-(f-h);f===h?m=u:m=f>h?y:y-o}Ma(e,m)&&(m=d)}if(n.key===d8e&&(p&&ln(n),d===-1?m=l:(m=Ct(e,{startingIndex:d,amount:o,disabledIndices:s}),a&&d+o>u&&(m=Ct(e,{startingIndex:d%o-o,amount:o,disabledIndices:s}))),Ma(e,m)&&(m=d)),r==="both"){const h=Zr(d/o);n.key===(i?ts:ns)&&(p&&ln(n),d%o!==o-1?(m=Ct(e,{startingIndex:d,disabledIndices:s}),a&&ii(m,o,h)&&(m=Ct(e,{startingIndex:d-d%o-1,disabledIndices:s}))):a&&(m=Ct(e,{startingIndex:d-d%o-1,disabledIndices:s})),ii(m,o,h)&&(m=d)),n.key===(i?ns:ts)&&(p&&ln(n),d%o!==0?(m=Ct(e,{startingIndex:d,decrement:!0,disabledIndices:s}),a&&ii(m,o,h)&&(m=Ct(e,{startingIndex:d+(o-d%o),decrement:!0,disabledIndices:s}))):a&&(m=Ct(e,{startingIndex:d+(o-d%o),decrement:!0,disabledIndices:s})),ii(m,o,h)&&(m=d));const f=Zr(u/o)===h;Ma(e,m)&&(a&&f?m=n.key===(i?ns:ts)?u:Ct(e,{startingIndex:d-d%o-1,disabledIndices:s}):m=d)}return m}function M8e(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 S8e(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 N8e(e,t){return t.flatMap((n,r)=>e.includes(n)?[r]:[])}function Oi(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 V5=()=>({getShadowRoot:!0,displayCheck:typeof ResizeObserver=="function"&&ResizeObserver.toString().includes("[native code]")?"full":"none"});function G5(e,t){const n=P5(e,V5()),r=n.length;if(r===0)return;const a=Ia(wn(e)),i=n.indexOf(a),o=i===-1?t===1?0:r-1:i+t;return n[o]}function A8e(e){return G5(wn(e).body,1)||e}function T8e(e){return G5(wn(e).body,-1)||e}function is(e,t){const n=t||e.currentTarget,r=e.relatedTarget;return!r||!Cr(n,r)}function C8e(e){P5(e,V5()).forEach(n=>{n.dataset.tabindex=n.getAttribute("tabindex")||"",n.setAttribute("tabindex","-1")})}function r2(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 a2(e,t,n){let{reference:r,floating:a}=e;const i=lr(t),o=O5(t),s=I5(o),l=Tr(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(vo(t)){case"start":h[o]-=m*(n&&u?-1:1);break;case"end":h[o]+=m*(n&&u?-1:1);break}return h}const R8e=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}=a2(u,r,l),m=r,h={},f=0;for(let y=0;y<s.length;y++){const{name:w,fn:_}=s[y],{x:k,y:v,data:M,reset:S}=await _({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=v??p,h={...h,[w]:{...h[w],...M}},S&&f<=50&&(f++,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}=a2(u,m,l)),y=-1)}return{x:d,y:p,placement:m,strategy:a,middlewareData:h}};async function W5(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}=ko(t,e),f=V6e(h),w=s[m?p==="floating"?"reference":"floating":p],_=Yi(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,v=await(i.getOffsetParent==null?void 0:i.getOffsetParent(s.floating)),M=await(i.isElement==null?void 0:i.isElement(v))?await(i.getScale==null?void 0:i.getScale(v))||{x:1,y:1}:{x:1,y:1},S=Yi(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:k,offsetParent:v,strategy:l}):k);return{top:(_.top-S.top+f.top)/M.y,bottom:(S.bottom-_.bottom+f.bottom)/M.y,left:(_.left-S.left+f.left)/M.x,right:(S.right-_.right+f.right)/M.x}}const I8e=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:f="none",flipAlignment:y=!0,...w}=ko(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const _=Tr(a),k=lr(s),v=Tr(s)===s,M=await(l.isRTL==null?void 0:l.isRTL(u.floating)),S=m||(v||!y?[Ki(s)]:P6e(s)),x=f!=="none";!m&&x&&S.push(...H6e(s,y,f,M));const $=[s,...S],H=await W5(t,w),C=[];let L=((r=i.flip)==null?void 0:r.overflows)||[];if(d&&C.push(H[_]),p){const G=F6e(a,o,M);C.push(H[G[0]],H[G[1]])}if(L=[...L,{placement:a,overflows:C}],!C.every(G=>G<=0)){var W,Z;const G=(((W=i.flip)==null?void 0:W.index)||0)+1,R=$[G];if(R&&(!(p==="alignment"?k!==lr(R):!1)||L.every(D=>lr(D.placement)===k?D.overflows[0]>0:!0)))return{data:{index:G,overflows:L},reset:{placement:R}};let B=(Z=L.filter(P=>P.overflows[0]<=0).sort((P,D)=>P.overflows[1]-D.overflows[1])[0])==null?void 0:Z.placement;if(!B)switch(h){case"bestFit":{var ee;const P=(ee=L.filter(D=>{if(x){const Y=lr(D.placement);return Y===k||Y==="y"}return!0}).map(D=>[D.placement,D.overflows.filter(Y=>Y>0).reduce((Y,A)=>Y+A,0)]).sort((D,Y)=>D[1]-Y[1])[0])==null?void 0:ee[0];P&&(B=P);break}case"initialPlacement":B=s;break}if(a!==B)return{reset:{placement:B}}}return{}}}},O8e=new Set(["left","top"]);async function L8e(e,t){const{placement:n,platform:r,elements:a}=e,i=await(r.isRTL==null?void 0:r.isRTL(a.floating)),o=Tr(n),s=vo(n),l=lr(n)==="y",u=O8e.has(o)?-1:1,d=i&&l?-1:1,p=ko(t,e);let{mainAxis:m,crossAxis:h,alignmentAxis:f}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return s&&typeof f=="number"&&(h=s==="end"?f*-1:f),l?{x:h*d,y:m*u}:{x:m*u,y:h*d}}const D8e=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 L8e(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}}}}},z8e=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:_,y:k}=w;return{x:_,y:k}}},...l}=ko(e,t),u={x:n,y:r},d=await W5(t,l),p=lr(Tr(a)),m=R5(p);let h=u[m],f=u[p];if(i){const w=m==="y"?"top":"left",_=m==="y"?"bottom":"right",k=h+d[w],v=h-d[_];h=Zh(k,h,v)}if(o){const w=p==="y"?"top":"left",_=p==="y"?"bottom":"right",k=f+d[w],v=f-d[_];f=Zh(k,f,v)}const y=s.fn({...t,[m]:h,[p]:f});return{...y,data:{x:y.x-n,y:y.y-r,enabled:{[m]:i,[p]:o}}}}}};function K5(e){const t=mn(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const a=Ot(e),i=a?e.offsetWidth:n,o=a?e.offsetHeight:r,s=Wi(n)!==i||Wi(r)!==o;return s&&(n=i,r=o),{width:n,height:r,$:s}}function ap(e){return lt(e)?e:e.contextElement}function Qr(e){const t=ap(e);if(!Ot(t))return Ln(1);const n=t.getBoundingClientRect(),{width:r,height:a,$:i}=K5(t);let o=(i?Wi(n.width):n.width)/r,s=(i?Wi(n.height):n.height)/a;return(!o||!Number.isFinite(o))&&(o=1),(!s||!Number.isFinite(s))&&(s=1),{x:o,y:s}}const $8e=Ln(0);function Y5(e){const t=Kt(e);return!yo()||!t.visualViewport?$8e:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function F8e(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Kt(e)?!1:t}function Rr(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const a=e.getBoundingClientRect(),i=ap(e);let o=Ln(1);t&&(r?lt(r)&&(o=Qr(r)):o=Qr(e));const s=F8e(i,n,r)?Y5(i):Ln(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=Kt(i),h=r&<(r)?Kt(r):r;let f=m,y=pd(f);for(;y&&r&&h!==f;){const w=Qr(y),_=y.getBoundingClientRect(),k=mn(y),v=_.left+(y.clientLeft+parseFloat(k.paddingLeft))*w.x,M=_.top+(y.clientTop+parseFloat(k.paddingTop))*w.y;l*=w.x,u*=w.y,d*=w.x,p*=w.y,l+=v,u+=M,f=Kt(y),y=pd(f)}}return Yi({width:d,height:p,x:l,y:u})}function _o(e,t){const n=bo(e).scrollLeft;return t?t.left+n:Rr($n(e)).left+n}function Z5(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-_o(e,n),a=n.top+t.scrollTop;return{x:r,y:a}}function P8e(e){let{elements:t,rect:n,offsetParent:r,strategy:a}=e;const i=a==="fixed",o=$n(r),s=t?go(t.floating):!1;if(r===o||s&&i)return n;let l={scrollLeft:0,scrollTop:0},u=Ln(1);const d=Ln(0),p=Ot(r);if((p||!p&&!i)&&((ia(r)!=="body"||ja(o))&&(l=bo(r)),Ot(r))){const h=Rr(r);u=Qr(r),d.x=h.x+r.clientLeft,d.y=h.y+r.clientTop}const m=o&&!p&&!i?Z5(o,l):Ln(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 q8e(e){return Array.from(e.getClientRects())}function B8e(e){const t=$n(e),n=bo(e),r=e.ownerDocument.body,a=Nr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=Nr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let o=-n.scrollLeft+_o(e);const s=-n.scrollTop;return mn(r).direction==="rtl"&&(o+=Nr(t.clientWidth,r.clientWidth)-a),{width:a,height:i,x:o,y:s}}const i2=25;function U8e(e,t){const n=Kt(e),r=$n(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=yo();(!d||d&&t==="fixed")&&(s=a.offsetLeft,l=a.offsetTop)}const u=_o(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,f=Math.abs(r.clientWidth-p.clientWidth-h);f<=i2&&(i-=f)}else u<=i2&&(i+=u);return{width:i,height:o,x:s,y:l}}const H8e=new Set(["absolute","fixed"]);function j8e(e,t){const n=Rr(e,!0,t==="fixed"),r=n.top+e.clientTop,a=n.left+e.clientLeft,i=Ot(e)?Qr(e):Ln(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 o2(e,t,n){let r;if(t==="viewport")r=U8e(e,n);else if(t==="document")r=B8e($n(e));else if(lt(t))r=j8e(t,n);else{const a=Y5(e);r={x:t.x-a.x,y:t.y-a.y,width:t.width,height:t.height}}return Yi(r)}function X5(e,t){const n=Qn(e);return n===t||!lt(n)||Yn(n)?!1:mn(n).position==="fixed"||X5(n,t)}function V8e(e,t){const n=t.get(e);if(n)return n;let r=dr(e,[],!1).filter(s=>lt(s)&&ia(s)!=="body"),a=null;const i=mn(e).position==="fixed";let o=i?Qn(e):e;for(;lt(o)&&!Yn(o);){const s=mn(o),l=np(o);!l&&s.position==="fixed"&&(a=null),(i?!l&&!a:!l&&s.position==="static"&&!!a&&H8e.has(a.position)||ja(o)&&!l&&X5(e,o))?r=r.filter(d=>d!==o):a=s,o=Qn(o)}return t.set(e,r),r}function G8e(e){let{element:t,boundary:n,rootBoundary:r,strategy:a}=e;const o=[...n==="clippingAncestors"?go(t)?[]:V8e(t,this._c):[].concat(n),r],s=o[0],l=o.reduce((u,d)=>{const p=o2(t,d,a);return u.top=Nr(p.top,u.top),u.right=Gi(p.right,u.right),u.bottom=Gi(p.bottom,u.bottom),u.left=Nr(p.left,u.left),u},o2(t,s,a));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function W8e(e){const{width:t,height:n}=K5(e);return{width:t,height:n}}function K8e(e,t,n){const r=Ot(t),a=$n(t),i=n==="fixed",o=Rr(e,!0,i,t);let s={scrollLeft:0,scrollTop:0};const l=Ln(0);function u(){l.x=_o(a)}if(r||!r&&!i)if((ia(t)!=="body"||ja(a))&&(s=bo(t)),r){const h=Rr(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?Z5(a,s):Ln(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 os(e){return mn(e).position==="static"}function s2(e,t){if(!Ot(e)||mn(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return $n(e)===n&&(n=n.ownerDocument.body),n}function Q5(e,t){const n=Kt(e);if(go(e))return n;if(!Ot(e)){let a=Qn(e);for(;a&&!Yn(a);){if(lt(a)&&!os(a))return a;a=Qn(a)}return n}let r=s2(e,t);for(;r&&A6e(r)&&os(r);)r=s2(r,t);return r&&Yn(r)&&os(r)&&!np(r)?n:r||O6e(e)||n}const Y8e=async function(e){const t=this.getOffsetParent||Q5,n=this.getDimensions,r=await n(e.floating);return{reference:K8e(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function Z8e(e){return mn(e).direction==="rtl"}const X8e={convertOffsetParentRelativeRectToViewportRelativeRect:P8e,getDocumentElement:$n,getClippingRect:G8e,getOffsetParent:Q5,getElementRects:Y8e,getClientRects:q8e,getDimensions:W8e,getScale:Qr,isElement:lt,isRTL:Z8e};function J5(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Q8e(e,t){let n=null,r;const a=$n(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 f=Zr(p),y=Zr(a.clientWidth-(d+m)),w=Zr(a.clientHeight-(p+h)),_=Zr(d),v={rootMargin:-f+"px "+-y+"px "+-w+"px "+-_+"px",threshold:Nr(0,Gi(1,l))||1};let M=!0;function S(x){const $=x[0].intersectionRatio;if($!==l){if(!M)return o();$?o(!1,$):r=setTimeout(()=>{o(!1,1e-7)},1e3)}$===1&&!J5(u,e.getBoundingClientRect())&&o(),M=!1}try{n=new IntersectionObserver(S,{...v,root:a.ownerDocument})}catch{n=new IntersectionObserver(S,v)}n.observe(e)}return o(!0),i}function ip(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=ap(e),d=a||i?[...u?dr(u):[],...dr(t)]:[];d.forEach(_=>{a&&_.addEventListener("scroll",n,{passive:!0}),i&&_.addEventListener("resize",n)});const p=u&&s?Q8e(u,n):null;let m=-1,h=null;o&&(h=new ResizeObserver(_=>{let[k]=_;k&&k.target===u&&h&&(h.unobserve(t),cancelAnimationFrame(m),m=requestAnimationFrame(()=>{var v;(v=h)==null||v.observe(t)})),n()}),u&&!l&&h.observe(u),h.observe(t));let f,y=l?Rr(e):null;l&&w();function w(){const _=Rr(e);y&&!J5(y,_)&&n(),y=_,f=requestAnimationFrame(w)}return n(),()=>{var _;d.forEach(k=>{a&&k.removeEventListener("scroll",n),i&&k.removeEventListener("resize",n)}),p?.(),(_=h)==null||_.disconnect(),h=null,l&&cancelAnimationFrame(f)}}const J8e=D8e,e7e=z8e,t7e=I8e,n7e=(e,t,n)=>{const r=new Map,a={platform:X8e,...n},i={...a.platform,_c:r};return R8e(e,t,{...a,platform:i})};var r7e=typeof document<"u",a7e=function(){},Li=r7e?K.useLayoutEffect:a7e;function Xi(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(!Xi(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)&&!Xi(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function e3(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function l2(e,t){const n=e3(e);return Math.round(t*n)/n}function ss(e){const t=ne.useRef(e);return Li(()=>{t.current=e}),t}function i7e(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]=ne.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[m,h]=ne.useState(r);Xi(m,r)||h(r);const[f,y]=ne.useState(null),[w,_]=ne.useState(null),k=ne.useCallback(D=>{D!==x.current&&(x.current=D,y(D))},[]),v=ne.useCallback(D=>{D!==$.current&&($.current=D,_(D))},[]),M=i||f,S=o||w,x=ne.useRef(null),$=ne.useRef(null),H=ne.useRef(d),C=l!=null,L=ss(l),W=ss(a),Z=ss(u),ee=ne.useCallback(()=>{if(!x.current||!$.current)return;const D={placement:t,strategy:n,middleware:m};W.current&&(D.platform=W.current),n7e(x.current,$.current,D).then(Y=>{const A={...Y,isPositioned:Z.current!==!1};G.current&&!Xi(H.current,A)&&(H.current=A,f5.flushSync(()=>{p(A)}))})},[m,t,n,W,Z]);Li(()=>{u===!1&&H.current.isPositioned&&(H.current.isPositioned=!1,p(D=>({...D,isPositioned:!1})))},[u]);const G=ne.useRef(!1);Li(()=>(G.current=!0,()=>{G.current=!1}),[]),Li(()=>{if(M&&(x.current=M),S&&($.current=S),M&&S){if(L.current)return L.current(M,S,ee);ee()}},[M,S,ee,L,C]);const R=ne.useMemo(()=>({reference:x,floating:$,setReference:k,setFloating:v}),[k,v]),B=ne.useMemo(()=>({reference:M,floating:S}),[M,S]),P=ne.useMemo(()=>{const D={position:n,left:0,top:0};if(!B.floating)return D;const Y=l2(B.floating,d.x),A=l2(B.floating,d.y);return s?{...D,transform:"translate("+Y+"px, "+A+"px)",...e3(B.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:Y,top:A}},[n,s,B.floating,d.x,d.y]);return ne.useMemo(()=>({...d,update:ee,refs:R,elements:B,floatingStyles:P}),[d,ee,R,B,P])}const op=(e,t)=>({...J8e(e),options:[e,t]}),sp=(e,t)=>({...e7e(e),options:[e,t]}),lp=(e,t)=>({...t7e(e),options:[e,t]}),o7e="data-floating-ui-focusable",c2="active",u2="selected",Va="ArrowLeft",Ga="ArrowRight",t3="ArrowUp",wo="ArrowDown",s7e={...ne};let d2=!1,l7e=0;const p2=()=>"floating-ui-"+Math.random().toString(36).slice(2,6)+l7e++;function c7e(){const[e,t]=ne.useState(()=>d2?p2():void 0);return Tt(()=>{e==null&&t(p2())},[]),ne.useEffect(()=>{d2=!0},[]),e}const u7e=s7e.useId,cp=u7e||c7e;let La;process.env.NODE_ENV!=="production"&&(La=new Set);function ls(){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=La)!=null&&e.has(a))){var i;(i=La)==null||i.add(a),console.warn(a)}}function d7e(){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=La)!=null&&e.has(a))){var i;(i=La)==null||i.add(a),console.error(a)}}function p7e(){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 h7e=ne.createContext(null),m7e=ne.createContext(null),xo=()=>{var e;return((e=ne.useContext(h7e))==null?void 0:e.id)||null},Eo=()=>ne.useContext(m7e);function Wa(e){return"data-floating-ui-"+e}function sn(e){e.current!==-1&&(clearTimeout(e.current),e.current=-1)}const h2=Wa("safe-polygon");function cs(e,t,n){if(n&&!Oa(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 us(e){return typeof e=="function"?e():e}function f7e(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=Eo(),f=xo(),y=Gn(u),w=Gn(l),_=Gn(n),k=Gn(p),v=ne.useRef(),M=ne.useRef(-1),S=ne.useRef(),x=ne.useRef(-1),$=ne.useRef(!0),H=ne.useRef(!1),C=ne.useRef(()=>{}),L=ne.useRef(!1),W=tn(()=>{var P;const D=(P=a.current.openEvent)==null?void 0:P.type;return D?.includes("mouse")&&D!=="mousedown"});ne.useEffect(()=>{if(!s)return;function P(D){let{open:Y}=D;Y||(sn(M),sn(x),$.current=!0,L.current=!1)}return i.on("openchange",P),()=>{i.off("openchange",P)}},[s,i]),ne.useEffect(()=>{if(!s||!y.current||!n)return;function P(Y){W()&&r(!1,Y,"hover")}const D=wn(o.floating).documentElement;return D.addEventListener("mouseleave",P),()=>{D.removeEventListener("mouseleave",P)}},[o.floating,n,r,s,y,W]);const Z=ne.useCallback(function(P,D,Y){D===void 0&&(D=!0),Y===void 0&&(Y="hover");const A=cs(w.current,"close",v.current);A&&!S.current?(sn(M),M.current=window.setTimeout(()=>r(!1,P,Y),A)):D&&(sn(M),r(!1,P,Y))},[w,r]),ee=tn(()=>{C.current(),S.current=void 0}),G=tn(()=>{if(H.current){const P=wn(o.floating).body;P.style.pointerEvents="",P.removeAttribute(h2),H.current=!1}}),R=tn(()=>a.current.openEvent?["click","mousedown"].includes(a.current.openEvent.type):!1);ne.useEffect(()=>{if(!s)return;function P(te){if(sn(M),$.current=!1,d&&!Oa(v.current)||us(k.current)>0&&!cs(w.current,"open"))return;const O=cs(w.current,"open",v.current);O?M.current=window.setTimeout(()=>{_.current||r(!0,te,"hover")},O):n||r(!0,te,"hover")}function D(te){if(R()){G();return}C.current();const O=wn(o.floating);if(sn(x),L.current=!1,y.current&&a.current.floatingContext){n||sn(M),S.current=y.current({...a.current.floatingContext,tree:h,x:te.clientX,y:te.clientY,onClose(){G(),ee(),R()||Z(te,!0,"safe-polygon")}});const ye=S.current;O.addEventListener("mousemove",ye),C.current=()=>{O.removeEventListener("mousemove",ye)};return}(v.current==="touch"?!Cr(o.floating,te.relatedTarget):!0)&&Z(te)}function Y(te){R()||a.current.floatingContext&&(y.current==null||y.current({...a.current.floatingContext,tree:h,x:te.clientX,y:te.clientY,onClose(){G(),ee(),R()||Z(te)}})(te))}function A(){sn(M)}function J(te){R()||Z(te,!1)}if(lt(o.domReference)){const te=o.domReference,O=o.floating;return n&&te.addEventListener("mouseleave",Y),m&&te.addEventListener("mousemove",P,{once:!0}),te.addEventListener("mouseenter",P),te.addEventListener("mouseleave",D),O&&(O.addEventListener("mouseleave",Y),O.addEventListener("mouseenter",A),O.addEventListener("mouseleave",J)),()=>{n&&te.removeEventListener("mouseleave",Y),m&&te.removeEventListener("mousemove",P),te.removeEventListener("mouseenter",P),te.removeEventListener("mouseleave",D),O&&(O.removeEventListener("mouseleave",Y),O.removeEventListener("mouseenter",A),O.removeEventListener("mouseleave",J))}}},[o,s,e,d,m,Z,ee,G,r,n,_,h,w,y,a,R,k]),Tt(()=>{var P;if(s&&n&&(P=y.current)!=null&&(P=P.__options)!=null&&P.blockPointerEvents&&W()){H.current=!0;const Y=o.floating;if(lt(o.domReference)&&Y){var D;const A=wn(o.floating).body;A.setAttribute(h2,"");const J=o.domReference,te=h==null||(D=h.nodesRef.current.find(O=>O.id===f))==null||(D=D.context)==null?void 0:D.elements.floating;return te&&(te.style.pointerEvents=""),A.style.pointerEvents="none",J.style.pointerEvents="auto",Y.style.pointerEvents="auto",()=>{A.style.pointerEvents="",J.style.pointerEvents="",Y.style.pointerEvents=""}}}},[s,n,f,o,h,y,W]),Tt(()=>{n||(v.current=void 0,L.current=!1,ee(),G())},[n,ee,G]),ne.useEffect(()=>()=>{ee(),sn(M),sn(x),G()},[s,o.domReference,ee,G]);const B=ne.useMemo(()=>{function P(D){v.current=D.pointerType}return{onPointerDown:P,onPointerEnter:P,onMouseMove(D){const{nativeEvent:Y}=D;function A(){!$.current&&!_.current&&r(!0,Y,"hover")}d&&!Oa(v.current)||n||us(k.current)===0||L.current&&D.movementX**2+D.movementY**2<2||(sn(x),v.current==="touch"?A():(L.current=!0,x.current=window.setTimeout(A,us(k.current))))}}},[d,r,n,_,k]);return ne.useMemo(()=>s?{reference:B}:{},[s,B])}let m2=0;function g7e(e,t){t===void 0&&(t={});const{preventScroll:n=!1,cancelPrevious:r=!0,sync:a=!1}=t;r&&cancelAnimationFrame(m2);const i=()=>e?.focus({preventScroll:n});a?i():m2=requestAnimationFrame(i)}const n3={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},f2=ne.forwardRef(function(t,n){const[r,a]=ne.useState();Tt(()=>{U5()&&a("button")},[]);const i={ref:n,tabIndex:0,role:r,"aria-hidden":r?void 0:!0,[Wa("focus-guard")]:"",style:n3};return N.jsx("span",{...t,...i})}),r3=ne.createContext(null),g2=Wa("portal");function y7e(e){e===void 0&&(e={});const{id:t,root:n}=e,r=cp(),a=k7e(),[i,o]=ne.useState(null),s=ne.useRef(null);return Tt(()=>()=>{i?.remove(),queueMicrotask(()=>{s.current=null})},[i]),Tt(()=>{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(g2,""),l.appendChild(u),s.current=u,o(u)},[t,r]),Tt(()=>{if(n===null||!r||s.current)return;let l=n||a?.portalNode;l&&!tp(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(g2,""),l=u||l,l.appendChild(d),s.current=d,o(d)},[t,n,r,a]),i}function b7e(e){const{children:t,id:n,root:r,preserveTabOrder:a=!0}=e,i=y7e({id:n,root:r}),[o,s]=ne.useState(null),l=ne.useRef(null),u=ne.useRef(null),d=ne.useRef(null),p=ne.useRef(null),m=o?.modal,h=o?.open,f=!!o&&!o.modal&&o.open&&a&&!!(r||i);return ne.useEffect(()=>{if(!i||!a||m)return;function y(w){i&&is(w)&&(w.type==="focusin"?r2:C8e)(i)}return i.addEventListener("focusin",y,!0),i.addEventListener("focusout",y,!0),()=>{i.removeEventListener("focusin",y,!0),i.removeEventListener("focusout",y,!0)}},[i,a,m]),ne.useEffect(()=>{i&&(h||r2(i))},[h,i]),N.jsxs(r3.Provider,{value:ne.useMemo(()=>({preserveTabOrder:a,beforeOutsideRef:l,afterOutsideRef:u,beforeInsideRef:d,afterInsideRef:p,portalNode:i,setFocusManagerState:s}),[a,i]),children:[f&&i&&N.jsx(f2,{"data-type":"outside",ref:l,onFocus:y=>{if(is(y,i)){var w;(w=d.current)==null||w.focus()}else{const _=o?o.domReference:null,k=T8e(_);k?.focus()}}}),f&&i&&N.jsx("span",{"aria-owns":i.id,style:n3}),i&&f5.createPortal(t,i),f&&i&&N.jsx(f2,{"data-type":"outside",ref:u,onFocus:y=>{if(is(y,i)){var w;(w=p.current)==null||w.focus()}else{const _=o?o.domReference:null,k=A8e(_);k?.focus(),o?.closeOnFocusOut&&o?.onOpenChange(!1,y.nativeEvent,"focus-out")}}})]})}const k7e=()=>ne.useContext(r3);function y2(e){return Ot(e.target)&&e.target.tagName==="BUTTON"}function v7e(e){return Ot(e.target)&&e.target.tagName==="A"}function b2(e){return rp(e)}function a3(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=ne.useRef(),h=ne.useRef(!1),f=ne.useMemo(()=>({onPointerDown(y){m.current=y.pointerType},onMouseDown(y){const w=m.current;y.button===0&&s!=="click"&&(Oa(w,!0)&&u||(n&&l&&(!(a.current.openEvent&&p)||a.current.openEvent.type==="mousedown")?r(!1,y.nativeEvent,"click"):(y.preventDefault(),r(!0,y.nativeEvent,"click"))))},onClick(y){const w=m.current;if(s==="mousedown"&&m.current){m.current=void 0;return}Oa(w,!0)&&u||(n&&l&&(!(a.current.openEvent&&p)||a.current.openEvent.type==="click")?r(!1,y.nativeEvent,"click"):r(!0,y.nativeEvent,"click"))},onKeyDown(y){m.current=void 0,!(y.defaultPrevented||!d||y2(y))&&(y.key===" "&&!b2(i)&&(y.preventDefault(),h.current=!0),!v7e(y)&&y.key==="Enter"&&r(!(n&&l),y.nativeEvent,"click"))},onKeyUp(y){y.defaultPrevented||!d||y2(y)||b2(i)||y.key===" "&&h.current&&(h.current=!1,r(!(n&&l),y.nativeEvent,"click"))}}),[a,i,s,u,d,r,n,p,l]);return ne.useMemo(()=>o?{reference:f}:{},[o,f])}const _7e={pointerdown:"onPointerDown",mousedown:"onMouseDown",click:"onClick"},w7e={pointerdown:"onPointerDownCapture",mousedown:"onMouseDownCapture",click:"onClickCapture"},k2=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 up(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:f}=t,y=Eo(),w=tn(typeof l=="function"?l:()=>!1),_=typeof l=="function"?w:l,k=ne.useRef(!1),{escapeKey:v,outsidePress:M}=k2(h),{escapeKey:S,outsidePress:x}=k2(f),$=ne.useRef(!1),H=tn(G=>{var R;if(!n||!o||!s||G.key!=="Escape"||$.current)return;const B=(R=i.current.floatingContext)==null?void 0:R.nodeId,P=y?Ea(y.nodesRef.current,B):[];if(!v&&(G.stopPropagation(),P.length>0)){let D=!0;if(P.forEach(Y=>{var A;if((A=Y.context)!=null&&A.open&&!Y.context.dataRef.current.__escapeKeyBubbles){D=!1;return}}),!D)return}r(!1,g8e(G)?G.nativeEvent:G,"escape-key")}),C=tn(G=>{var R;const B=()=>{var P;H(G),(P=jr(G))==null||P.removeEventListener("keydown",B)};(R=jr(G))==null||R.addEventListener("keydown",B)}),L=tn(G=>{var R;const B=i.current.insideReactTree;i.current.insideReactTree=!1;const P=k.current;if(k.current=!1,u==="click"&&P||B||typeof _=="function"&&!_(G))return;const D=jr(G),Y="["+Wa("inert")+"]",A=wn(a.floating).querySelectorAll(Y);let J=lt(D)?D:null;for(;J&&!Yn(J);){const ye=Qn(J);if(Yn(ye)||!lt(ye))break;J=ye}if(A.length&<(D)&&!p8e(D)&&!Cr(D,a.floating)&&Array.from(A).every(ye=>!Cr(J,ye)))return;if(Ot(D)&&ee){const ye=Yn(D),ke=mn(D),Oe=/auto|scroll/,ze=ye||Oe.test(ke.overflowX),He=ye||Oe.test(ke.overflowY),re=ze&&D.clientWidth>0&&D.scrollWidth>D.clientWidth,Ee=He&&D.clientHeight>0&&D.scrollHeight>D.clientHeight,Qe=ke.direction==="rtl",Je=Ee&&(Qe?G.offsetX<=D.offsetWidth-D.clientWidth:G.offsetX>D.clientWidth),we=re&&G.offsetY>D.clientHeight;if(Je||we)return}const te=(R=i.current.floatingContext)==null?void 0:R.nodeId,O=y&&Ea(y.nodesRef.current,te).some(ye=>{var ke;return rs(G,(ke=ye.context)==null?void 0:ke.elements.floating)});if(rs(G,a.floating)||rs(G,a.domReference)||O)return;const de=y?Ea(y.nodesRef.current,te):[];if(de.length>0){let ye=!0;if(de.forEach(ke=>{var Oe;if((Oe=ke.context)!=null&&Oe.open&&!ke.context.dataRef.current.__outsidePressBubbles){ye=!1;return}}),!ye)return}r(!1,G,"outside-press")}),W=tn(G=>{var R;const B=()=>{var P;L(G),(P=jr(G))==null||P.removeEventListener(u,B)};(R=jr(G))==null||R.addEventListener(u,B)});ne.useEffect(()=>{if(!n||!o)return;i.current.__escapeKeyBubbles=v,i.current.__outsidePressBubbles=M;let G=-1;function R(A){r(!1,A,"ancestor-scroll")}function B(){window.clearTimeout(G),$.current=!0}function P(){G=window.setTimeout(()=>{$.current=!1},yo()?5:0)}const D=wn(a.floating);s&&(D.addEventListener("keydown",S?C:H,S),D.addEventListener("compositionstart",B),D.addEventListener("compositionend",P)),_&&D.addEventListener(u,x?W:L,x);let Y=[];return m&&(lt(a.domReference)&&(Y=dr(a.domReference)),lt(a.floating)&&(Y=Y.concat(dr(a.floating))),!lt(a.reference)&&a.reference&&a.reference.contextElement&&(Y=Y.concat(dr(a.reference.contextElement)))),Y=Y.filter(A=>{var J;return A!==((J=D.defaultView)==null?void 0:J.visualViewport)}),Y.forEach(A=>{A.addEventListener("scroll",R,{passive:!0})}),()=>{s&&(D.removeEventListener("keydown",S?C:H,S),D.removeEventListener("compositionstart",B),D.removeEventListener("compositionend",P)),_&&D.removeEventListener(u,x?W:L,x),Y.forEach(A=>{A.removeEventListener("scroll",R)}),window.clearTimeout(G)}},[i,a,s,_,u,n,r,m,o,v,M,H,S,C,L,x,W]),ne.useEffect(()=>{i.current.insideReactTree=!1},[i,_,u]);const Z=ne.useMemo(()=>({onKeyDown:H,...d&&{[_7e[p]]:G=>{r(!1,G.nativeEvent,"reference-press")},...p!=="click"&&{onClick(G){r(!1,G.nativeEvent,"reference-press")}}}}),[H,r,d,p]),ee=ne.useMemo(()=>({onKeyDown:H,onMouseDown(){k.current=!0},onMouseUp(){k.current=!0},[w7e[u]]:()=>{i.current.insideReactTree=!0}}),[H,u,i]);return ne.useMemo(()=>o?{reference:Z,floating:ee}:{},[o,Z,ee])}function x7e(e){const{open:t=!1,onOpenChange:n,elements:r}=e,a=cp(),i=ne.useRef({}),[o]=ne.useState(()=>p7e()),s=xo()!=null;if(process.env.NODE_ENV!=="production"){const h=r.reference;h&&!lt(h)&&d7e("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]=ne.useState(r.reference),d=tn((h,f,y)=>{i.current.openEvent=h?f:void 0,o.emit("openchange",{open:h,event:f,reason:y,nested:s}),n?.(h,f,y)}),p=ne.useMemo(()=>({setPositionReference:u}),[]),m=ne.useMemo(()=>({reference:l||r.reference||null,floating:r.floating||null,domReference:r.reference}),[l,r.reference,r.floating]);return ne.useMemo(()=>({dataRef:i,open:t,onOpenChange:d,elements:m,events:o,floatingId:a,refs:p}),[t,d,m,o,a,p])}function dp(e){e===void 0&&(e={});const{nodeId:t}=e,n=x7e({...e,elements:{reference:null,floating:null,...e.elements}}),r=e.rootContext||n,a=r.elements,[i,o]=ne.useState(null),[s,l]=ne.useState(null),d=a?.domReference||i,p=ne.useRef(null),m=Eo();Tt(()=>{d&&(p.current=d)},[d]);const h=i7e({...e,elements:{...a,...s&&{reference:s}}}),f=ne.useCallback(v=>{const M=lt(v)?{getBoundingClientRect:()=>v.getBoundingClientRect(),getClientRects:()=>v.getClientRects(),contextElement:v}:v;l(M),h.refs.setReference(M)},[h.refs]),y=ne.useCallback(v=>{(lt(v)||v===null)&&(p.current=v,o(v)),(lt(h.refs.reference.current)||h.refs.reference.current===null||v!==null&&!lt(v))&&h.refs.setReference(v)},[h.refs]),w=ne.useMemo(()=>({...h.refs,setReference:y,setPositionReference:f,domReference:p}),[h.refs,y,f]),_=ne.useMemo(()=>({...h.elements,domReference:d}),[h.elements,d]),k=ne.useMemo(()=>({...h,...r,refs:w,elements:_,nodeId:t}),[h,w,_,t,r]);return Tt(()=>{r.dataRef.current.floatingContext=k;const v=m?.nodesRef.current.find(M=>M.id===t);v&&(v.context=k)}),ne.useMemo(()=>({...h,context:k,refs:w,elements:_}),[h,w,_,k])}function ds(){return l8e()&&U5()}function E7e(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=ne.useRef(!1),d=ne.useRef(-1),p=ne.useRef(!0);ne.useEffect(()=>{if(!s)return;const h=Kt(o.domReference);function f(){!n&&Ot(o.domReference)&&o.domReference===Ia(wn(o.domReference))&&(u.current=!0)}function y(){p.current=!0}function w(){p.current=!1}return h.addEventListener("blur",f),ds()&&(h.addEventListener("keydown",y,!0),h.addEventListener("pointerdown",w,!0)),()=>{h.removeEventListener("blur",f),ds()&&(h.removeEventListener("keydown",y,!0),h.removeEventListener("pointerdown",w,!0))}},[o.domReference,n,s]),ne.useEffect(()=>{if(!s)return;function h(f){let{reason:y}=f;(y==="reference-press"||y==="escape-key")&&(u.current=!0)}return a.on("openchange",h),()=>{a.off("openchange",h)}},[a,s]),ne.useEffect(()=>()=>{sn(d)},[]);const m=ne.useMemo(()=>({onMouseLeave(){u.current=!1},onFocus(h){if(u.current)return;const f=jr(h.nativeEvent);if(l&<(f)){if(ds()&&!h.relatedTarget){if(!p.current&&!rp(f))return}else if(!m8e(f))return}r(!0,h.nativeEvent,"focus")},onBlur(h){u.current=!1;const f=h.relatedTarget,y=h.nativeEvent,w=lt(f)&&f.hasAttribute(Wa("focus-guard"))&&f.getAttribute("data-type")==="outside";d.current=window.setTimeout(()=>{var _;const k=Ia(o.domReference?o.domReference.ownerDocument:document);!f&&k===o.domReference||Cr((_=i.current.floatingContext)==null?void 0:_.refs.floating.current,k)||Cr(o.domReference,k)||w||r(!1,y,"focus")})}}),[i,o.domReference,r,l]);return ne.useMemo(()=>s?{reference:m}:{},[s,m])}function ps(e,t,n){const r=new Map,a=n==="item";let i=e;if(a&&e){const{[c2]:o,[u2]:s,...l}=e;i=l}return{...n==="floating"&&{tabIndex:-1,[o7e]:""},...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&&[c2,u2].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,f=new Array(h),y=0;y<h;y++)f[y]=arguments[y];return(m=r.get(u))==null?void 0:m.map(w=>w(...f)).find(w=>w!==void 0)}}}else o[u]=d}),o),{})}}function pp(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=ne.useCallback(s=>ps(s,e,"reference"),t),i=ne.useCallback(s=>ps(s,e,"floating"),n),o=ne.useCallback(s=>ps(s,e,"item"),r);return ne.useMemo(()=>({getReferenceProps:a,getFloatingProps:i,getItemProps:o}),[a,i,o])}const M7e="Escape";function Mo(e,t,n){switch(e){case"vertical":return t;case"horizontal":return n;default:return t||n}}function oi(e,t){return Mo(t,e===t3||e===wo,e===Va||e===Ga)}function hs(e,t,n){return Mo(t,e===wo,n?e===Va:e===Ga)||e==="Enter"||e===" "||e===""}function v2(e,t,n){return Mo(t,n?e===Va:e===Ga,e===wo)}function _2(e,t,n,r){const a=n?e===Ga:e===Va,i=e===t3;return t==="both"||t==="horizontal"&&r&&r>1?e===M7e:Mo(t,a,i)}function S7e(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:f=!1,virtual:y=!1,focusItemOnOpen:w="auto",focusItemOnHover:_=!0,openOnArrowKeyDown:k=!0,disabledIndices:v=void 0,orientation:M="vertical",parentOrientation:S,cols:x=1,scrollItemIntoView:$=!0,virtualItemRef:H,itemSizes:C,dense:L=!1}=t;process.env.NODE_ENV!=="production"&&(p&&(m||ls("`useListNavigation` looping must be enabled to allow escaping."),y||ls("`useListNavigation` must be virtual to allow escaping.")),M==="vertical"&&x>1&&ls("In grid list navigation mode (`cols` > 1), the `orientation` should",'be either "horizontal" or "both".'));const W=j5(a.floating),Z=Gn(W),ee=xo(),G=Eo();Tt(()=>{e.dataRef.current.orientation=M},[e,M]);const R=tn(()=>{l(D.current===-1?null:D.current)}),B=h8e(a.domReference),P=ne.useRef(w),D=ne.useRef(d??-1),Y=ne.useRef(null),A=ne.useRef(!0),J=ne.useRef(R),te=ne.useRef(!!a.floating),O=ne.useRef(n),de=ne.useRef(!1),ye=ne.useRef(!1),ke=Gn(v),Oe=Gn(n),ze=Gn($),He=Gn(d),[re,Ee]=ne.useState(),[Qe,Je]=ne.useState(),we=tn(()=>{function _e(q){if(y){var X;(X=q.id)!=null&&X.endsWith("-fui-option")&&(q.id=i+"-"+Math.random().toString(16).slice(2,10)),Ee(q.id),G?.events.emit("virtualfocus",q),H&&(H.current=q)}else g7e(q,{sync:de.current,preventScroll:!0})}const Pe=o.current[D.current],Me=ye.current;Pe&&_e(Pe),(de.current?q=>q():requestAnimationFrame)(()=>{const q=o.current[D.current]||Pe;if(!q)return;Pe||_e(q);const X=ze.current;X&&ve&&(Me||!A.current)&&(q.scrollIntoView==null||q.scrollIntoView(typeof X=="boolean"?{block:"nearest",inline:"nearest"}:X))})});Tt(()=>{u&&(n&&a.floating?P.current&&d!=null&&(ye.current=!0,D.current=d,R()):te.current&&(D.current=-1,J.current()))},[u,n,a.floating,d,R]),Tt(()=>{if(u&&n&&a.floating)if(s==null){if(de.current=!1,He.current!=null)return;if(te.current&&(D.current=-1,we()),(!O.current||!te.current)&&P.current&&(Y.current!=null||P.current===!0&&Y.current==null)){let _e=0;const Pe=()=>{o.current[0]==null?(_e<2&&(_e?requestAnimationFrame:queueMicrotask)(Pe),_e++):(D.current=Y.current==null||hs(Y.current,M,f)||h?as(o,ke.current):n2(o,ke.current),Y.current=null,R())};Pe()}}else Ma(o,s)||(D.current=s,we(),ye.current=!1)},[u,n,a.floating,s,He,h,o,M,f,R,we,ke]),Tt(()=>{var _e;if(!u||a.floating||!G||y||!te.current)return;const Pe=G.nodesRef.current,Me=(_e=Pe.find(X=>X.id===ee))==null||(_e=_e.context)==null?void 0:_e.elements.floating,Ze=Ia(wn(a.floating)),q=Pe.some(X=>X.context&&Cr(X.context.elements.floating,Ze));Me&&!q&&A.current&&Me.focus({preventScroll:!0})},[u,a.floating,G,ee,y]),Tt(()=>{if(!u||!G||!y||ee)return;function _e(Pe){Je(Pe.id),H&&(H.current=Pe)}return G.events.on("virtualfocus",_e),()=>{G.events.off("virtualfocus",_e)}},[u,G,y,ee,H]),Tt(()=>{J.current=R,O.current=n,te.current=!!a.floating}),Tt(()=>{n||(Y.current=null,P.current=w)},[n,w]);const Ne=s!=null,ve=ne.useMemo(()=>{function _e(Me){if(!Oe.current)return;const Ze=o.current.indexOf(Me);Ze!==-1&&D.current!==Ze&&(D.current=Ze,R())}return{onFocus(Me){let{currentTarget:Ze}=Me;de.current=!0,_e(Ze)},onClick:Me=>{let{currentTarget:Ze}=Me;return Ze.focus({preventScroll:!0})},onMouseMove(Me){let{currentTarget:Ze}=Me;de.current=!0,ye.current=!1,_&&_e(Ze)},onPointerLeave(Me){let{pointerType:Ze}=Me;if(!(!A.current||Ze==="touch")&&(de.current=!0,!!_&&(D.current=-1,R(),!y))){var q;(q=Z.current)==null||q.focus({preventScroll:!0})}}}},[Oe,Z,_,o,R,y]),Be=ne.useCallback(()=>{var _e;return S??(G==null||(_e=G.nodesRef.current.find(Pe=>Pe.id===ee))==null||(_e=_e.context)==null||(_e=_e.dataRef)==null?void 0:_e.current.orientation)},[ee,G,S]),pe=tn(_e=>{if(A.current=!1,de.current=!0,_e.which===229||!Oe.current&&_e.currentTarget===Z.current)return;if(h&&_2(_e.key,M,f,x)){oi(_e.key,Be())||ln(_e),r(!1,_e.nativeEvent,"list-navigation"),Ot(a.domReference)&&(y?G?.events.emit("virtualfocus",a.domReference):a.domReference.focus());return}const Pe=D.current,Me=as(o,v),Ze=n2(o,v);if(B||(_e.key==="Home"&&(ln(_e),D.current=Me,R()),_e.key==="End"&&(ln(_e),D.current=Ze,R())),x>1){const q=C||Array.from({length:o.current.length},()=>({width:1,height:1})),X=M8e(q,x,L),le=X.findIndex(je=>je!=null&&!Oi(o,je,v)),he=X.reduce((je,xt,Mt)=>xt!=null&&!Oi(o,xt,v)?Mt:je,-1),Ae=X[E8e({current:X.map(je=>je!=null?o.current[je]:null)},{event:_e,orientation:M,loop:m,rtl:f,cols:x,disabledIndices:N8e([...(typeof v!="function"?v:null)||o.current.map((je,xt)=>Oi(o,xt,v)?xt:void 0),void 0],X),minIndex:le,maxIndex:he,prevIndex:S8e(D.current>Ze?Me:D.current,q,X,x,_e.key===wo?"bl":_e.key===(f?Va:Ga)?"tr":"tl"),stopEvent:!0})];if(Ae!=null&&(D.current=Ae,R()),M==="both")return}if(oi(_e.key,M)){if(ln(_e),n&&!y&&Ia(_e.currentTarget.ownerDocument)===_e.currentTarget){D.current=hs(_e.key,M,f)?Me:Ze,R();return}hs(_e.key,M,f)?m?D.current=Pe>=Ze?p&&Pe!==o.current.length?-1:Me:Ct(o,{startingIndex:Pe,disabledIndices:v}):D.current=Math.min(Ze,Ct(o,{startingIndex:Pe,disabledIndices:v})):m?D.current=Pe<=Me?p&&Pe!==-1?o.current.length:Ze:Ct(o,{startingIndex:Pe,decrement:!0,disabledIndices:v}):D.current=Math.max(Me,Ct(o,{startingIndex:Pe,decrement:!0,disabledIndices:v})),Ma(o,D.current)&&(D.current=-1),R()}}),Re=ne.useMemo(()=>y&&n&&Ne&&{"aria-activedescendant":Qe||re},[y,n,Ne,Qe,re]),rt=ne.useMemo(()=>({"aria-orientation":M==="both"?void 0:M,...B?{}:Re,onKeyDown:pe,onPointerMove(){A.current=!0}}),[Re,pe,M,B]),We=ne.useMemo(()=>{function _e(Me){w==="auto"&&y8e(Me.nativeEvent)&&(P.current=!0)}function Pe(Me){P.current=w,w==="auto"&&b8e(Me.nativeEvent)&&(P.current=!0)}return{...Re,onKeyDown(Me){A.current=!1;const Ze=Me.key.startsWith("Arrow"),q=["Home","End"].includes(Me.key),X=Ze||q,le=v2(Me.key,M,f),he=_2(Me.key,M,f,x),Ae=v2(Me.key,Be(),f),je=oi(Me.key,M),xt=(h?Ae:je)||Me.key==="Enter"||Me.key.trim()==="";if(y&&n){const yt=G?.nodesRef.current.find(St=>St.parentId==null),Nt=G&&yt?f8e(G.nodesRef.current,yt.id):null;if(X&&Nt&&H){const St=new KeyboardEvent("keydown",{key:Me.key,bubbles:!0});if(le||he){var Mt,Sn;const ri=((Mt=Nt.context)==null?void 0:Mt.elements.domReference)===Me.currentTarget,Hn=he&&!ri?(Sn=Nt.context)==null?void 0:Sn.elements.domReference:le?o.current.find(Fr=>Fr?.id===re):null;Hn&&(ln(Me),Hn.dispatchEvent(St),Je(void 0))}if((je||q)&&Nt.context&&Nt.context.open&&Nt.parentId&&Me.currentTarget!==Nt.context.elements.domReference){var Nn;ln(Me),(Nn=Nt.context.elements.domReference)==null||Nn.dispatchEvent(St);return}}return pe(Me)}if(!(!n&&!k&&Ze)){if(xt){const yt=oi(Me.key,Be());Y.current=h&&yt?null:Me.key}if(h){Ae&&(ln(Me),n?(D.current=as(o,ke.current),R()):r(!0,Me.nativeEvent,"list-navigation"));return}je&&(d!=null&&(D.current=d),ln(Me),!n&&k?r(!0,Me.nativeEvent,"list-navigation"):pe(Me),n&&R())}},onFocus(){n&&!y&&(D.current=-1,R())},onPointerDown:Pe,onPointerEnter:Pe,onMouseDown:_e,onClick:_e}},[re,Re,x,pe,ke,w,o,h,R,r,n,k,M,Be,f,d,G,y,H]);return ne.useMemo(()=>u?{reference:We,floating:rt,item:ve}:{},[u,We,rt,ve])}const N7e=new Map([["select","listbox"],["combobox","listbox"],["label",!1]]);function hp(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=cp(),d=((n=i.domReference)==null?void 0:n.id)||u,p=ne.useMemo(()=>{var k;return((k=j5(i.floating))==null?void 0:k.id)||o},[i.floating,o]),m=(r=N7e.get(l))!=null?r:l,f=xo()!=null,y=ne.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"&&f&&{role:"menuitem"},...l==="select"&&{"aria-autocomplete":"none"},...l==="combobox"&&{"aria-autocomplete":"list"}},[m,p,f,a,d,l]),w=ne.useMemo(()=>{const k={id:p,...m&&{role:m}};return m==="tooltip"||l==="label"?k:{...k,...m==="menu"&&{"aria-labelledby":d}}},[m,p,d,l]),_=ne.useCallback(k=>{let{active:v,selected:M}=k;const S={role:"option",...v&&{id:p+"-fui-option"}};switch(l){case"select":case"combobox":return{...S,"aria-selected":M}}return{}},[p,l]);return ne.useMemo(()=>s?{reference:y,floating:w,item:_}:{},[s,y,w,_])}const Wn=({content:e,children:t,placement:n="top",delay:r=300,disabled:a=!1,className:i=""})=>{const[o,s]=K.useState(!1),{refs:l,floatingStyles:u,context:d,isPositioned:p}=dp({open:o,onOpenChange:s,placement:n,strategy:"absolute",whileElementsMounted:ip,middleware:[op(8),lp(),sp({padding:8})]}),m=f7e(d,{delay:{open:r,close:0},enabled:!a}),h=E7e(d,{enabled:!a}),f=up(d,{enabled:!0,outsidePress:!0,outsidePressEvent:"mousedown",referencePress:!0,referencePressEvent:"mousedown",escapeKey:!0,ancestorScroll:!0}),y=hp(d,{role:"tooltip"}),{getReferenceProps:w,getFloatingProps:_}=pp([m,h,f,y]);return K.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(b7e,{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(),..._(),children:e})})]})},xn=({icon:e,size:t="md",iconSize:n,type:r="button",className:a="",tooltip:i,tooltipPlacement:o,...s})=>{const l=w6e[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(Wn,{content:i,placement:o,children:d}):d},mp=({text:e})=>{const[t,n]=K.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(Wn,{content:"Copy to clipboard",children:N.jsx(xn,{icon:t?"Check":"Copy",onClick:r,"aria-label":"Copy message",size:"sm"})})},yn=()=>nt().config.translations??ji,w2=300,i3=K.memo(({field:e,isExpanded:t,canApply:n,onToggleExpand:r,onApply:a})=>{const i=yn(),o=e.value.length>w2,s=o&&!t?`${e.value.slice(0,w2)}...`:e.value,l=K.useCallback(()=>{r(e.name)},[e.name,r]),u=K.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(xn,{icon:"Check",onClick:u,tooltip:`${i.formProposalApplyFieldPrefix} ${e.label||e.name}`,size:"sm"}),N.jsx(mp,{text:e.value})]})]})});i3.displayName="FormFieldRow";const A7e=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)},T7e=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:A7e(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}},o3=({call:e,chatId:t,applyAllButtonText:n,showStatus:r=!0})=>{const a=nt(),i=yn(),o=K.useMemo(()=>T7e(e),[e]),[s,l]=K.useState(new Set),u=K.useMemo(()=>{const S=(e.output??{})?._mp?.lastAction,x=typeof S?.action=="string"?S.action:void 0,$=typeof S?.at=="string"?S.at:void 0;return{action:x,at:$}},[e.output]),d=K.useMemo(()=>u.action==="apply",[u.action]),p=K.useMemo(()=>u.action==="reject",[u.action]),m=K.useMemo(()=>e.status===exports.AgentToolCallStatus.Succeeded&&!!o.formId&&o.fields.length>0&&!d,[e.status,o.formId,o.fields.length,d]);K.useMemo(()=>e.status===exports.AgentToolCallStatus.Succeeded&&!!o.formId&&o.fields.length>0&&!d&&!p,[e.status,o.formId,o.fields.length,d,p]);const h=K.useCallback(async v=>{o.formId&&a.transport.recordToolCallAction&&await a.transport.recordToolCallAction(t,{toolCallId:e.id,action:v.action,data:{formId:o.formId,formName:o.formName,fields:v.fields},systemMessage:v.action==="apply"?`Applied ${v.fields.length} field(s) to ${o.formName??o.formId}.`:`Rejected ${o.formName??o.formId} suggestion.`},{excludeSocketId:!1})},[o.formId,o.formName,t,e.id,a.transport]),f=K.useCallback(async v=>{if(o.formId){a.events.dispatchEvent(new CustomEvent(ep,{detail:{chatId:t,toolCallId:e.id,formId:o.formId,...o.formName?{formName:o.formName}:{},fields:v}}));try{await h({action:"apply",fields:v})}catch{return}}},[o.formId,o.formName,t,e.id,a.events,h]);K.useCallback(async()=>{if(o.formId)try{await h({action:"reject",fields:o.fields})}catch{return}},[o.formId,o.fields,h]);const y=K.useCallback(v=>{l(M=>{if(M.has(v)){if(M.size===1)return new Set;const S=new Set(M);return S.delete(v),S}else{const S=new Set(M);return S.add(v),S}})},[]),w=K.useCallback(v=>{f([v])},[f]),_=K.useCallback(()=>{f(o.fields)},[f,o.fields]);if(e.status===exports.AgentToolCallStatus.Failed&&e.error)return N.jsx("div",{className:"mp-agent-tool-body",children:N.jsx("div",{className:"mp-agent-tool-simple-message",children:i.formProposalFailed})});if(e.status!==exports.AgentToolCallStatus.Succeeded)return N.jsx("div",{className:"mp-agent-tool-simple-message",children:i.formProposalPreparing});if(!o.formId||o.fields.length===0)return N.jsx("div",{className:"mp-agent-tool-simple-message",children:i.formProposalNone});const k=K.useMemo(()=>o.formName?`${i.formProposalHeaderPrefix} ${o.formName}`:`${i.formProposalHeaderPrefix} ${o.formId}`,[o.formName,o.formId,i.formProposalHeaderPrefix]);return N.jsxs("div",{className:"mp-agent-tool-body",children:[N.jsx("div",{className:"mp-agent-tool-simple-message",children:k}),o.notes?N.jsx("div",{className:"mp-agent-tool-simple-message",children:o.notes}):null,N.jsx("div",{className:"mp-agent-form-proposal-fields",children:o.fields.map(v=>N.jsx(i3,{field:v,isExpanded:s.has(v.name),canApply:m,onToggleExpand:y,onApply:w},v.name))}),N.jsxs("div",{className:"mp-agent-form-proposal-actions",children:[r&&(d||p)&&N.jsxs("div",{className:"mp-agent-form-proposal-status",children:[N.jsx("span",{className:`mp-agent-form-proposal-badge ${d?"is-applied":"is-rejected"}`,children:d?i.formProposalApplied:i.formProposalRejected}),u.at?N.jsx("span",{className:"mp-agent-form-proposal-status-time",children:N.jsx(M6e,{date:u.at})}):null]}),N.jsxs("button",{type:"button",onClick:_,className:"mp-agent-form-proposal-apply-all",children:[N.jsx(N5,{size:14})," ",n||i.formProposalApplyAll]})]})]})},So=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),f=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??Rt.nanoid(),type:exports.AgentAttachmentType.Context,name:f,...d?{url:d}:{},metadata:{schemaVersion:1,kind:l,capturedAt:a??new Date().toISOString(),...p?{source:p}:{},...h?{security:h}:{},...s?{target:s}:{},...u}}},C7e=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())}},s3=(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=C7e(t)?!0:void 0;return So({kind:"pageContext",name:e.name??"Page context",url:t,title:o,summary:l?`${l.pathname}${l.search}${l.hash}`:void 0,data:u,source:{app:"browser",url:t,route:l?`${l.pathname}${l.search}${l.hash}`:void 0},...d?{security:{containsPII:!0,redactionsApplied:[]}}:{}})},l3=()=>{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?R7e(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}:{}}}},R7e=e=>{if(e.id)return`#${x2(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(`#${x2(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(" > ")},x2=e=>e.replace(/[^a-zA-Z0-9_-]/g,"\\$&");class c3{constructor(t){this.rawConfig=t,this.events=new EventTarget;const n=cd.parse(t);this.config={...n,toolRenderers:t.toolRenderers,tools:t.tools,pageContext:t.pageContext?{...n.pageContext,...t.pageContext}:n.pageContext,translations:t.translations?{...ji,...t.translations}:ji},this.transport=this.createTransport(this.config.transport),this.tools=new v_(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",o3),this.queryClient=new Bt.QueryClient({defaultOptions:{queries:{staleTime:3e4,refetchOnWindowFocus:!1}}})}config;transport;tools;queryClient;events;toolRendererMap=new Map;storeRef;pageContextProviders=new Set;createTransport(t){return t.mode==="proxy"?new Yr(t):new es(t)}configureTransportAfterCreate(t){this.config.transport.mode==="direct"&&t instanceof es&&(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=cd.parse({...this.rawConfig,transport:t}),r=this.config.transport,a=this.transport;this.rawConfig={...this.rawConfig,transport:t},this.config.transport=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 Yr?a.updateConfig(this.config.transport):i==="direct"&&a instanceof es?(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}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 s3({...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:Rt.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 I7e={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"},u3=e=>({...I7e,...e}),d3=K.createContext(u3()),O7e=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}),p3=({value:e,children:t})=>{const n=K.useMemo(()=>u3(e),[e]);return N.jsxs(d3.Provider,{value:n,children:[N.jsx("style",{children:`:root {
|
|
8320
8320
|
${Object.entries(O7e(n)).map(([r,a])=>`${r}: ${a};`).join(`
|
|
8321
8321
|
`)}
|
|
8322
|
-
}`}),t]})},L7e=()=>K.useContext(d3),si=e=>e.type===exports.AgentAttachmentType.Context&&e?.metadata?.kind==="pageContext";var Cn=(e=>(e.Idle="idle",e.Sending="sending",e.Streaming="streaming",e))(Cn||{});const h3=()=>({messages:[],reasoning:[],artifacts:[],pendingAssistant:void 0,messageQueue:[],composerDraft:{value:"",attachments:[]},composerError:void 0,pageContextDismissed:!1,status:"idle"}),et=(e,t)=>e.chatState[t]??h3(),D7e=e=>h5.create()((t,n)=>({contextKey:e,activeChatId:void 0,draftChatKey:`draft-${Rt.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=et(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=et(i,r);return{chatState:{...i.chatState,[r]:{...o,reasoning:[...o.reasoning,a]}}}}),setArtifacts:(r,a)=>t(i=>{const o=et(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=et(i,r);return{chatState:{...i.chatState,[r]:{...o,composerDraft:{value:a.value??"",attachments:a.attachments??[]}}}}}),setComposerValue:(r,a)=>t(i=>{const o=et(i,r);return{chatState:{...i.chatState,[r]:{...o,composerDraft:{...o.composerDraft,value:a}}}}}),addComposerAttachments:(r,a)=>t(i=>{const o=et(i,r),s=o.composerDraft.attachments??[];if(!a||a.length===0)return i;const l=s.find(si),u=a.find(si);if(u){const m=a.filter(_=>!si(_)),h=s.filter(_=>!si(_)),y=[l?{...u,id:l.id}:u,...m,...h],w=new Map;for(const _ of y)w.set(_.id,_);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=et(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=et(a,r);return{chatState:{...a.chatState,[r]:{...i,composerDraft:{value:"",attachments:[]}}}}}),setComposerError:(r,a)=>t(i=>{const o=et(i,r);return{chatState:{...i.chatState,[r]:{...o,composerError:a}}}}),setPageContextDismissed:(r,a)=>t(i=>{const o=et(i,r);return{chatState:{...i.chatState,[r]:{...o,pageContextDismissed:a}}}}),setChatStatus:(r,a)=>t(i=>{const o=et(i,r);return{chatState:{...i.chatState,[r]:{...o,status:a}}}}),setPendingAssistant:(r,a)=>t(i=>{const o=et(i,r);return{chatState:{...i.chatState,[r]:{...o,pendingAssistant:a}}}}),commitPendingAssistant:r=>t(a=>{const i=et(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=et(o,r),l={id:Rt.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=et(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=et(i,r),s=et(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]:h3()}}}),appendSystemMessage:(r,a)=>t(i=>{const o=et(i,r),s={id:Rt.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=et(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=et(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=et(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}}}})})),E2="mp-agent-selected-model",ka="__auto__";function m3(e){return e.mode==="direct"?`${E2}-${e.mode}-${e.provider}`:`${E2}-${e.mode}`}function M2(e,t){try{const n=m3(e);localStorage.setItem(n,t)}catch(n){console.warn("Failed to save selected model to localStorage:",n)}}function z7e(e){try{const t=m3(e);return localStorage.getItem(t)}catch(t){return console.warn("Failed to load selected model from localStorage:",t),null}}function f3(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 $7e(e,t,n){const r=z7e(t);if(r){if(r===ka)return;if(f3(e,t).some(i=>i.id===r))return r}}const F7e="mp-agents-last-active-chat";function g3(e){return`${F7e}-${e}`}function y3(e){return typeof e=="string"&&e.length>0&&e.length<256}function P7e(e){if(typeof window>"u")return null;try{const t=localStorage.getItem(g3(e));return t&&y3(t)?t:null}catch{return null}}function q7e(e,t){if(!(typeof window>"u"))try{const n=g3(e);t&&y3(t)?localStorage.setItem(n,t):localStorage.removeItem(n)}catch{}}const S2="mp-agents-guest-user-id";function ta(){if(typeof window>"u")return`${Vi.DefaultUserId}-${Rt.nanoid()}`;const e=localStorage.getItem(S2);if(e)return e;const t=`${Vi.DefaultUserId}-${Rt.nanoid()}`;return localStorage.setItem(S2,t),t}const zn=Object.create(null);zn.open="0";zn.close="1";zn.ping="2";zn.pong="3";zn.message="4";zn.upgrade="5";zn.noop="6";const Di=Object.create(null);Object.keys(zn).forEach(e=>{Di[zn[e]]=e});const yd={type:"error",data:"parser error"},b3=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",k3=typeof ArrayBuffer=="function",v3=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,fp=({type:e,data:t},n,r)=>b3&&t instanceof Blob?n?r(t):N2(t,r):k3&&(t instanceof ArrayBuffer||v3(t))?n?r(t):N2(new Blob([t]),r):r(zn[e]+(t||"")),N2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function A2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let ms;function B7e(e,t){if(b3&&e.data instanceof Blob)return e.data.arrayBuffer().then(A2).then(t);if(k3&&(e.data instanceof ArrayBuffer||v3(e.data)))return t(A2(e.data));fp(e,!1,n=>{ms||(ms=new TextEncoder),t(ms.encode(n))})}const T2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",va=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<T2.length;e++)va[T2.charCodeAt(e)]=e;const U7e=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=va[e.charCodeAt(r)],o=va[e.charCodeAt(r+1)],s=va[e.charCodeAt(r+2)],l=va[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},H7e=typeof ArrayBuffer=="function",gp=(e,t)=>{if(typeof e!="string")return{type:"message",data:_3(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:j7e(e.substring(1),t)}:Di[n]?e.length>1?{type:Di[n],data:e.substring(1)}:{type:Di[n]}:yd},j7e=(e,t)=>{if(H7e){const n=U7e(e);return _3(n,t)}else return{base64:!0,data:e}},_3=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},w3="",V7e=(e,t)=>{const n=e.length,r=new Array(n);let a=0;e.forEach((i,o)=>{fp(i,!1,s=>{r[o]=s,++a===n&&t(r.join(w3))})})},G7e=(e,t)=>{const n=e.split(w3),r=[];for(let a=0;a<n.length;a++){const i=gp(n[a],t);if(r.push(i),i.type==="error")break}return r};function W7e(){return new TransformStream({transform(e,t){B7e(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 fs;function li(e){return e.reduce((t,n)=>t+n.length,0)}function ci(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 K7e(e,t){fs||(fs=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(li(n)<1)break;const l=ci(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(li(n)<2)break;const l=ci(n,2);a=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),r=3}else if(r===2){if(li(n)<8)break;const l=ci(n,8),u=new DataView(l.buffer,l.byteOffset,l.length),d=u.getUint32(0);if(d>Math.pow(2,21)-1){s.enqueue(yd);break}a=d*Math.pow(2,32)+u.getUint32(4),r=3}else{if(li(n)<a)break;const l=ci(n,a);s.enqueue(gp(i?l:fs.decode(l),t)),r=0}if(a===0||a>e){s.enqueue(yd);break}}}})}const x3=4;function vt(e){if(e)return Y7e(e)}function Y7e(e){for(var t in vt.prototype)e[t]=vt.prototype[t];return e}vt.prototype.on=vt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};vt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};vt.prototype.off=vt.prototype.removeListener=vt.prototype.removeAllListeners=vt.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};vt.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};vt.prototype.emitReserved=vt.prototype.emit;vt.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};vt.prototype.hasListeners=function(e){return!!this.listeners(e).length};const No=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),cn=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Z7e="arraybuffer";function E3(e,...t){return t.reduce((n,r)=>(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const X7e=cn.setTimeout,Q7e=cn.clearTimeout;function Ao(e,t){t.useNativeTimers?(e.setTimeoutFn=X7e.bind(cn),e.clearTimeoutFn=Q7e.bind(cn)):(e.setTimeoutFn=cn.setTimeout.bind(cn),e.clearTimeoutFn=cn.clearTimeout.bind(cn))}const J7e=1.33;function e_e(e){return typeof e=="string"?t_e(e):Math.ceil((e.byteLength||e.size)*J7e)}function t_e(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 M3(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function n_e(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function r_e(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 a_e extends Error{constructor(t,n,r){super(t),this.description=n,this.context=r,this.type="TransportError"}}class yp extends vt{constructor(t){super(),this.writable=!1,Ao(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 a_e(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=gp(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=n_e(t);return n.length?"?"+n:""}}class i_e extends yp{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)};G7e(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,V7e(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]=M3()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}}let S3=!1;try{S3=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const o_e=S3;function s_e(){}class l_e extends i_e{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 Dn extends vt{constructor(t,n,r){super(),this.createRequest=t,Ao(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=E3(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=Dn.requestsCount++,Dn.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=s_e,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Dn.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()}}Dn.requestsCount=0;Dn.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",C2);else if(typeof addEventListener=="function"){const e="onpagehide"in cn?"pagehide":"unload";addEventListener(e,C2,!1)}}function C2(){for(let e in Dn.requests)Dn.requests.hasOwnProperty(e)&&Dn.requests[e].abort()}const c_e=function(){const e=N3({xdomain:!1});return e&&e.responseType!==null}();class u_e extends l_e{constructor(t){super(t);const n=t&&t.forceBase64;this.supportsBinary=c_e&&!n}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Dn(N3,this.uri(),t)}}function N3(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||o_e))return new XMLHttpRequest}catch{}if(!t)try{return new cn[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const A3=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class d_e extends yp{get name(){return"websocket"}doOpen(){const t=this.uri(),n=this.opts.protocols,r=A3?{}:E3(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;fp(r,this.supportsBinary,i=>{try{this.doWrite(r,i)}catch{}a&&No(()=>{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]=M3()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}}const gs=cn.WebSocket||cn.MozWebSocket;class p_e extends d_e{createSocket(t,n,r){return A3?new gs(t,n,r):n?new gs(t,n):new gs(t)}doWrite(t,n){this.ws.send(n)}}class h_e extends yp{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=K7e(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),a=W7e();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&&No(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const m_e={websocket:p_e,webtransport:h_e,polling:u_e},f_e=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,g_e=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function bd(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=f_e.exec(e||""),i={},o=14;for(;o--;)i[g_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=y_e(i,i.path),i.queryKey=b_e(i,i.query),i}function y_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 b_e(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,a,i){a&&(n[a]=i)}),n}const kd=typeof addEventListener=="function"&&typeof removeEventListener=="function",zi=[];kd&&addEventListener("offline",()=>{zi.forEach(e=>e())},!1);class pr extends vt{constructor(t,n){if(super(),this.binaryType=Z7e,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=bd(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=bd(n.host).host);Ao(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=r_e(this.opts.query)),kd&&(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"})},zi.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=x3,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&&pr.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",pr.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+=e_e(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,No(()=>{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(pr.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(),kd&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const r=zi.indexOf(this._offlineEventListener);r!==-1&&zi.splice(r,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this._prevBufferLen=0}}}pr.protocol=x3;class k_e extends pr{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;pr.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;pr.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 v_e=class extends k_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=>m_e[a]).filter(a=>!!a)),super(t,r)}};function __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=bd(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 w_e=typeof ArrayBuffer=="function",x_e=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,T3=Object.prototype.toString,E_e=typeof Blob=="function"||typeof Blob<"u"&&T3.call(Blob)==="[object BlobConstructor]",M_e=typeof File=="function"||typeof File<"u"&&T3.call(File)==="[object FileConstructor]";function bp(e){return w_e&&(e instanceof ArrayBuffer||x_e(e))||E_e&&e instanceof Blob||M_e&&e instanceof File}function $i(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,r=e.length;n<r;n++)if($i(e[n]))return!0;return!1}if(bp(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return $i(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&$i(e[n]))return!0;return!1}function S_e(e){const t=[],n=e.data,r=e;return r.data=vd(n,t),r.attachments=t.length,{packet:r,buffers:t}}function vd(e,t){if(!e)return e;if(bp(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]=vd(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]=vd(e[r],t));return n}return e}function N_e(e,t){return e.data=_d(e.data,t),delete e.attachments,e}function _d(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]=_d(e[n],t);else if(typeof e=="object")for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=_d(e[n],t));return e}const A_e=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],T_e=5;var Ge;(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"})(Ge||(Ge={}));class C_e{constructor(t){this.replacer=t}encode(t){return(t.type===Ge.EVENT||t.type===Ge.ACK)&&$i(t)?this.encodeAsBinary({type:t.type===Ge.EVENT?Ge.BINARY_EVENT:Ge.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let n=""+t.type;return(t.type===Ge.BINARY_EVENT||t.type===Ge.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=S_e(t),r=this.encodeAsString(n.packet),a=n.buffers;return a.unshift(r),a}}function R2(e){return Object.prototype.toString.call(e)==="[object Object]"}class kp extends vt{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===Ge.BINARY_EVENT;r||n.type===Ge.BINARY_ACK?(n.type=r?Ge.EVENT:Ge.ACK,this.reconstructor=new R_e(n),n.attachments===0&&super.emitReserved("decoded",n)):super.emitReserved("decoded",n)}else if(bp(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(Ge[r.type]===void 0)throw new Error("unknown packet type "+r.type);if(r.type===Ge.BINARY_EVENT||r.type===Ge.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(kp.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 Ge.CONNECT:return R2(n);case Ge.DISCONNECT:return n===void 0;case Ge.CONNECT_ERROR:return typeof n=="string"||R2(n);case Ge.EVENT:case Ge.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&A_e.indexOf(n[0])===-1);case Ge.ACK:case Ge.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class R_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=N_e(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const I_e=Object.freeze(Object.defineProperty({__proto__:null,Decoder:kp,Encoder:C_e,get PacketType(){return Ge},protocol:T_e},Symbol.toStringTag,{value:"Module"}));function kn(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const O_e=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class C3 extends vt{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=[kn(t,"open",this.onopen.bind(this)),kn(t,"packet",this.onpacket.bind(this)),kn(t,"error",this.onerror.bind(this)),kn(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(O_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:Ge.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:Ge.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 Ge.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 Ge.EVENT:case Ge.BINARY_EVENT:this.onevent(t);break;case Ge.ACK:case Ge.BINARY_ACK:this.onack(t);break;case Ge.DISCONNECT:this.ondisconnect();break;case Ge.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:Ge.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:Ge.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 oa(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}oa.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};oa.prototype.reset=function(){this.attempts=0};oa.prototype.setMin=function(e){this.ms=e};oa.prototype.setMax=function(e){this.max=e};oa.prototype.setJitter=function(e){this.jitter=e};class wd extends vt{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,Ao(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 oa({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||I_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 v_e(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const a=kn(n,"open",function(){r.onopen(),t&&t()}),i=s=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",s),t?t(s):this.maybeReconnectOnOpen()},o=kn(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(kn(t,"ping",this.onping.bind(this)),kn(t,"data",this.ondata.bind(this)),kn(t,"error",this.onerror.bind(this)),kn(t,"close",this.onclose.bind(this)),kn(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){No(()=>{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 C3(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 ma={};function Fi(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=__e(e,t.path||"/socket.io"),r=n.source,a=n.id,i=n.path,o=ma[a]&&i in ma[a].nsps,s=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let l;return s?l=new wd(r,t):(ma[a]||(ma[a]=new wd(r,t)),l=ma[a]),n.query&&!t.query&&(t.query=n.queryKey),l.socket(n.path,t)}Object.assign(Fi,{Manager:wd,Socket:C3,io:Fi,connect:Fi});const L_e=K.createContext(null),D_e=({children:e})=>{const t=nt(),n=xe(y=>y.upsertChat),r=xe(y=>y.upsertChatState),a=xe(y=>y.contextKey),i=K.useMemo(()=>t.config.user?.id??ta(),[t.config.user?.id]),o=t.config.transport,[s,l]=K.useState(null),[u,d]=K.useState(void 0),p=K.useRef(a),m=K.useRef(n),h=K.useRef(r);K.useEffect(()=>{p.current=a,m.current=n,h.current=r},[a,n,r]),K.useEffect(()=>{if(o.mode!=="proxy"){l(null),d(void 0),t.transport instanceof Yr&&t.transport.setSocketId(void 0);return}const y=o.baseUrl,w=new URL(y,window.location.origin),_=`${w.protocol}//${w.host}`,k=o.socketNamespace,v=k?`${_}${k}`:_,M={},S=o;S.headers&&Object.assign(M,S.headers);const x={},$=S.apiKey&&`Bearer ${S.apiKey}`||S.headers?.Authorization;$&&(x.authorization=$,M.Authorization=$);const H=o.socketPath??Vi.Path,C=Fi(v,{path:H,auth:x,transports:["websocket","polling"],...Object.keys(M).length>0&&{extraHeaders:M}});l(C);const L=()=>{d(C.id),t.transport instanceof Yr&&t.transport.setSocketId(C.id)},W=()=>{d(void 0),t.transport instanceof Yr&&t.transport.setSocketId(void 0)},Z=R=>{R.contextKey===p.current&&m.current(R)},ee=R=>{const B=t.store.getState(),P=et(B,R.chat),D=P.messages.findIndex(Y=>Y.id===R.id);if(D>=0){const Y=[...P.messages];Y[D]=R,h.current(R.chat,{...P,messages:Y});return}h.current(R.chat,{...P,messages:[...P.messages,R]})},G=R=>{m.current(R)};return C.on("connect",L),C.on("disconnect",W),C.on("connect_error",R=>{console.error("Socket.IO connection error:",R.message)}),C.on(Ii.ChatNew,Z),C.on(Ii.MessageNew,ee),C.on(Ii.ChatUpdate,G),()=>{t.transport instanceof Yr&&t.transport.setSocketId(void 0),d(void 0),l(null),C.disconnect()}},[t,t.transport,o.mode,o.mode==="proxy"?o.baseUrl:void 0,o.mode==="proxy"?o.apiKey:void 0,o.mode==="proxy"?o.socketPath:void 0,o.mode==="proxy"?o.socketNamespace:void 0,o.mode==="proxy"?JSON.stringify(o.headers??{}):"",i]);const f=K.useMemo(()=>({socket:s,socketId:u}),[s,u]);return N.jsx(L_e.Provider,{value:f,children:e})},vp=K.createContext(null),z_e=({config:e,children:t})=>{const n=K.useRef();n.current||(n.current=new c3(e));const[,r]=K.useState(0);K.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=K.useRef();if(!a.current){const o=n.current.defaultContextKey??n.current.config.contextKeys[0]?.key??"default";a.current=D7e(o),n.current.attachStore(a.current);const s=n.current.config.user?.id??ta(),l=P7e(s);l&&a.current.getState().setActiveChat(l);const u=$7e(n.current.config.models,n.current.config.transport);a.current.getState().setComposerOptions({model:u})}const i=K.useMemo(()=>({runtime:n.current,store:a.current}),[]);return K.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??ta();q7e(u,l)})},[]),N.jsx(vp.Provider,{value:i,children:N.jsx(Bt.QueryClientProvider,{client:i.runtime.queryClient,children:N.jsx(p3,{value:i.runtime.config.theme,children:N.jsx(D_e,{children:t})})})})},nt=()=>{const e=K.useContext(vp);if(!e)throw new Error("useAgentRuntime must be used inside <AgentProvider />");return e.runtime},xe=e=>{const t=K.useContext(vp);if(!t)throw new Error("useAgentStore must be used inside <AgentProvider />");return h5.useStore(t.store,e)},To=30*1e3,Co=5*60*1e3,R3=20,_n={all:["mp-agents","activities"],lists:()=>[..._n.all,"list"],list:e=>[..._n.lists(),e],infinites:()=>[..._n.all,"infinite"],infinite:e=>[..._n.infinites(),e],detail:e=>[..._n.all,"detail",e],summary:e=>[..._n.all,"summary",e]},$_e=e=>e?.pages.flatMap(t=>t.data)??[],I3=(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.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}},O3=e=>({data:[],cursor:{total:0,skip:0,limit:e}}),F_e=e=>{const t=nt(),{groupId:n,parentId:r,enabled:a=!0,sortOrder:i=exports.SortOrder.Desc,sortField:o="createdAt",pageSize:s=R3,from:l,to:u,tenant:d,ownerId:p}=e??{};return Bt.useInfiniteQuery({queryKey:_n.infinite({groupId:n,parentId:r,sortField:o,sortOrder:i,pageSize:s,from:l,to:u,tenant:d,ownerId:p}),queryFn:async({pageParam:m})=>t.transport.listActivities?t.transport.listActivities(I3({groupId:n,parentId:r,sortField:o,sortOrder:i,from:l,to:u,tenant:d,ownerId:p},m,s)):O3(s),initialPageParam:0,getNextPageParam:m=>{const h=(m.cursor.skip??0)+m.data.length;return h<m.cursor.total?h:void 0},enabled:a&&!!t.transport.listActivities,staleTime:To,gcTime:Co})},P_e=e=>{const t=nt(),{groupId:n,parentId:r,page:a,enabled:i=!0,sortOrder:o=exports.SortOrder.Desc,sortField:s="createdAt",pageSize:l=R3,from:u,to:d,tenant:p,ownerId:m}=e,h=(a-1)*l,f=Bt.useQuery({queryKey:_n.list({groupId:n,parentId:r,sortField:s,sortOrder:o,pageSize:l,page:a,from:u,to:d,tenant:p,ownerId:m}),queryFn:async()=>t.transport.listActivities?t.transport.listActivities(I3({groupId:n,parentId:r,sortField:s,sortOrder:o,from:u,to:d,tenant:p,ownerId:m},h,l)):O3(l),enabled:i&&!!t.transport.listActivities&&a>=1,staleTime:To,gcTime:Co}),y=f.data?.cursor.total??0,w=Math.max(1,Math.ceil(y/l));return{...f,page:a,pageSize:l,totalPages:w,total:y,hasNextPage:a<w,hasPreviousPage:a>1}},q_e=e=>{const t=nt();return Bt.useQuery({queryKey:_n.detail(e),queryFn:async()=>!e||!t.transport.getActivity?null:t.transport.getActivity(e),enabled:!!e&&!!t.transport.getActivity,staleTime:To,gcTime:Co})},B_e=e=>{const t=nt(),{enabled:n=!0,...r}=e??{};return Bt.useQuery({queryKey:_n.summary(r),queryFn:async()=>t.transport.getActivitySummary?t.transport.getActivitySummary(r):[],enabled:n&&!!t.transport.getActivitySummary,staleTime:To,gcTime:Co})},L3=30*1e3,D3=5*60*1e3,_p=20,sr={all:["mp-agents","chats"],lists:()=>[...sr.all,"list"],list:e=>[...sr.lists(),e],infinites:()=>[...sr.all,"infinite"],infinite:e=>[...sr.infinites(),e],detail:e=>[...sr.all,"detail",e]},U_e=e=>e?.pages.flatMap(t=>t.data)??[],z3=e=>{const t=nt(),n=t.config.user?.id??ta(),{pageSize:r=_p,sortOrder:a="desc",sortField:i="updatedAt",enabled:o=!0}=e??{};return Bt.useInfiniteQuery({queryKey:sr.infinite({userId:n,sortField:i,sortOrder:a,pageSize:r}),queryFn:async({pageParam:s})=>await t.transport.listChats({userId:n,skip:s,limit:r,sortOrder:a,sortField:i}),initialPageParam:0,getNextPageParam:s=>{const{cursor:l,data:u}=s,d=(l.skip??0)+u.length;return d<l.total?d:void 0},enabled:o&&!!n,staleTime:L3,gcTime:D3})},$3=z3,H_e=e=>{const t=nt(),n=t.config.user?.id??ta(),{page:r,pageSize:a=_p,sortOrder:i="desc",sortField:o="updatedAt",enabled:s=!0}=e,l=(r-1)*a,u=Bt.useQuery({queryKey:sr.list({userId:n,sortField:o,sortOrder:i,pageSize:a,page:r}),queryFn:async()=>t.transport.listChats({userId:n,skip:l,limit:a,sortOrder:i,sortField:o}),enabled:s&&!!n&&r>=1,staleTime:L3,gcTime:D3}),d=u.data?.cursor.total??0,p=Math.max(1,Math.ceil(d/a));return{...u,page:r,pageSize:a,totalPages:p,total:d,hasNextPage:r<p,hasPreviousPage:r>1}},wp=e=>{const t=$3(e),n=xe(r=>r.hydrateChats);return K.useEffect(()=>{if(t.data?.pages){const r=t.data.pages.flatMap(a=>a.data);n(r)}},[t.data,n]),t},F3=(e={},t=[])=>{const{threshold:n=50,scrollOnMount:r=!0}=e,a=K.useRef(null),i=K.useRef(null),[o,s]=K.useState(!0),l=K.useRef(!1),u=K.useRef(!1),d=K.useRef(),p=K.useCallback(()=>{const f=a.current;if(!f)return!1;const{scrollTop:y,scrollHeight:w,clientHeight:_}=f;return w-y-_<=n},[n]),m=K.useCallback(()=>{const f=a.current,y=i.current;!f||!y||y.scrollIntoView({behavior:"auto",block:"end"})},[]),h=K.useCallback(()=>{const f=p();s(f),f&&(l.current=!1)},[p]);return K.useEffect(()=>{const f=a.current;if(!f)return;let y=f.scrollTop,w;const _=()=>{const k=f.scrollTop;if(!u.current){const v=k<y,M=k>y;(v||M&&!p())&&(l.current=!0)}y=k,h(),w&&clearTimeout(w),w=window.setTimeout(()=>{u.current=!1},150)};return f.addEventListener("scroll",_,{passive:!0}),()=>{f.removeEventListener("scroll",_),w&&clearTimeout(w)}},[p,h]),K.useEffect(()=>{const f=a.current;if(!f)return;const y=new MutationObserver(()=>{!l.current&&o&&(d.current&&cancelAnimationFrame(d.current),d.current=requestAnimationFrame(()=>{u.current=!0,m(),setTimeout(()=>{u.current=!1},50)})),h()});return y.observe(f,{childList:!0,subtree:!0,characterData:!0,attributes:!1}),()=>{y.disconnect(),d.current&&cancelAnimationFrame(d.current)}},[o,m,h]),K.useEffect(()=>{t.length!==0&&!l.current&&o&&(d.current&&cancelAnimationFrame(d.current),d.current=requestAnimationFrame(()=>{u.current=!0,m(),setTimeout(()=>{u.current=!1},50)}))},[...t]),K.useEffect(()=>{if(r&&a.current){const f=window.setTimeout(()=>{u.current=!0,m(),setTimeout(()=>{u.current=!1},50)},100);return()=>{clearTimeout(f)}}},[r,m]),{containerRef:a,sentinelRef:i,isNearBottom:o,scrollToBottom:m,checkIsNearBottom:p}},P3=()=>{const e=nt();return Bt.useQuery({queryKey:["mp-agents","models"],queryFn:async()=>e.transport.listModels?await e.transport.listModels():[],staleTime:5*60*1e3,refetchOnWindowFocus:!1})},q3=()=>{const e=xe(s=>s.activeChatId??s.draftChatKey),t=xe(s=>et(s,e).composerDraft),n=xe(s=>s.setComposerValue),r=xe(s=>s.setComposerDraft),a=xe(s=>s.clearComposerDraft),i=xe(s=>s.addComposerAttachments),o=xe(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)}},B3=e=>{const t=nt();return Bt.useQuery({queryKey:["mp-agents","configurations",e??"all"],queryFn:async()=>t.transport.listAgentConfigurations?t.transport.listAgentConfigurations(e):[],staleTime:6e4,refetchOnWindowFocus:!1})},j_e=(e,t=[])=>{const n=nt(),r=K.useRef(e),a=K.useCallback(e,t);r.current=a;const i=K.useCallback(o=>r.current(o),[]);K.useEffect(()=>n.registerPageContextProvider(i),[n,i])},U3=(e,t,n=[],r)=>{const a=nt(),i=K.useRef(t),o=K.useCallback(t,n);i.current=o;const s=K.useCallback(u=>{i.current(u)},[]),l=typeof r=="boolean"?r:r?.capture;K.useEffect(()=>(a.events.addEventListener(e,s,r),()=>{a.events.removeEventListener(e,s,l)}),[a,e,s,l])},V_e=({formId:e,onApply:t,enabled:n=!0})=>{U3(ep,r=>{n&&r.detail.formId===e&&t(r.detail)},[n,e,t])},G_e=["mp-agents","configurations"],H3=()=>{const e=nt(),t=Bt.useQueryClient(),n=()=>t.invalidateQueries({queryKey:G_e}),r=Bt.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=Bt.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}},j3=()=>{const e=nt(),t=xe(s=>s.activeChatId),n=xe(s=>s.chats),r=xe(s=>s.upsertChat),a=xe(s=>s.setActiveChat),i=!!t&&!n[t],o=Bt.useQuery({queryKey:["mp-agents","chat",t],queryFn:()=>e.transport.getChat(t),enabled:i,staleTime:6e4,retry:!1});return K.useEffect(()=>{o.data&&r(o.data)},[o.data,r]),K.useEffect(()=>{o.isError&&t&&a(void 0)},[o.isError,t,a]),o},V3=30,G3=e=>{const t=nt(),n=xe(i=>i.setChatMessages),r=xe(i=>!!(e&&i.chats[e])),a=Bt.useInfiniteQuery({queryKey:["mp-agents","messages",e],queryFn:async({pageParam:i})=>{if(!e||!t.transport.getMessages)throw new Error("No chat or transport");return await t.transport.getMessages(e,{limit:V3,...i?{before:i}:{}})},initialPageParam:void 0,getNextPageParam:i=>i.hasMore&&i.messages.length>0?i.messages[0]?.id:void 0,enabled:!!e&&!!t.transport.getMessages&&r});return K.useEffect(()=>{if(!e||!a.data?.pages)return;const o=a.data.pages.slice().reverse().flatMap(l=>l.messages),s=new Set(o.map(l=>l.id));n(e,l=>{const u=l.filter(d=>!s.has(d.id));return[...o,...u]})},[e,a.data,n]),a},W3=()=>{const e=nt(),t=e.config.user?.id??ta(),n=xe(u=>u.activeChatId),r=xe(u=>u.removeChat),a=xe(u=>u.setActiveChat),[i,o]=K.useState(new Set),s=K.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=K.useCallback(u=>i.has(u),[i]);return{deleteChat:s,isDeleting:l}},W_e=({initialSystemPrompt:e,composerFormRef:t})=>{const n=nt(),{composer:r,contextKey:a,activeChatId:i,draftChatKey:o,queuedMessages:s,activeChatStatus:l,upsertChat:u,setChatStatus:d,setActiveChat:p,setComposerError:m,moveChatKeyState:h,removeQueuedMessage:f,setPendingAssistant:y,enqueueQueuedMessage:w,appendMessagesToChat:_,commitPendingAssistant:k,setPageContextDismissed:v}=xe(P=>{const D=P.activeChatId??P.draftChatKey,Y=et(P,D);return{composer:P.composer,contextKey:P.contextKey,activeChatId:P.activeChatId,draftChatKey:P.draftChatKey,queuedMessages:Y.messageQueue,activeChatStatus:Y.status,upsertChat:P.upsertChat,setActiveChat:P.setActiveChat,setChatStatus:P.setChatStatus,setComposerError:P.setComposerError,moveChatKeyState:P.moveChatKeyState,setPendingAssistant:P.setPendingAssistant,removeQueuedMessage:P.removeQueuedMessage,enqueueQueuedMessage:P.enqueueQueuedMessage,appendMessagesToChat:P.appendMessagesToChat,commitPendingAssistant:P.commitPendingAssistant,setPageContextDismissed:P.setPageContextDismissed}}),M=K.useCallback(P=>!P||P.length===0?!1:P.some(D=>D.type===exports.AgentAttachmentType.Context&&D?.metadata?.kind==="pageContext"),[]),S=K.useRef(!1),x=K.useRef(!1),$=K.useRef(void 0),H=K.useRef(new Set),C=i??o,L=K.useCallback(async(P,D)=>{if(!n.transport.generateTitle)return;const Y=n.config.features?.titleGeneration==="llm"?"llm":"local";let A;try{A=await n.transport.generateTitle({userId:D,content:P,strategy:Y,contextKey:a})}catch{}return A},[n.transport,n.config.features?.titleGeneration,a]),W=K.useCallback(async(P,D)=>{const Y=n.config.user?.id??"guest",A=!i,J=i??o,te={current:J};$.current=J;const O={value:P,attachments:D??[]};m(te.current,void 0);let de;if(A){const we=await L(P,Y);we&&we.trim().length>0&&(de={...de??{},title:we})}const ke=(i?n.store.getState().chats[i]:void 0)?.model,Oe=r.model!==ke;let ze,He=!1;Oe?(ze=r.model,He=!0):ke?(ze=ke,He=!1):(ze=void 0,He=!1);const re={userId:Y,content:P,metadata:de,contextKey:a,...A?{}:{chatId:i},...He?{model:ze??""}:{},...D&&D.length>0?{attachments:D}:{}},Ee=()=>{y(te.current,void 0)},Qe=we=>{if(we?.name==="AbortError"){const Ne=$.current??te.current;return H.current.has(Ne)?(k(te.current),H.current.delete(Ne)):(Ee(),t.current.setDraft(O)),{type:"aborted"}}throw we},Je=async()=>{let we=`pending-${Date.now()}`,Ne="",ve;d(te.current,Cn.Streaming),y(te.current,{id:we,content:"",reasoning:"",toolCalls:[],attachments:[],chat:i||"",role:exports.MessageRole.Assistant,createdAt:new Date().toISOString()});try{let Be=i;const pe=await n.transport.streamMessage(re,Re=>{if(Re.type===exports.StreamChunkType.Chat&&Re.chat){u(Re.chat),Be=Re.chat.id,A&&($.current=Re.chat.id,h(te.current,Re.chat.id),te.current=Re.chat.id,p(Re.chat.id));return}if(Re.type===exports.StreamChunkType.Reasoning&&Re.reasoning){Ne+=Re.reasoning,ve={...ve??{id:we,chat:Be,role:exports.MessageRole.Assistant,content:"",createdAt:new Date().toISOString()},reasoning:Ne},y(te.current,ve);return}if(Re.type===exports.StreamChunkType.Error&&Re.error)throw new Error(Re.error);Re.message&&Re.message.role===exports.MessageRole.User||Re.message&&(we=Re.message.id,ve={...Re.message,reasoning:Ne||Re.message.reasoning},y(te.current,ve))},{streamKey:$.current});if(pe){const Re=pe.messages.map(_e=>_e.id===ve.id&&_e.role===exports.MessageRole.Assistant?{..._e,reasoning:Ne}:_e);_(pe.id,Re);const rt=n.store.getState();return(rt.activeChatId??rt.draftChatKey)===te.current&&p(pe.id),Ee(),{type:"success"}}return Ee(),{type:"success"}}catch(Be){return Qe(Be)}};try{const we=await Je();return we.type==="success"&&(S.current=!1),we}catch(we){Ee();const Ne=we?.chat;Ne&&(u(Ne),p(Ne.id));const ve=we instanceof Error?we:new Error("Failed to send message");return m(te.current,ve.message||"Failed to send message"),t.current.setDraft(O),S.current=!1,{type:"error",error:ve}}finally{x.current=!1,d(te.current,Cn.Idle),$.current=void 0}},[i,a,r.model,n.transport,n.config.user?.id,u,p,y,d,L,e,h,t,m]),Z=K.useCallback(async()=>{if(l!==Cn.Idle||x.current||!s.length||S.current)return;const P=s[0];x.current=!0,f(C,P.id);try{await W(P.content,P.attachments)}finally{x.current=!1}},[l,s,C,W,f]);K.useEffect(()=>{Z()},[Z]);const ee=K.useCallback(async P=>{if(x.current)return;const D=s.find(Y=>Y.id===P);if(D){S.current=!1,x.current=!0,f(C,P);try{await W(D.content,D.attachments)}finally{x.current=!1}}},[s,C,f,W]),G=K.useCallback(async P=>{const Y=t.current.getDraft().attachments;if(M(Y)&&v(C,!0),l!==Cn.Idle){w(C,P,Y),t.current.clearDraft();return}S.current=!1,t.current.clearDraft(),await W(P,Y)},[l,w,C,W,t,M,v]),R=K.useCallback(()=>{S.current=!0;const P=$.current??C;H.current.add(P),n.transport.cancelStream?.(P),k(P),d(P,Cn.Idle)},[C,n.transport,k,d]),B=K.useCallback(async P=>{l===Cn.Streaming&&R(),await ee(P)},[l,R,ee]);return{pendingKey:C,queuedMessages:s,activeChatStatus:l,activeChatId:i,removeQueuedMessage:f,handleSubmit:G,handleStop:R,handleQueuedClick:B}},K_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(mo,{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(Xd,{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(T5,{size:12})})]})]},r.id))})]}):null;function Y_e(e,t){return e.size>t.maxFileSize?{type:"size",message:`File "${e.name}" exceeds maximum size of ${xp(t.maxFileSize)}`,fileName:e.name}:null}function Z_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=Y_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 ${xp(n.maxTotalAttachmentsSize)}`}:null}function xp(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 X_e(){return{maxFileSize:10*1024*1024,maxTotalAttachmentsSize:50*1024*1024,maxFilesPerMessage:10,allowedMimeTypes:void 0}}const K3=e=>{switch(e.type){case exports.AgentAttachmentType.Link:return N.jsx(M5,{size:12});case exports.AgentAttachmentType.Artifact:return N.jsx(mo,{size:12});case exports.AgentAttachmentType.Context:switch(e?.metadata?.kind){case"pageContext":return N.jsx(Qd,{size:12});case"formSnapshot":case"formField":return N.jsx(E5,{size:12});default:return N.jsx(Jd,{size:12})}case exports.AgentAttachmentType.File:default:return N.jsx(x5,{size:12})}},Q_e=({attachments:e})=>!e||e.length===0?null:N.jsx("div",{className:"mp-agent-message-attachments","aria-label":"Message attachments",children:e.map(t=>{const n=N.jsxs(N.Fragment,{children:[N.jsx("span",{className:"mp-agent-message-attachment-icon",children:K3(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:n},t.id):N.jsx("span",{className:"mp-agent-message-attachment",title:t.mimeType??t.name,children:n},t.id)})}),J_e=({attachments:e,onRemove:t,uploadProgress:n,uploadErrors:r})=>{const a=yn();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?` (${xp(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:K3(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(xn,{size:"sm",icon:"X",type:"button",onClick:d=>{d.preventDefault(),d.stopPropagation(),t(i.id)},"aria-label":`Remove attachment ${i.name}`}):null]},i.id)})})},ewe=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)},twe=e=>{try{const t=new URL(e);return t.hostname+(t.pathname&&t.pathname!=="/"?t.pathname:"")}catch{return e}},xd="mp-agent:locationchange",I2="__mp_agent_history_patched__",O2=()=>{try{window.dispatchEvent(new Event(xd))}catch{}},nwe=()=>{if(typeof window>"u")return;const e=window;if(!e[I2]){e[I2]=!0;try{const t=history.pushState;history.pushState=function(...n){const r=t.apply(this,n);return O2(),r}}catch{}try{const t=history.replaceState;history.replaceState=function(...n){const r=t.apply(this,n);return O2(),r}}catch{}}},rwe=e=>{if(typeof window>"u")return()=>{};nwe();const t=()=>e();return window.addEventListener("popstate",t),window.addEventListener("hashchange",t),window.addEventListener(xd,t),()=>{window.removeEventListener("popstate",t),window.removeEventListener("hashchange",t),window.removeEventListener(xd,t)}};async function awe(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 iwe(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 owe(e,t,n){const r=Rt.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 awe(e,n.chatId,n.userId,t);return await iwe(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 swe(e,t,n){const r=await Promise.allSettled(e.map(o=>owe(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 lwe=({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]=K.useState(!1),[h,f]=K.useState(null),[y,w]=K.useState(""),_=K.useRef([]),k=K.useRef(null),{refs:v,floatingStyles:M,context:S,isPositioned:x}=dp({open:p,onOpenChange:m,placement:s,strategy:"absolute",whileElementsMounted:ip,middleware:[op(8),lp({fallbackPlacements:["top-start","bottom-start","top-end","bottom-end"]}),sp({padding:8})]}),$=a3(S,{enabled:!a}),H=up(S),C=hp(S),W=S7e(S,{listRef:_,activeIndex:h,onNavigate:f,enabled:p&&!l,virtual:!1}),{getReferenceProps:Z,getFloatingProps:ee,getItemProps:G}=pp(l?[$,H,C]:[$,H,C,W]),R=e.findIndex(J=>J.value===t),B=R>=0?e[R]:void 0,P=K.useMemo(()=>{const J=y.trim().toLowerCase();if(!l||!J)return e;const O=d?de=>d(de,J):de=>`${de.label} ${de.description??""}`.toLowerCase().includes(J);return e.filter(O)},[e,y,l,d]);K.useEffect(()=>{if(!p){f(null),w("");return}l&&setTimeout(()=>k.current?.focus(),0);const J=P.findIndex(te=>te.value===t);f(J>=0?J:0)},[p,l,t,P]),K.useEffect(()=>{p&&f(P.length>0?0:null)},[y,P.length,p]);const D=J=>P.length===0?null:J<0?P.length-1:J>=P.length?0:J,Y=J=>{J!=null&&_.current[J]?.scrollIntoView({block:"nearest"})},A=J=>{n(J),m(!1),f(null),w("")};return N.jsxs("div",{className:`mp-agent-dropdown ${i}`,children:[N.jsxs("button",{ref:v.setReference,type:"button",className:`mp-agent-dropdown-trigger ${o}`,disabled:a,"aria-expanded":p,"aria-haspopup":"listbox",...Z(),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(w5,{size:16,className:`mp-agent-dropdown-chevron ${p?"open":""}`})]}),p&&N.jsxs("div",{role:"listbox",ref:v.setFloating,style:{...M,opacity:x?1:0,pointerEvents:x?"auto":"none",transition:x?"opacity 0.15s ease-out":"none"},className:"mp-agent-dropdown-menu",...ee(),children:[l&&N.jsx("div",{className:"mp-agent-dropdown-search",onKeyDown:J=>J.stopPropagation(),children:N.jsx("input",{ref:k,className:"mp-agent-dropdown-search-input",value:y,placeholder:u,onChange:J=>w(J.target.value),onKeyDown:J=>{if(J.key==="Escape"){J.preventDefault(),m(!1),w("");return}if(J.key==="ArrowDown"||J.key==="ArrowUp"){J.preventDefault();const te=J.key==="ArrowDown"?1:-1,O=h??(te>0?-1:0),de=D(O+te);f(de),Y(de);return}if(J.key==="Enter"){if(h==null)return;const te=P[h];if(!te)return;J.preventDefault(),A(te.value)}}})}),N.jsxs("div",{className:"mp-agent-dropdown-list",children:[P.map((J,te)=>N.jsxs("button",{ref:O=>{_.current[te]=O},type:"button",className:`mp-agent-dropdown-item ${t===J.value?"selected":""} ${h===te?"active":""}`,role:"option","aria-selected":t===J.value,...G({onClick:()=>A(J.value),onMouseEnter:()=>{f(te)},onKeyDown:O=>{(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),A(J.value))}}),children:[J.icon&&N.jsx("span",{className:"mp-agent-dropdown-item-icon",children:J.icon}),N.jsxs("span",{className:"mp-agent-dropdown-item-content",children:[N.jsx("span",{className:"mp-agent-dropdown-item-label",children:J.label}),J.description&&N.jsx("span",{className:"mp-agent-dropdown-item-description",children:J.description})]})]},J.value)),l&&P.length===0&&N.jsx("div",{className:"mp-agent-dropdown-empty","aria-label":"No results",children:"No results"})]})]})]})},cwe=K.memo(()=>{const e=nt(),t=xe(p=>p.composer),n=xe(p=>p.contextKey),r=xe(p=>p.setComposerOptions),a=e.config.models,{data:i,isLoading:o}=P3(),s=K.useMemo(()=>{const p=i&&i.length>0?i:a;return f3(p,e.config.transport).filter(h=>!h.contexts?.length||h.contexts.includes(n))},[i,a,e.config.transport,n]),l=K.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:ka,label:"Auto"},...p]},[s]),u=K.useMemo(()=>t.model!==void 0?t.model:ka,[t.model]),d=K.useCallback(p=>{p===ka?(r({model:void 0}),M2(e.config.transport,ka)):(r({model:p}),M2(e.config.transport,p))},[r,e.config.transport]);return o&&!a?.length||l.length===0?null:N.jsx(lwe,{options:l,value:u,onChange:d,placeholder:"Select model...",searchable:!0,searchPlaceholder:"Search models...",placement:"top-start",triggerClassName:"mp-agent-model-selector-trigger"})}),uwe=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):""},dwe=({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"})})},L2=e=>e.reduce((t,n)=>(t[n.agentName]={...n.tools},t),{}),Y3=({preferences:e,disabled:t})=>{const n=yn(),{upsertSingle:r}=H3(),[a,i]=K.useState(()=>L2(e)),[o,s]=K.useState({});K.useEffect(()=>{i(L2(e))},[e]);const l=r.error?.message,u=K.useMemo(()=>e.some(p=>Object.keys(p.tools).length>0),[e]),d=(p,m,h)=>{i(f=>{const y=f[p]??{},w=y,_={...y,[m]:h},k={...f,[p]:_};return s(v=>({...v,[p]:{...v[p]??{},[m]:!0}})),r.mutate({agentName:p,input:{tools:_}},{onError:()=>{i(v=>({...v,[p]:w}))},onSettled:()=>{s(v=>{const M={...v[p]??{}};if(delete M[m],Object.keys(M).length===0){const{[p]:S,...x}=v;return x}return{...v,[p]:M}})}}),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(([f,y])=>{const w=!!o[p.agentName]?.[f];return N.jsxs("label",{className:"mp-agent-preferences-tool",children:[N.jsx("span",{className:"mp-agent-preferences-tool-label",children:uwe(f)}),N.jsx(dwe,{checked:y,onChange:_=>d(p.agentName,f,_),disabled:!!t||w})]},`${p.agentName}:${f}`)})})]},p.agentName)}),l&&N.jsx("div",{className:"mp-agent-preferences-error",children:l})]})};function pwe(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 hwe=()=>{const e=yn(),t=nt(),n=xe(l=>l.contextKey),{data:r,isLoading:a,isError:i}=B3(n),o=K.useMemo(()=>pwe(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(Y3,{preferences:o,disabled:!s})},mwe=()=>{const[e,t]=K.useState(!1),n=yn(),{refs:r,floatingStyles:a,context:i,isPositioned:o}=dp({open:e,onOpenChange:t,placement:"top-start",strategy:"absolute",whileElementsMounted:ip,middleware:[op(8),lp({fallbackPlacements:["bottom-start","top-end","bottom-end"]}),sp({padding:8})]}),s=a3(i),l=up(i),u=hp(i),{getReferenceProps:d,getFloatingProps:p}=pp([s,l,u]);return N.jsxs("div",{className:"mp-agent-tool-config-dropdown",children:[N.jsx(Wn,{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(S5,{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(hwe,{})})]})},fwe=K.forwardRef(({autoFocus:e,activeChatId:t,status:n,onStop:r,onSubmit:a},i)=>{const o=yn(),s=nt(),l=K.useRef(null),u=K.useRef(null),d=xe(re=>re.activeChatId??re.draftChatKey),p=xe(re=>et(re,d).composerDraft),m=xe(re=>et(re,d).composerError),h=xe(re=>et(re,d).pageContextDismissed),f=xe(re=>re.setComposerValue),y=xe(re=>re.setComposerDraft),w=xe(re=>re.clearComposerDraft),_=xe(re=>re.setComposerError),k=xe(re=>re.addComposerAttachments),v=xe(re=>re.removeComposerAttachment),M=xe(re=>re.setPageContextDismissed),S=p.value,x=p.attachments,[$,H]=K.useState(new Map),[C,L]=K.useState(new Map),W=K.useRef(S),Z=K.useRef(x),ee=K.useRef(h),G=s.config.features?.pageContextAttachments!==!1,R=re=>re.type===exports.AgentAttachmentType.Context&&re?.metadata?.kind==="pageContext",B=x.some(R),P=()=>{if(G)return s.buildPageContextAttachment()};K.useEffect(()=>{Z.current=x},[x]),K.useEffect(()=>{W.current=S},[S]),K.useEffect(()=>{ee.current=h},[h]),K.useEffect(()=>{if(!G||h||B)return;const re=P();re&&k(d,[re])},[G,h,B,d,k]),K.useEffect(()=>{if(G&&!(typeof window>"u"))return rwe(()=>{if(ee.current)return;const re=Z.current,Ee=re.find(R);if(!Ee)return;const Qe=P();if(!Qe)return;const Je={...Qe,id:Ee.id},we=re.map(Ne=>Ne.id===Ee.id?Je:Ne);y(d,{value:W.current,attachments:we})})},[G,d,y]),K.useImperativeHandle(i,()=>({setValue:re=>{f(d,re)},getDraft:()=>({value:S,attachments:x}),setDraft:re=>{y(d,{value:re.value,attachments:re.attachments??[]})},clearDraft:()=>{w(d)}})),K.useEffect(()=>{const re=l.current;re&&(re.style.height="auto",re.style.height=`${Math.min(re.scrollHeight,200)}px`)},[S]);const D=async re=>{if(!re||re.length===0)return;const Ee=Array.from(re),Qe=X_e(),Je=Z_e(Ee,x,Qe);if(Je){L(we=>{const Ne=new Map(we);return Ee.forEach(ve=>{Ne.set(ve.name,Je.message)}),Ne});return}L(we=>{const Ne=new Map(we);return Ee.forEach(ve=>Ne.delete(ve.name)),Ne});try{const we=s.config.transport;if(we.mode!=="proxy")throw new Error("File uploads are only supported with proxy transport");const Ne={presignedUrlEndpoint:`${we.baseUrl}/files/upload/presigned`,getAuthHeaders:()=>{const Be={};return we.headers?we.headers:(we.apiKey&&(Be.Authorization=`Bearer ${we.apiKey}`),Be)}},ve=await swe(Ee,Ne,{chatId:t,userId:s.config.user?.id,onProgress:Be=>{H(pe=>{const Re=new Map(pe);return Re.set(Be.fileId,Be),Re})}});k(d,ve),setTimeout(()=>{H(Be=>{const pe=new Map(Be);return ve.forEach(Re=>pe.delete(Re.id)),pe})},2e3)}catch(we){const Ne=we instanceof Error?we.message:"Failed to upload files";L(ve=>{const Be=new Map(ve);return Ee.forEach(pe=>{Be.set(pe.name,Ne)}),Be})}},Y=()=>{u.current?.click()},A=re=>{const Ee=ewe(re);if(!Ee)return!1;if(x.some(we=>we.type===exports.AgentAttachmentType.Link&&we.url===Ee))return!0;const Qe=twe(Ee),Je={id:Rt.nanoid(),url:Ee,name:Qe,type:exports.AgentAttachmentType.Link};return k(d,[Je]),!0},J=async re=>{await D(re.target.files),re.target.value=""},te=re=>{const Ee=x.find(Qe=>Qe.id===re);Ee&&R(Ee)&&M(d,!0),v(d,re)},O=()=>{if(typeof window>"u"||typeof document>"u")return!1;const re=l3(),Ee=re?.selectedText??window.getSelection?.()?.toString()?.trim()??"";if(!Ee)return!1;const Qe=window.location?.href,Je=Ee.slice(0,20),we=Ee.length>20?Je+"...":Ee,Ne=So({kind:"webSnippet",url:Qe,title:we,selectedText:Ee,source:{app:"browser",url:Qe},...re?.target?{target:re.target}:{}});return k(d,[Ne]),!0},de=re=>{re.preventDefault();const Ee=S.trim();Ee&&(_(d,void 0),a(Ee))},ye=re=>{re.key==="Enter"&&!re.shiftKey&&(re.preventDefault(),de(re))},ke=re=>{m&&_(d,void 0),f(d,re.target.value)},Oe=re=>{if(re.nativeEvent.shiftKey)return;const Ee=re.clipboardData?.getData("text/plain")??"";if(!Ee)return;A(Ee)&&re.preventDefault()},He=!!S.trim();return N.jsxs(N.Fragment,{children:[N.jsxs("form",{onSubmit:de,className:"mp-agent-composer-input-wrapper",children:[N.jsx("input",{ref:u,type:"file",multiple:!0,style:{display:"none"},onChange:J}),N.jsx(J_e,{attachments:x,onRemove:te,uploadProgress:$,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:ye,onPaste:Oe})]}),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(cwe,{}),s.config.features?.toolConfiguration&&N.jsx(mwe,{}),N.jsx(Wn,{content:o.attachFiles,children:N.jsx("button",{type:"button",className:"mp-agent-composer-button mp-agent-composer-tool-button",onClick:Y,"aria-label":o.attachFiles,children:N.jsx(mo,{size:16})})}),N.jsx(Wn,{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(Jd,{size:16})})}),G&&!B&&N.jsx(Wn,{content:"Attach page context",children:N.jsx("button",{type:"button",className:"mp-agent-composer-button mp-agent-composer-tool-button",onClick:()=>{M(d,!1);const re=P();re&&k(d,[re])},"aria-label":"Attach page context",children:N.jsx(Qd,{size:16})})})]}),N.jsx("div",{className:"mp-agent-composer-actions-right",children:n===Cn.Streaming&&!He?N.jsx(Wn,{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(A5,{size:12})})}):N.jsx(Wn,{content:He?o.sendMessage:o.typeMessageToSend,children:N.jsx("button",{type:"submit",disabled:!He,"aria-label":o.sendMessage,className:"mp-agent-composer-button mp-agent-composer-send-button",children:N.jsx(Xd,{size:16})})})})]})]})}),Z3=({autoFocus:e})=>{const t=K.useRef({setValue:()=>{},getDraft:()=>({value:"",attachments:[]}),setDraft:()=>{},clearDraft:()=>{}}),{pendingKey:n,queuedMessages:r,activeChatStatus:a,activeChatId:i,handleSubmit:o,handleStop:s,handleQueuedClick:l,removeQueuedMessage:u}=W_e({composerFormRef:t});return N.jsx("div",{className:"mp-agent-composer-wrapper",children:N.jsxs("div",{className:"mp-agent-composer",children:[N.jsx(K_e,{queuedMessages:r,onSendQueued:l,onRemoveQueued:d=>u(n,d)}),N.jsx(fwe,{status:a,ref:t,autoFocus:e,activeChatId:i,onStop:s,onSubmit:o})]})})},X3=K.memo(()=>{const e=xe(n=>n.activeChatId??n.draftChatKey),t=xe(n=>et(n,e).composerError);return t?N.jsx("div",{className:"mp-agent-composer-error",children:t}):null});X3.displayName="ComposerError";const gwe=(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}...`}},ys=e=>{if(e===void 0)return"undefined";try{return JSON.stringify(e,null,2)??"undefined"}catch{try{return String(e)}catch{return"[unserializable]"}}},D2=({call:e})=>nt().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:ys(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:ys(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:ys(e.error)})})]})]})]}):null,ywe=({call:e})=>{const t=nt();if(!t.config.debug)return null;const r=t.tools.get(e.name)?.label??e.name,a=gwe(e,r);return N.jsx("div",{className:"mp-agent-tool-header",children:N.jsx("div",{className:"mp-agent-tool-simple-message",children:a})})},Q3=({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"})}),bwe=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}},kwe=({callId:e,input:t,isSubmitting:n,onSubmit:r})=>{const[a,i]=K.useState([]),[o,s]=K.useState(""),[l,u]=K.useState(void 0),d=K.useMemo(()=>bwe(t),[t]);K.useEffect(()=>{i([]),s(""),u(void 0)},[e,t]);const p=h=>{if(d){if(u(void 0),d.selectionMode==="single"){i([h]);return}i(f=>f.includes(h)?f.filter(y=>y!==h):[...f,h])}},m=async()=>{if(!d)return;const h=o.trim(),f=a.length>0,y=d.allowFreeText&&h.length>0;if(!f&&!y){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:v,description:M})=>({id:k,label:v,...M?{description:M}:{}})),_={question:d.question,selectionMode:d.selectionMode,selectedOptionIds:a,selectedOptions:w,...h?{freeText:h}:{}};await r(JSON.stringify(_))};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 f=`${e}-${h.id}`,y=a.includes(h.id);return N.jsxs("label",{htmlFor:f,className:"mp-agent-tool-user-action-option",children:[N.jsx("input",{id:f,type:d.selectionMode==="single"?"radio":"checkbox",name:`mp-agent-tool-user-action-${e}`,checked:y,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."})})},vwe=({call:e,messageId:t,chatId:n,onApprovalSent:r})=>{const a=nt(),i=xe(x=>x.appendMessagesToChat),[o,s]=K.useState(!1),[l,u]=K.useState(!1),[d,p]=K.useState(!1),[m,h]=K.useState(JSON.stringify(e.input??{},null,2)),[f,y]=K.useState(void 0),w=a.config.user?.id??"guest",_=e.requiresUserAction;K.useEffect(()=>{l||(h(JSON.stringify(e.input??{},null,2)),y(void 0))},[e.id,e.input,l]);const k=()=>{h(JSON.stringify(e.input??{},null,2)),y(void 0),u(!0)},v=()=>{h(JSON.stringify(e.input??{},null,2)),y(void 0),u(!1)},M=async()=>{if(!(!a.transport.updateToolCall||d||o)){y(void 0),p(!0);try{const x=JSON.parse(m);if(!x||typeof x!="object"||Array.isArray(x))throw new Error("Tool input must be a JSON object.");const $=await a.transport.updateToolCall({chatId:n,messageId:t,toolCallId:e.id,input:x});i(n,[$]),u(!1)}catch(x){y(x instanceof Error?x.message:"Failed to update tool input.")}finally{p(!1)}}},S=async(x,$)=>{if(!(!e.approvalId||o||d||l)){s(!0);try{const H={chatId:n,messageId:t,approvalId:e.approvalId,approved:x,...$?{userResponse:$}:{},userId:w},C=await a.transport.streamMessage(H,L=>{L.type===exports.StreamChunkType.Message&&L.message&&i(n,[L.message])},{streamKey:n});C?i(C.id,C.messages):r()}catch(H){console.error("Failed to send approval:",H)}finally{s(!1)}}};return e.approved!==void 0?N.jsx(Q3,{call:e}):_?N.jsx(kwe,{callId:e.id,input:e.input,isSubmitting:o,onSubmit:x=>S(!0,x)}):N.jsxs("div",{className:"mp-agent-tool-approval-buttons",children:[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"}),l?N.jsxs("div",{className:"mp-agent-tool-input-actions",children:[N.jsx(xn,{icon:"Check",size:"sm",tooltip:"Save tool input",onClick:M,disabled:d||o,"aria-label":"Save tool input"}),N.jsx(xn,{icon:"X",size:"sm",tooltip:"Cancel input edit",onClick:v,disabled:d||o,"aria-label":"Cancel tool input edit"})]}):N.jsx(xn,{icon:"Pencil",size:"sm",tooltip:"Edit tool input",onClick:k,disabled:o||d,"aria-label":"Edit tool input"})]}),l?N.jsx("textarea",{className:"mp-agent-tool-input-editor",value:m,onChange:x=>{h(x.target.value),f&&y(void 0)},rows:8,spellCheck:!1,disabled:d||o}):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:()=>S(!0),disabled:o||l||d,children:o?"Processing...":"Approve"}),N.jsx("button",{className:"mp-agent-tool-deny-button",onClick:()=>S(!1),disabled:o||d,children:o?"Processing...":"Deny"})]})]})},z2=({call:e,messageId:t,chatId:n})=>{const r=nt(),a=xe(l=>l.upsertChat),i=e.requiresConfirmation&&e.approvalId&&e.approved===void 0,o=e.requiresConfirmation&&e.approvalId&&e.approved!==void 0,s=async()=>{try{const l=await r.transport.getChat(n);a(l)}catch(l){console.error("Failed to refresh chat after approval:",l)}};return!i&&!o?null:N.jsxs("div",{className:"mp-agent-tool-approval",children:[i&&N.jsx(vwe,{call:e,messageId:t,chatId:n,onApprovalSent:s}),o&&N.jsx(Q3,{call:e})]})},_we=({call:e,contextKey:t,messageId:n,chatId:r})=>{const a=nt(),i=K.useMemo(()=>a.getToolRenderer(e),[a,e]);return i?N.jsxs("div",{className:"mp-agent-tool-panel",children:[N.jsx(i,{call:e,contextKey:t,chatId:r}),N.jsx(z2,{call:e,messageId:n,chatId:r}),N.jsx(D2,{call:e})]}):N.jsxs("div",{className:"mp-agent-tool-panel",children:[N.jsx(ywe,{call:e}),N.jsx(z2,{call:e,messageId:n,chatId:r}),N.jsx(D2,{call:e})]})},J3=K.memo(({role:e,isGrouped:t})=>{if(t)return N.jsx("div",{className:"mp-agent-message-avatar-spacer"});const n=e===exports.MessageRole.User,r=n?"You":"AI";return N.jsx("div",{className:`mp-agent-message-avatar ${n?"mp-agent-message-avatar-user":""}`,children:N.jsx("div",{className:"mp-agent-message-avatar-icon",children:r})})});J3.displayName="MessageAvatar";const wwe=e=>e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"}):"",ev=K.memo(({role:e,createdAt:t,isGrouped:n})=>{if(n)return null;const a=e===exports.MessageRole.User?"You":"Assistant";return N.jsxs("div",{className:"mp-agent-message-header",children:[N.jsx("span",{className:"mp-agent-message-role",children:a}),N.jsx("span",{className:"mp-agent-message-time",children:wwe(t)})]})});ev.displayName="MessageHeader";function $2(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 xwe(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const Ewe=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Mwe=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Swe={};function F2(e,t){return(Swe.jsx?Mwe:Ewe).test(e)}const Nwe=/[ \t\n\f\r]/g;function Awe(e){return typeof e=="object"?e.type==="text"?P2(e.value):!1:P2(e)}function P2(e){return e.replace(Nwe,"")===""}let Ka=class{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}};Ka.prototype.normal={};Ka.prototype.property={};Ka.prototype.space=void 0;function tv(e,t){const n={},r={};for(const a of e)Object.assign(n,a.property),Object.assign(r,a.normal);return new Ka(n,r,t)}function Da(e){return e.toLowerCase()}let Yt=class{constructor(t,n){this.attribute=n,this.property=t}};Yt.prototype.attribute="";Yt.prototype.booleanish=!1;Yt.prototype.boolean=!1;Yt.prototype.commaOrSpaceSeparated=!1;Yt.prototype.commaSeparated=!1;Yt.prototype.defined=!1;Yt.prototype.mustUseProperty=!1;Yt.prototype.number=!1;Yt.prototype.overloadedBoolean=!1;Yt.prototype.property="";Yt.prototype.spaceSeparated=!1;Yt.prototype.space=void 0;let Twe=0;const $e=Ir(),kt=Ir(),Ed=Ir(),ce=Ir(),st=Ir(),Jr=Ir(),Jt=Ir();function Ir(){return 2**++Twe}const Md=Object.freeze(Object.defineProperty({__proto__:null,boolean:$e,booleanish:kt,commaOrSpaceSeparated:Jt,commaSeparated:Jr,number:ce,overloadedBoolean:Ed,spaceSeparated:st},Symbol.toStringTag,{value:"Module"})),bs=Object.keys(Md);let Ep=class extends Yt{constructor(t,n,r,a){let i=-1;if(super(t,n),q2(this,"space",a),typeof r=="number")for(;++i<bs.length;){const o=bs[i];q2(this,bs[i],(r&Md[o])===Md[o])}}};Ep.prototype.defined=!0;function q2(e,t,n){n&&(e[t]=n)}function sa(e){const t={},n={};for(const[r,a]of Object.entries(e.properties)){const i=new Ep(r,e.transform(e.attributes||{},r),a,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(i.mustUseProperty=!0),t[r]=i,n[Da(r)]=r,n[Da(i.attribute)]=r}return new Ka(t,n,e.space)}const nv=sa({properties:{ariaActiveDescendant:null,ariaAtomic:kt,ariaAutoComplete:null,ariaBusy:kt,ariaChecked:kt,ariaColCount:ce,ariaColIndex:ce,ariaColSpan:ce,ariaControls:st,ariaCurrent:null,ariaDescribedBy:st,ariaDetails:null,ariaDisabled:kt,ariaDropEffect:st,ariaErrorMessage:null,ariaExpanded:kt,ariaFlowTo:st,ariaGrabbed:kt,ariaHasPopup:null,ariaHidden:kt,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:st,ariaLevel:ce,ariaLive:null,ariaModal:kt,ariaMultiLine:kt,ariaMultiSelectable:kt,ariaOrientation:null,ariaOwns:st,ariaPlaceholder:null,ariaPosInSet:ce,ariaPressed:kt,ariaReadOnly:kt,ariaRelevant:null,ariaRequired:kt,ariaRoleDescription:st,ariaRowCount:ce,ariaRowIndex:ce,ariaRowSpan:ce,ariaSelected:kt,ariaSetSize:ce,ariaSort:null,ariaValueMax:ce,ariaValueMin:ce,ariaValueNow:ce,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function rv(e,t){return t in e?e[t]:t}function av(e,t){return rv(e,t.toLowerCase())}const Cwe=sa({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Jr,acceptCharset:st,accessKey:st,action:null,allow:null,allowFullScreen:$e,allowPaymentRequest:$e,allowUserMedia:$e,alt:null,as:null,async:$e,autoCapitalize:null,autoComplete:st,autoFocus:$e,autoPlay:$e,blocking:st,capture:null,charSet:null,checked:$e,cite:null,className:st,cols:ce,colSpan:null,content:null,contentEditable:kt,controls:$e,controlsList:st,coords:ce|Jr,crossOrigin:null,data:null,dateTime:null,decoding:null,default:$e,defer:$e,dir:null,dirName:null,disabled:$e,download:Ed,draggable:kt,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:$e,formTarget:null,headers:st,height:ce,hidden:Ed,high:ce,href:null,hrefLang:null,htmlFor:st,httpEquiv:st,id:null,imageSizes:null,imageSrcSet:null,inert:$e,inputMode:null,integrity:null,is:null,isMap:$e,itemId:null,itemProp:st,itemRef:st,itemScope:$e,itemType:st,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:$e,low:ce,manifest:null,max:null,maxLength:ce,media:null,method:null,min:null,minLength:ce,multiple:$e,muted:$e,name:null,nonce:null,noModule:$e,noValidate:$e,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:$e,optimum:ce,pattern:null,ping:st,placeholder:null,playsInline:$e,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:$e,referrerPolicy:null,rel:st,required:$e,reversed:$e,rows:ce,rowSpan:ce,sandbox:st,scope:null,scoped:$e,seamless:$e,selected:$e,shadowRootClonable:$e,shadowRootDelegatesFocus:$e,shadowRootMode:null,shape:null,size:ce,sizes:null,slot:null,span:ce,spellCheck:kt,src:null,srcDoc:null,srcLang:null,srcSet:null,start:ce,step:null,style:null,tabIndex:ce,target:null,title:null,translate:null,type:null,typeMustMatch:$e,useMap:null,value:kt,width:ce,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:st,axis:null,background:null,bgColor:null,border:ce,borderColor:null,bottomMargin:ce,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:$e,declare:$e,event:null,face:null,frame:null,frameBorder:null,hSpace:ce,leftMargin:ce,link:null,longDesc:null,lowSrc:null,marginHeight:ce,marginWidth:ce,noResize:$e,noHref:$e,noShade:$e,noWrap:$e,object:null,profile:null,prompt:null,rev:null,rightMargin:ce,rules:null,scheme:null,scrolling:kt,standby:null,summary:null,text:null,topMargin:ce,valueType:null,version:null,vAlign:null,vLink:null,vSpace:ce,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:$e,disableRemotePlayback:$e,prefix:null,property:null,results:ce,security:null,unselectable:null},space:"html",transform:av}),Rwe=sa({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:Jt,accentHeight:ce,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:ce,amplitude:ce,arabicForm:null,ascent:ce,attributeName:null,attributeType:null,azimuth:ce,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:ce,by:null,calcMode:null,capHeight:ce,className:st,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:ce,diffuseConstant:ce,direction:null,display:null,dur:null,divisor:ce,dominantBaseline:null,download:$e,dx:null,dy:null,edgeMode:null,editable:null,elevation:ce,enableBackground:null,end:null,event:null,exponent:ce,externalResourcesRequired:null,fill:null,fillOpacity:ce,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:Jr,g2:Jr,glyphName:Jr,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:ce,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:ce,horizOriginX:ce,horizOriginY:ce,id:null,ideographic:ce,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:ce,k:ce,k1:ce,k2:ce,k3:ce,k4:ce,kernelMatrix:Jt,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:ce,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:ce,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:ce,overlineThickness:ce,paintOrder:null,panose1:null,path:null,pathLength:ce,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:st,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:ce,pointsAtY:ce,pointsAtZ:ce,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Jt,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Jt,rev:Jt,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Jt,requiredFeatures:Jt,requiredFonts:Jt,requiredFormats:Jt,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:ce,specularExponent:ce,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:ce,strikethroughThickness:ce,string:null,stroke:null,strokeDashArray:Jt,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:ce,strokeOpacity:ce,strokeWidth:null,style:null,surfaceScale:ce,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Jt,tabIndex:ce,tableValues:null,target:null,targetX:ce,targetY:ce,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Jt,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:ce,underlineThickness:ce,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:ce,values:null,vAlphabetic:ce,vMathematical:ce,vectorEffect:null,vHanging:ce,vIdeographic:ce,version:null,vertAdvY:ce,vertOriginX:ce,vertOriginY:ce,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:ce,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:rv}),iv=sa({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()}}),ov=sa({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:av}),sv=sa({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),Iwe={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"},Owe=/[A-Z]/g,B2=/-[a-z]/g,Lwe=/^data[-\w.:]+$/i;function lv(e,t){const n=Da(t);let r=t,a=Yt;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&Lwe.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(B2,zwe);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!B2.test(i)){let o=i.replace(Owe,Dwe);o.charAt(0)!=="-"&&(o="-"+o),t="data"+o}}a=Ep}return new a(r,t)}function Dwe(e){return"-"+e.toLowerCase()}function zwe(e){return e.charAt(1).toUpperCase()}const cv=tv([nv,Cwe,iv,ov,sv],"html"),Ro=tv([nv,Rwe,iv,ov,sv],"svg");function U2(e){const t=String(e||"").trim();return t?t.split(/[ \t\n\r\f]+/g):[]}function $we(e){return e.join(" ").trim()}var Mp={},H2=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,Fwe=/\n/g,Pwe=/^\s*/,qwe=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,Bwe=/^:\s*/,Uwe=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,Hwe=/^[;\s]*/,jwe=/^\s+|\s+$/g,Vwe=`
|
|
8322
|
+
}`}),t]})},L7e=()=>K.useContext(d3),si=e=>e.type===exports.AgentAttachmentType.Context&&e?.metadata?.kind==="pageContext";var Cn=(e=>(e.Idle="idle",e.Sending="sending",e.Streaming="streaming",e))(Cn||{});const h3=()=>({messages:[],reasoning:[],artifacts:[],pendingAssistant:void 0,messageQueue:[],composerDraft:{value:"",attachments:[]},composerError:void 0,pageContextDismissed:!1,status:"idle"}),et=(e,t)=>e.chatState[t]??h3(),D7e=e=>h5.create()((t,n)=>({contextKey:e,activeChatId:void 0,draftChatKey:`draft-${Rt.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=et(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=et(i,r);return{chatState:{...i.chatState,[r]:{...o,reasoning:[...o.reasoning,a]}}}}),setArtifacts:(r,a)=>t(i=>{const o=et(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=et(i,r);return{chatState:{...i.chatState,[r]:{...o,composerDraft:{value:a.value??"",attachments:a.attachments??[]}}}}}),setComposerValue:(r,a)=>t(i=>{const o=et(i,r);return{chatState:{...i.chatState,[r]:{...o,composerDraft:{...o.composerDraft,value:a}}}}}),addComposerAttachments:(r,a)=>t(i=>{const o=et(i,r),s=o.composerDraft.attachments??[];if(!a||a.length===0)return i;const l=s.find(si),u=a.find(si);if(u){const m=a.filter(_=>!si(_)),h=s.filter(_=>!si(_)),y=[l?{...u,id:l.id}:u,...m,...h],w=new Map;for(const _ of y)w.set(_.id,_);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=et(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=et(a,r);return{chatState:{...a.chatState,[r]:{...i,composerDraft:{value:"",attachments:[]}}}}}),setComposerError:(r,a)=>t(i=>{const o=et(i,r);return{chatState:{...i.chatState,[r]:{...o,composerError:a}}}}),setPageContextDismissed:(r,a)=>t(i=>{const o=et(i,r);return{chatState:{...i.chatState,[r]:{...o,pageContextDismissed:a}}}}),setChatStatus:(r,a)=>t(i=>{const o=et(i,r);return{chatState:{...i.chatState,[r]:{...o,status:a}}}}),setPendingAssistant:(r,a)=>t(i=>{const o=et(i,r);return{chatState:{...i.chatState,[r]:{...o,pendingAssistant:a}}}}),commitPendingAssistant:r=>t(a=>{const i=et(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=et(o,r),l={id:Rt.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=et(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=et(i,r),s=et(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]:h3()}}}),appendSystemMessage:(r,a)=>t(i=>{const o=et(i,r),s={id:Rt.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=et(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=et(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=et(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}}}})})),E2="mp-agent-selected-model",ka="__auto__";function m3(e){return e.mode==="direct"?`${E2}-${e.mode}-${e.provider}`:`${E2}-${e.mode}`}function M2(e,t){try{const n=m3(e);localStorage.setItem(n,t)}catch(n){console.warn("Failed to save selected model to localStorage:",n)}}function z7e(e){try{const t=m3(e);return localStorage.getItem(t)}catch(t){return console.warn("Failed to load selected model from localStorage:",t),null}}function f3(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 $7e(e,t,n){const r=z7e(t);if(r){if(r===ka)return;if(f3(e,t).some(i=>i.id===r))return r}}const F7e="mp-agents-last-active-chat";function g3(e){return`${F7e}-${e}`}function y3(e){return typeof e=="string"&&e.length>0&&e.length<256}function P7e(e){if(typeof window>"u")return null;try{const t=localStorage.getItem(g3(e));return t&&y3(t)?t:null}catch{return null}}function q7e(e,t){if(!(typeof window>"u"))try{const n=g3(e);t&&y3(t)?localStorage.setItem(n,t):localStorage.removeItem(n)}catch{}}const S2="mp-agents-guest-user-id";function ta(){if(typeof window>"u")return`${Vi.DefaultUserId}-${Rt.nanoid()}`;const e=localStorage.getItem(S2);if(e)return e;const t=`${Vi.DefaultUserId}-${Rt.nanoid()}`;return localStorage.setItem(S2,t),t}const zn=Object.create(null);zn.open="0";zn.close="1";zn.ping="2";zn.pong="3";zn.message="4";zn.upgrade="5";zn.noop="6";const Di=Object.create(null);Object.keys(zn).forEach(e=>{Di[zn[e]]=e});const yd={type:"error",data:"parser error"},b3=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",k3=typeof ArrayBuffer=="function",v3=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,fp=({type:e,data:t},n,r)=>b3&&t instanceof Blob?n?r(t):N2(t,r):k3&&(t instanceof ArrayBuffer||v3(t))?n?r(t):N2(new Blob([t]),r):r(zn[e]+(t||"")),N2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function A2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let ms;function B7e(e,t){if(b3&&e.data instanceof Blob)return e.data.arrayBuffer().then(A2).then(t);if(k3&&(e.data instanceof ArrayBuffer||v3(e.data)))return t(A2(e.data));fp(e,!1,n=>{ms||(ms=new TextEncoder),t(ms.encode(n))})}const T2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",va=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<T2.length;e++)va[T2.charCodeAt(e)]=e;const U7e=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=va[e.charCodeAt(r)],o=va[e.charCodeAt(r+1)],s=va[e.charCodeAt(r+2)],l=va[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},H7e=typeof ArrayBuffer=="function",gp=(e,t)=>{if(typeof e!="string")return{type:"message",data:_3(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:j7e(e.substring(1),t)}:Di[n]?e.length>1?{type:Di[n],data:e.substring(1)}:{type:Di[n]}:yd},j7e=(e,t)=>{if(H7e){const n=U7e(e);return _3(n,t)}else return{base64:!0,data:e}},_3=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},w3="",V7e=(e,t)=>{const n=e.length,r=new Array(n);let a=0;e.forEach((i,o)=>{fp(i,!1,s=>{r[o]=s,++a===n&&t(r.join(w3))})})},G7e=(e,t)=>{const n=e.split(w3),r=[];for(let a=0;a<n.length;a++){const i=gp(n[a],t);if(r.push(i),i.type==="error")break}return r};function W7e(){return new TransformStream({transform(e,t){B7e(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 fs;function li(e){return e.reduce((t,n)=>t+n.length,0)}function ci(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 K7e(e,t){fs||(fs=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(li(n)<1)break;const l=ci(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(li(n)<2)break;const l=ci(n,2);a=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),r=3}else if(r===2){if(li(n)<8)break;const l=ci(n,8),u=new DataView(l.buffer,l.byteOffset,l.length),d=u.getUint32(0);if(d>Math.pow(2,21)-1){s.enqueue(yd);break}a=d*Math.pow(2,32)+u.getUint32(4),r=3}else{if(li(n)<a)break;const l=ci(n,a);s.enqueue(gp(i?l:fs.decode(l),t)),r=0}if(a===0||a>e){s.enqueue(yd);break}}}})}const x3=4;function vt(e){if(e)return Y7e(e)}function Y7e(e){for(var t in vt.prototype)e[t]=vt.prototype[t];return e}vt.prototype.on=vt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};vt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};vt.prototype.off=vt.prototype.removeListener=vt.prototype.removeAllListeners=vt.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};vt.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};vt.prototype.emitReserved=vt.prototype.emit;vt.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};vt.prototype.hasListeners=function(e){return!!this.listeners(e).length};const No=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),cn=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Z7e="arraybuffer";function E3(e,...t){return t.reduce((n,r)=>(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const X7e=cn.setTimeout,Q7e=cn.clearTimeout;function Ao(e,t){t.useNativeTimers?(e.setTimeoutFn=X7e.bind(cn),e.clearTimeoutFn=Q7e.bind(cn)):(e.setTimeoutFn=cn.setTimeout.bind(cn),e.clearTimeoutFn=cn.clearTimeout.bind(cn))}const J7e=1.33;function e_e(e){return typeof e=="string"?t_e(e):Math.ceil((e.byteLength||e.size)*J7e)}function t_e(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 M3(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function n_e(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function r_e(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 a_e extends Error{constructor(t,n,r){super(t),this.description=n,this.context=r,this.type="TransportError"}}class yp extends vt{constructor(t){super(),this.writable=!1,Ao(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 a_e(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=gp(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=n_e(t);return n.length?"?"+n:""}}class i_e extends yp{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)};G7e(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,V7e(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]=M3()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}}let S3=!1;try{S3=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const o_e=S3;function s_e(){}class l_e extends i_e{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 Dn extends vt{constructor(t,n,r){super(),this.createRequest=t,Ao(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=E3(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=Dn.requestsCount++,Dn.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=s_e,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Dn.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()}}Dn.requestsCount=0;Dn.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",C2);else if(typeof addEventListener=="function"){const e="onpagehide"in cn?"pagehide":"unload";addEventListener(e,C2,!1)}}function C2(){for(let e in Dn.requests)Dn.requests.hasOwnProperty(e)&&Dn.requests[e].abort()}const c_e=function(){const e=N3({xdomain:!1});return e&&e.responseType!==null}();class u_e extends l_e{constructor(t){super(t);const n=t&&t.forceBase64;this.supportsBinary=c_e&&!n}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Dn(N3,this.uri(),t)}}function N3(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||o_e))return new XMLHttpRequest}catch{}if(!t)try{return new cn[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const A3=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class d_e extends yp{get name(){return"websocket"}doOpen(){const t=this.uri(),n=this.opts.protocols,r=A3?{}:E3(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;fp(r,this.supportsBinary,i=>{try{this.doWrite(r,i)}catch{}a&&No(()=>{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]=M3()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}}const gs=cn.WebSocket||cn.MozWebSocket;class p_e extends d_e{createSocket(t,n,r){return A3?new gs(t,n,r):n?new gs(t,n):new gs(t)}doWrite(t,n){this.ws.send(n)}}class h_e extends yp{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=K7e(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),a=W7e();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&&No(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const m_e={websocket:p_e,webtransport:h_e,polling:u_e},f_e=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,g_e=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function bd(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=f_e.exec(e||""),i={},o=14;for(;o--;)i[g_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=y_e(i,i.path),i.queryKey=b_e(i,i.query),i}function y_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 b_e(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,a,i){a&&(n[a]=i)}),n}const kd=typeof addEventListener=="function"&&typeof removeEventListener=="function",zi=[];kd&&addEventListener("offline",()=>{zi.forEach(e=>e())},!1);class pr extends vt{constructor(t,n){if(super(),this.binaryType=Z7e,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=bd(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=bd(n.host).host);Ao(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=r_e(this.opts.query)),kd&&(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"})},zi.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=x3,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&&pr.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",pr.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+=e_e(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,No(()=>{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(pr.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(),kd&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const r=zi.indexOf(this._offlineEventListener);r!==-1&&zi.splice(r,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this._prevBufferLen=0}}}pr.protocol=x3;class k_e extends pr{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;pr.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;pr.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 v_e=class extends k_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=>m_e[a]).filter(a=>!!a)),super(t,r)}};function __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=bd(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 w_e=typeof ArrayBuffer=="function",x_e=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,T3=Object.prototype.toString,E_e=typeof Blob=="function"||typeof Blob<"u"&&T3.call(Blob)==="[object BlobConstructor]",M_e=typeof File=="function"||typeof File<"u"&&T3.call(File)==="[object FileConstructor]";function bp(e){return w_e&&(e instanceof ArrayBuffer||x_e(e))||E_e&&e instanceof Blob||M_e&&e instanceof File}function $i(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,r=e.length;n<r;n++)if($i(e[n]))return!0;return!1}if(bp(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return $i(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&$i(e[n]))return!0;return!1}function S_e(e){const t=[],n=e.data,r=e;return r.data=vd(n,t),r.attachments=t.length,{packet:r,buffers:t}}function vd(e,t){if(!e)return e;if(bp(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]=vd(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]=vd(e[r],t));return n}return e}function N_e(e,t){return e.data=_d(e.data,t),delete e.attachments,e}function _d(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]=_d(e[n],t);else if(typeof e=="object")for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=_d(e[n],t));return e}const A_e=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],T_e=5;var Ge;(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"})(Ge||(Ge={}));class C_e{constructor(t){this.replacer=t}encode(t){return(t.type===Ge.EVENT||t.type===Ge.ACK)&&$i(t)?this.encodeAsBinary({type:t.type===Ge.EVENT?Ge.BINARY_EVENT:Ge.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let n=""+t.type;return(t.type===Ge.BINARY_EVENT||t.type===Ge.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=S_e(t),r=this.encodeAsString(n.packet),a=n.buffers;return a.unshift(r),a}}function R2(e){return Object.prototype.toString.call(e)==="[object Object]"}class kp extends vt{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===Ge.BINARY_EVENT;r||n.type===Ge.BINARY_ACK?(n.type=r?Ge.EVENT:Ge.ACK,this.reconstructor=new R_e(n),n.attachments===0&&super.emitReserved("decoded",n)):super.emitReserved("decoded",n)}else if(bp(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(Ge[r.type]===void 0)throw new Error("unknown packet type "+r.type);if(r.type===Ge.BINARY_EVENT||r.type===Ge.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(kp.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 Ge.CONNECT:return R2(n);case Ge.DISCONNECT:return n===void 0;case Ge.CONNECT_ERROR:return typeof n=="string"||R2(n);case Ge.EVENT:case Ge.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&A_e.indexOf(n[0])===-1);case Ge.ACK:case Ge.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class R_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=N_e(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const I_e=Object.freeze(Object.defineProperty({__proto__:null,Decoder:kp,Encoder:C_e,get PacketType(){return Ge},protocol:T_e},Symbol.toStringTag,{value:"Module"}));function kn(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const O_e=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class C3 extends vt{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=[kn(t,"open",this.onopen.bind(this)),kn(t,"packet",this.onpacket.bind(this)),kn(t,"error",this.onerror.bind(this)),kn(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(O_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:Ge.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:Ge.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 Ge.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 Ge.EVENT:case Ge.BINARY_EVENT:this.onevent(t);break;case Ge.ACK:case Ge.BINARY_ACK:this.onack(t);break;case Ge.DISCONNECT:this.ondisconnect();break;case Ge.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:Ge.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:Ge.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 oa(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}oa.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};oa.prototype.reset=function(){this.attempts=0};oa.prototype.setMin=function(e){this.ms=e};oa.prototype.setMax=function(e){this.max=e};oa.prototype.setJitter=function(e){this.jitter=e};class wd extends vt{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,Ao(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 oa({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||I_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 v_e(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const a=kn(n,"open",function(){r.onopen(),t&&t()}),i=s=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",s),t?t(s):this.maybeReconnectOnOpen()},o=kn(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(kn(t,"ping",this.onping.bind(this)),kn(t,"data",this.ondata.bind(this)),kn(t,"error",this.onerror.bind(this)),kn(t,"close",this.onclose.bind(this)),kn(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){No(()=>{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 C3(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 ma={};function Fi(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=__e(e,t.path||"/socket.io"),r=n.source,a=n.id,i=n.path,o=ma[a]&&i in ma[a].nsps,s=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let l;return s?l=new wd(r,t):(ma[a]||(ma[a]=new wd(r,t)),l=ma[a]),n.query&&!t.query&&(t.query=n.queryKey),l.socket(n.path,t)}Object.assign(Fi,{Manager:wd,Socket:C3,io:Fi,connect:Fi});const L_e=K.createContext(null),D_e=({children:e})=>{const t=nt(),n=xe(y=>y.upsertChat),r=xe(y=>y.upsertChatState),a=xe(y=>y.contextKey),i=K.useMemo(()=>t.config.user?.id??ta(),[t.config.user?.id]),o=t.config.transport,[s,l]=K.useState(null),[u,d]=K.useState(void 0),p=K.useRef(a),m=K.useRef(n),h=K.useRef(r);K.useEffect(()=>{p.current=a,m.current=n,h.current=r},[a,n,r]),K.useEffect(()=>{if(o.mode!=="proxy"){l(null),d(void 0),t.transport instanceof Yr&&t.transport.setSocketId(void 0);return}const y=o.baseUrl,w=new URL(y,window.location.origin),_=`${w.protocol}//${w.host}`,k=o.socketNamespace,v=k?`${_}${k}`:_,M={},S=o;S.headers&&Object.assign(M,S.headers);const x={},$=S.apiKey&&`Bearer ${S.apiKey}`||S.headers?.Authorization;$&&(x.authorization=$,M.Authorization=$);const H=o.socketPath??Vi.Path,C=Fi(v,{path:H,auth:x,transports:["websocket","polling"],...Object.keys(M).length>0&&{extraHeaders:M}});l(C);const L=()=>{d(C.id),t.transport instanceof Yr&&t.transport.setSocketId(C.id)},W=()=>{d(void 0),t.transport instanceof Yr&&t.transport.setSocketId(void 0)},Z=R=>{R.contextKey===p.current&&m.current(R)},ee=R=>{const B=t.store.getState(),P=et(B,R.chat),D=P.messages.findIndex(Y=>Y.id===R.id);if(D>=0){const Y=[...P.messages];Y[D]=R,h.current(R.chat,{...P,messages:Y});return}h.current(R.chat,{...P,messages:[...P.messages,R]})},G=R=>{m.current(R)};return C.on("connect",L),C.on("disconnect",W),C.on("connect_error",R=>{console.error("Socket.IO connection error:",R.message)}),C.on(Ii.ChatNew,Z),C.on(Ii.MessageNew,ee),C.on(Ii.ChatUpdate,G),()=>{t.transport instanceof Yr&&t.transport.setSocketId(void 0),d(void 0),l(null),C.disconnect()}},[t,t.transport,o.mode,o.mode==="proxy"?o.baseUrl:void 0,o.mode==="proxy"?o.apiKey:void 0,o.mode==="proxy"?o.socketPath:void 0,o.mode==="proxy"?o.socketNamespace:void 0,o.mode==="proxy"?JSON.stringify(o.headers??{}):"",i]);const f=K.useMemo(()=>({socket:s,socketId:u}),[s,u]);return N.jsx(L_e.Provider,{value:f,children:e})},vp=K.createContext(null),z_e=({config:e,children:t})=>{const n=K.useRef();n.current||(n.current=new c3(e));const[,r]=K.useState(0);K.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=K.useRef();if(!a.current){const o=n.current.defaultContextKey??n.current.config.contextKeys[0]?.key??"default";a.current=D7e(o),n.current.attachStore(a.current);const s=n.current.config.user?.id??ta(),l=P7e(s);l&&a.current.getState().setActiveChat(l);const u=$7e(n.current.config.models,n.current.config.transport);a.current.getState().setComposerOptions({model:u})}const i=K.useMemo(()=>({runtime:n.current,store:a.current}),[]);return K.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??ta();q7e(u,l)})},[]),N.jsx(vp.Provider,{value:i,children:N.jsx(Bt.QueryClientProvider,{client:i.runtime.queryClient,children:N.jsx(p3,{value:i.runtime.config.theme,children:N.jsx(D_e,{children:t})})})})},nt=()=>{const e=K.useContext(vp);if(!e)throw new Error("useAgentRuntime must be used inside <AgentProvider />");return e.runtime},xe=e=>{const t=K.useContext(vp);if(!t)throw new Error("useAgentStore must be used inside <AgentProvider />");return h5.useStore(t.store,e)},To=30*1e3,Co=5*60*1e3,R3=20,_n={all:["mp-agents","activities"],lists:()=>[..._n.all,"list"],list:e=>[..._n.lists(),e],infinites:()=>[..._n.all,"infinite"],infinite:e=>[..._n.infinites(),e],detail:e=>[..._n.all,"detail",e],summary:e=>[..._n.all,"summary",e]},$_e=e=>e?.pages.flatMap(t=>t.data)??[],I3=(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.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}},O3=e=>({data:[],cursor:{total:0,skip:0,limit:e}}),F_e=e=>{const t=nt(),{groupId:n,parentId:r,enabled:a=!0,sortOrder:i=exports.SortOrder.Desc,sortField:o="createdAt",pageSize:s=R3,from:l,to:u,tenant:d,ownerId:p}=e??{};return Bt.useInfiniteQuery({queryKey:_n.infinite({groupId:n,parentId:r,sortField:o,sortOrder:i,pageSize:s,from:l,to:u,tenant:d,ownerId:p}),queryFn:async({pageParam:m})=>t.transport.listActivities?t.transport.listActivities(I3({groupId:n,parentId:r,sortField:o,sortOrder:i,from:l,to:u,tenant:d,ownerId:p},m,s)):O3(s),initialPageParam:0,getNextPageParam:m=>{const h=(m.cursor.skip??0)+m.data.length;return h<m.cursor.total?h:void 0},enabled:a&&!!t.transport.listActivities,staleTime:To,gcTime:Co})},P_e=e=>{const t=nt(),{groupId:n,parentId:r,page:a,enabled:i=!0,sortOrder:o=exports.SortOrder.Desc,sortField:s="createdAt",pageSize:l=R3,from:u,to:d,tenant:p,ownerId:m}=e,h=(a-1)*l,f=Bt.useQuery({queryKey:_n.list({groupId:n,parentId:r,sortField:s,sortOrder:o,pageSize:l,page:a,from:u,to:d,tenant:p,ownerId:m}),queryFn:async()=>t.transport.listActivities?t.transport.listActivities(I3({groupId:n,parentId:r,sortField:s,sortOrder:o,from:u,to:d,tenant:p,ownerId:m},h,l)):O3(l),enabled:i&&!!t.transport.listActivities&&a>=1,staleTime:To,gcTime:Co}),y=f.data?.cursor.total??0,w=Math.max(1,Math.ceil(y/l));return{...f,page:a,pageSize:l,totalPages:w,total:y,hasNextPage:a<w,hasPreviousPage:a>1}},q_e=e=>{const t=nt();return Bt.useQuery({queryKey:_n.detail(e),queryFn:async()=>!e||!t.transport.getActivity?null:t.transport.getActivity(e),enabled:!!e&&!!t.transport.getActivity,staleTime:To,gcTime:Co})},B_e=e=>{const t=nt(),{enabled:n=!0,...r}=e??{};return Bt.useQuery({queryKey:_n.summary(r),queryFn:async()=>t.transport.getActivitySummary?t.transport.getActivitySummary(r):[],enabled:n&&!!t.transport.getActivitySummary,staleTime:To,gcTime:Co})},L3=30*1e3,D3=5*60*1e3,_p=20,sr={all:["mp-agents","chats"],lists:()=>[...sr.all,"list"],list:e=>[...sr.lists(),e],infinites:()=>[...sr.all,"infinite"],infinite:e=>[...sr.infinites(),e],detail:e=>[...sr.all,"detail",e]},U_e=e=>e?.pages.flatMap(t=>t.data)??[],z3=e=>{const t=nt(),n=t.config.user?.id??ta(),{pageSize:r=_p,sortOrder:a="desc",sortField:i="updatedAt",enabled:o=!0}=e??{};return Bt.useInfiniteQuery({queryKey:sr.infinite({userId:n,sortField:i,sortOrder:a,pageSize:r}),queryFn:async({pageParam:s})=>await t.transport.listChats({userId:n,skip:s,limit:r,sortOrder:a,sortField:i}),initialPageParam:0,getNextPageParam:s=>{const{cursor:l,data:u}=s,d=(l.skip??0)+u.length;return d<l.total?d:void 0},enabled:o&&!!n,staleTime:L3,gcTime:D3})},$3=z3,H_e=e=>{const t=nt(),n=t.config.user?.id??ta(),{page:r,pageSize:a=_p,sortOrder:i="desc",sortField:o="updatedAt",enabled:s=!0}=e,l=(r-1)*a,u=Bt.useQuery({queryKey:sr.list({userId:n,sortField:o,sortOrder:i,pageSize:a,page:r}),queryFn:async()=>t.transport.listChats({userId:n,skip:l,limit:a,sortOrder:i,sortField:o}),enabled:s&&!!n&&r>=1,staleTime:L3,gcTime:D3}),d=u.data?.cursor.total??0,p=Math.max(1,Math.ceil(d/a));return{...u,page:r,pageSize:a,totalPages:p,total:d,hasNextPage:r<p,hasPreviousPage:r>1}},wp=e=>{const t=$3(e),n=xe(r=>r.hydrateChats);return K.useEffect(()=>{if(t.data?.pages){const r=t.data.pages.flatMap(a=>a.data);n(r)}},[t.data,n]),t},F3=(e={},t=[])=>{const{threshold:n=50,scrollOnMount:r=!0}=e,a=K.useRef(null),i=K.useRef(null),[o,s]=K.useState(!0),l=K.useRef(!1),u=K.useRef(!1),d=K.useRef(),p=K.useCallback(()=>{const f=a.current;if(!f)return!1;const{scrollTop:y,scrollHeight:w,clientHeight:_}=f;return w-y-_<=n},[n]),m=K.useCallback(()=>{const f=a.current,y=i.current;!f||!y||y.scrollIntoView({behavior:"auto",block:"end"})},[]),h=K.useCallback(()=>{const f=p();s(f),f&&(l.current=!1)},[p]);return K.useEffect(()=>{const f=a.current;if(!f)return;let y=f.scrollTop,w;const _=()=>{const k=f.scrollTop;if(!u.current){const v=k<y,M=k>y;(v||M&&!p())&&(l.current=!0)}y=k,h(),w&&clearTimeout(w),w=window.setTimeout(()=>{u.current=!1},150)};return f.addEventListener("scroll",_,{passive:!0}),()=>{f.removeEventListener("scroll",_),w&&clearTimeout(w)}},[p,h]),K.useEffect(()=>{const f=a.current;if(!f)return;const y=new MutationObserver(()=>{!l.current&&o&&(d.current&&cancelAnimationFrame(d.current),d.current=requestAnimationFrame(()=>{u.current=!0,m(),setTimeout(()=>{u.current=!1},50)})),h()});return y.observe(f,{childList:!0,subtree:!0,characterData:!0,attributes:!1}),()=>{y.disconnect(),d.current&&cancelAnimationFrame(d.current)}},[o,m,h]),K.useEffect(()=>{t.length!==0&&!l.current&&o&&(d.current&&cancelAnimationFrame(d.current),d.current=requestAnimationFrame(()=>{u.current=!0,m(),setTimeout(()=>{u.current=!1},50)}))},[...t]),K.useEffect(()=>{if(r&&a.current){const f=window.setTimeout(()=>{u.current=!0,m(),setTimeout(()=>{u.current=!1},50)},100);return()=>{clearTimeout(f)}}},[r,m]),{containerRef:a,sentinelRef:i,isNearBottom:o,scrollToBottom:m,checkIsNearBottom:p}},P3=()=>{const e=nt();return Bt.useQuery({queryKey:["mp-agents","models"],queryFn:async()=>e.transport.listModels?await e.transport.listModels():[],staleTime:5*60*1e3,refetchOnWindowFocus:!1})},q3=()=>{const e=xe(s=>s.activeChatId??s.draftChatKey),t=xe(s=>et(s,e).composerDraft),n=xe(s=>s.setComposerValue),r=xe(s=>s.setComposerDraft),a=xe(s=>s.clearComposerDraft),i=xe(s=>s.addComposerAttachments),o=xe(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)}},B3=e=>{const t=nt();return Bt.useQuery({queryKey:["mp-agents","configurations",e??"all"],queryFn:async()=>t.transport.listAgentConfigurations?t.transport.listAgentConfigurations(e):[],staleTime:6e4,refetchOnWindowFocus:!1})},j_e=(e,t=[])=>{const n=nt(),r=K.useRef(e),a=K.useCallback(e,t);r.current=a;const i=K.useCallback(o=>r.current(o),[]);K.useEffect(()=>n.registerPageContextProvider(i),[n,i])},U3=(e,t,n=[],r)=>{const a=nt(),i=K.useRef(t),o=K.useCallback(t,n);i.current=o;const s=K.useCallback(u=>{i.current(u)},[]),l=typeof r=="boolean"?r:r?.capture;K.useEffect(()=>(a.events.addEventListener(e,s,r),()=>{a.events.removeEventListener(e,s,l)}),[a,e,s,l])},V_e=({formId:e,onApply:t,enabled:n=!0})=>{U3(ep,r=>{n&&r.detail.formId===e&&t(r.detail)},[n,e,t])},G_e=["mp-agents","configurations"],H3=()=>{const e=nt(),t=Bt.useQueryClient(),n=()=>t.invalidateQueries({queryKey:G_e}),r=Bt.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=Bt.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}},j3=()=>{const e=nt(),t=xe(s=>s.activeChatId),n=xe(s=>s.chats),r=xe(s=>s.upsertChat),a=xe(s=>s.setActiveChat),i=!!t&&!n[t],o=Bt.useQuery({queryKey:["mp-agents","chat",t],queryFn:()=>e.transport.getChat(t),enabled:i,staleTime:6e4,retry:!1});return K.useEffect(()=>{o.data&&r(o.data)},[o.data,r]),K.useEffect(()=>{o.isError&&t&&a(void 0)},[o.isError,t,a]),o},V3=30,G3=e=>{const t=nt(),n=xe(i=>i.setChatMessages),r=xe(i=>!!(e&&i.chats[e])),a=Bt.useInfiniteQuery({queryKey:["mp-agents","messages",e],queryFn:async({pageParam:i})=>{if(!e||!t.transport.getMessages)throw new Error("No chat or transport");return await t.transport.getMessages(e,{limit:V3,...i?{before:i}:{}})},initialPageParam:void 0,getNextPageParam:i=>i.hasMore&&i.messages.length>0?i.messages[0]?.id:void 0,enabled:!!e&&!!t.transport.getMessages&&r});return K.useEffect(()=>{if(!e||!a.data?.pages)return;const o=a.data.pages.slice().reverse().flatMap(l=>l.messages),s=new Set(o.map(l=>l.id));n(e,l=>{const u=l.filter(d=>!s.has(d.id));return[...o,...u]})},[e,a.data,n]),a},W3=()=>{const e=nt(),t=e.config.user?.id??ta(),n=xe(u=>u.activeChatId),r=xe(u=>u.removeChat),a=xe(u=>u.setActiveChat),[i,o]=K.useState(new Set),s=K.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=K.useCallback(u=>i.has(u),[i]);return{deleteChat:s,isDeleting:l}},W_e=({initialSystemPrompt:e,composerFormRef:t})=>{const n=nt(),{composer:r,contextKey:a,activeChatId:i,draftChatKey:o,queuedMessages:s,activeChatStatus:l,upsertChat:u,setChatStatus:d,setActiveChat:p,setComposerError:m,moveChatKeyState:h,removeQueuedMessage:f,setPendingAssistant:y,enqueueQueuedMessage:w,appendMessagesToChat:_,commitPendingAssistant:k,setPageContextDismissed:v}=xe(P=>{const D=P.activeChatId??P.draftChatKey,Y=et(P,D);return{composer:P.composer,contextKey:P.contextKey,activeChatId:P.activeChatId,draftChatKey:P.draftChatKey,queuedMessages:Y.messageQueue,activeChatStatus:Y.status,upsertChat:P.upsertChat,setActiveChat:P.setActiveChat,setChatStatus:P.setChatStatus,setComposerError:P.setComposerError,moveChatKeyState:P.moveChatKeyState,setPendingAssistant:P.setPendingAssistant,removeQueuedMessage:P.removeQueuedMessage,enqueueQueuedMessage:P.enqueueQueuedMessage,appendMessagesToChat:P.appendMessagesToChat,commitPendingAssistant:P.commitPendingAssistant,setPageContextDismissed:P.setPageContextDismissed}}),M=K.useCallback(P=>!P||P.length===0?!1:P.some(D=>D.type===exports.AgentAttachmentType.Context&&D?.metadata?.kind==="pageContext"),[]),S=K.useRef(!1),x=K.useRef(!1),$=K.useRef(void 0),H=K.useRef(new Set),C=i??o,L=K.useCallback(async(P,D)=>{if(!n.transport.generateTitle)return;const Y=n.config.features?.titleGeneration==="llm"?"llm":"local";let A;try{A=await n.transport.generateTitle({userId:D,content:P,strategy:Y,contextKey:a})}catch{}return A},[n.transport,n.config.features?.titleGeneration,a]),W=K.useCallback(async(P,D)=>{const Y=n.config.user?.id??"guest",A=!i,J=i??o,te={current:J};$.current=J;const O={value:P,attachments:D??[]};m(te.current,void 0);let de;if(A){const we=await L(P,Y);we&&we.trim().length>0&&(de={...de??{},title:we})}const ke=(i?n.store.getState().chats[i]:void 0)?.model,Oe=r.model!==ke;let ze,He=!1;Oe?(ze=r.model,He=!0):ke?(ze=ke,He=!1):(ze=void 0,He=!1);const re={userId:Y,content:P,metadata:de,contextKey:a,...A?{}:{chatId:i},...He?{model:ze??""}:{},...D&&D.length>0?{attachments:D}:{}},Ee=()=>{y(te.current,void 0)},Qe=we=>{if(we?.name==="AbortError"){const Ne=$.current??te.current;return H.current.has(Ne)?(k(te.current),H.current.delete(Ne)):(Ee(),t.current.setDraft(O)),{type:"aborted"}}throw we},Je=async()=>{let we=`pending-${Date.now()}`,Ne="",ve;d(te.current,Cn.Streaming),y(te.current,{id:we,content:"",reasoning:"",toolCalls:[],attachments:[],chat:i||"",role:exports.MessageRole.Assistant,createdAt:new Date().toISOString()});try{let Be=i;const pe=await n.transport.streamMessage(re,Re=>{if(Re.type===exports.StreamChunkType.Chat&&Re.chat){u(Re.chat),Be=Re.chat.id,A&&($.current=Re.chat.id,h(te.current,Re.chat.id),te.current=Re.chat.id,p(Re.chat.id));return}if(Re.type===exports.StreamChunkType.Reasoning&&Re.reasoning){Ne+=Re.reasoning,ve={...ve??{id:we,chat:Be,role:exports.MessageRole.Assistant,content:"",createdAt:new Date().toISOString()},reasoning:Ne},y(te.current,ve);return}if(Re.type===exports.StreamChunkType.Error&&Re.error)throw new Error(Re.error);Re.message&&Re.message.role===exports.MessageRole.User||Re.message&&(we=Re.message.id,ve={...Re.message,reasoning:Ne||Re.message.reasoning},y(te.current,ve))},{streamKey:$.current});if(pe){const Re=pe.messages.map(_e=>_e.id===ve.id&&_e.role===exports.MessageRole.Assistant?{..._e,reasoning:Ne}:_e);_(pe.id,Re);const rt=n.store.getState();return(rt.activeChatId??rt.draftChatKey)===te.current&&p(pe.id),Ee(),{type:"success"}}return Ee(),{type:"success"}}catch(Be){return Qe(Be)}};try{const we=await Je();return we.type==="success"&&(S.current=!1),we}catch(we){Ee();const Ne=we?.chat;Ne&&(u(Ne),p(Ne.id));const ve=we instanceof Error?we:new Error("Failed to send message");return m(te.current,ve.message||"Failed to send message"),t.current.setDraft(O),S.current=!1,{type:"error",error:ve}}finally{x.current=!1,d(te.current,Cn.Idle),$.current=void 0}},[i,a,r.model,n.transport,n.config.user?.id,u,p,y,d,L,e,h,t,m]),Z=K.useCallback(async()=>{if(l!==Cn.Idle||x.current||!s.length||S.current)return;const P=s[0];x.current=!0,f(C,P.id);try{await W(P.content,P.attachments)}finally{x.current=!1}},[l,s,C,W,f]);K.useEffect(()=>{Z()},[Z]);const ee=K.useCallback(async P=>{if(x.current)return;const D=s.find(Y=>Y.id===P);if(D){S.current=!1,x.current=!0,f(C,P);try{await W(D.content,D.attachments)}finally{x.current=!1}}},[s,C,f,W]),G=K.useCallback(async P=>{const Y=t.current.getDraft().attachments;if(M(Y)&&v(C,!0),l!==Cn.Idle){w(C,P,Y),t.current.clearDraft();return}S.current=!1,t.current.clearDraft(),await W(P,Y)},[l,w,C,W,t,M,v]),R=K.useCallback(()=>{S.current=!0;const P=$.current??C;H.current.add(P),n.transport.cancelStream?.(P),k(P),d(P,Cn.Idle)},[C,n.transport,k,d]),B=K.useCallback(async P=>{l===Cn.Streaming&&R(),await ee(P)},[l,R,ee]);return{pendingKey:C,queuedMessages:s,activeChatStatus:l,activeChatId:i,removeQueuedMessage:f,handleSubmit:G,handleStop:R,handleQueuedClick:B}},K_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(mo,{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(Xd,{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(T5,{size:12})})]})]},r.id))})]}):null;function Y_e(e,t){return e.size>t.maxFileSize?{type:"size",message:`File "${e.name}" exceeds maximum size of ${xp(t.maxFileSize)}`,fileName:e.name}:null}function Z_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=Y_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 ${xp(n.maxTotalAttachmentsSize)}`}:null}function xp(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 X_e(){return{maxFileSize:10*1024*1024,maxTotalAttachmentsSize:50*1024*1024,maxFilesPerMessage:10,allowedMimeTypes:void 0}}const K3=e=>{switch(e.type){case exports.AgentAttachmentType.Link:return N.jsx(M5,{size:12});case exports.AgentAttachmentType.Artifact:return N.jsx(mo,{size:12});case exports.AgentAttachmentType.Context:switch(e?.metadata?.kind){case"pageContext":return N.jsx(Qd,{size:12});case"formSnapshot":case"formField":return N.jsx(E5,{size:12});default:return N.jsx(Jd,{size:12})}case exports.AgentAttachmentType.File:default:return N.jsx(x5,{size:12})}},Q_e=({attachments:e})=>!e||e.length===0?null:N.jsx("div",{className:"mp-agent-message-attachments","aria-label":"Message attachments",children:e.map(t=>{const n=N.jsxs(N.Fragment,{children:[N.jsx("span",{className:"mp-agent-message-attachment-icon",children:K3(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:n},t.id):N.jsx("span",{className:"mp-agent-message-attachment",title:t.mimeType??t.name,children:n},t.id)})}),J_e=({attachments:e,onRemove:t,uploadProgress:n,uploadErrors:r})=>{const a=yn();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?` (${xp(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:K3(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(xn,{size:"sm",icon:"X",type:"button",onClick:d=>{d.preventDefault(),d.stopPropagation(),t(i.id)},"aria-label":`Remove attachment ${i.name}`}):null]},i.id)})})},ewe=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)},twe=e=>{try{const t=new URL(e);return t.hostname+(t.pathname&&t.pathname!=="/"?t.pathname:"")}catch{return e}},xd="mp-agent:locationchange",I2="__mp_agent_history_patched__",O2=()=>{try{window.dispatchEvent(new Event(xd))}catch{}},nwe=()=>{if(typeof window>"u")return;const e=window;if(!e[I2]){e[I2]=!0;try{const t=history.pushState;history.pushState=function(...n){const r=t.apply(this,n);return O2(),r}}catch{}try{const t=history.replaceState;history.replaceState=function(...n){const r=t.apply(this,n);return O2(),r}}catch{}}},rwe=e=>{if(typeof window>"u")return()=>{};nwe();const t=()=>e();return window.addEventListener("popstate",t),window.addEventListener("hashchange",t),window.addEventListener(xd,t),()=>{window.removeEventListener("popstate",t),window.removeEventListener("hashchange",t),window.removeEventListener(xd,t)}};async function awe(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 iwe(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 owe(e,t,n){const r=Rt.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 awe(e,n.chatId,n.userId,t);return await iwe(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 swe(e,t,n){const r=await Promise.allSettled(e.map(o=>owe(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 lwe=({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]=K.useState(!1),[h,f]=K.useState(null),[y,w]=K.useState(""),_=K.useRef([]),k=K.useRef(null),{refs:v,floatingStyles:M,context:S,isPositioned:x}=dp({open:p,onOpenChange:m,placement:s,strategy:"absolute",whileElementsMounted:ip,middleware:[op(8),lp({fallbackPlacements:["top-start","bottom-start","top-end","bottom-end"]}),sp({padding:8})]}),$=a3(S,{enabled:!a}),H=up(S),C=hp(S),W=S7e(S,{listRef:_,activeIndex:h,onNavigate:f,enabled:p&&!l,virtual:!1}),{getReferenceProps:Z,getFloatingProps:ee,getItemProps:G}=pp(l?[$,H,C]:[$,H,C,W]),R=e.findIndex(J=>J.value===t),B=R>=0?e[R]:void 0,P=K.useMemo(()=>{const J=y.trim().toLowerCase();if(!l||!J)return e;const O=d?de=>d(de,J):de=>`${de.label} ${de.description??""}`.toLowerCase().includes(J);return e.filter(O)},[e,y,l,d]);K.useEffect(()=>{if(!p){f(null),w("");return}l&&setTimeout(()=>k.current?.focus(),0);const J=P.findIndex(te=>te.value===t);f(J>=0?J:0)},[p,l,t,P]),K.useEffect(()=>{p&&f(P.length>0?0:null)},[y,P.length,p]);const D=J=>P.length===0?null:J<0?P.length-1:J>=P.length?0:J,Y=J=>{J!=null&&_.current[J]?.scrollIntoView({block:"nearest"})},A=J=>{n(J),m(!1),f(null),w("")};return N.jsxs("div",{className:`mp-agent-dropdown ${i}`,children:[N.jsxs("button",{ref:v.setReference,type:"button",className:`mp-agent-dropdown-trigger ${o}`,disabled:a,"aria-expanded":p,"aria-haspopup":"listbox",...Z(),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(w5,{size:16,className:`mp-agent-dropdown-chevron ${p?"open":""}`})]}),p&&N.jsxs("div",{role:"listbox",ref:v.setFloating,style:{...M,opacity:x?1:0,pointerEvents:x?"auto":"none",transition:x?"opacity 0.15s ease-out":"none"},className:"mp-agent-dropdown-menu",...ee(),children:[l&&N.jsx("div",{className:"mp-agent-dropdown-search",onKeyDown:J=>J.stopPropagation(),children:N.jsx("input",{ref:k,className:"mp-agent-dropdown-search-input",value:y,placeholder:u,onChange:J=>w(J.target.value),onKeyDown:J=>{if(J.key==="Escape"){J.preventDefault(),m(!1),w("");return}if(J.key==="ArrowDown"||J.key==="ArrowUp"){J.preventDefault();const te=J.key==="ArrowDown"?1:-1,O=h??(te>0?-1:0),de=D(O+te);f(de),Y(de);return}if(J.key==="Enter"){if(h==null)return;const te=P[h];if(!te)return;J.preventDefault(),A(te.value)}}})}),N.jsxs("div",{className:"mp-agent-dropdown-list",children:[P.map((J,te)=>N.jsxs("button",{ref:O=>{_.current[te]=O},type:"button",className:`mp-agent-dropdown-item ${t===J.value?"selected":""} ${h===te?"active":""}`,role:"option","aria-selected":t===J.value,...G({onClick:()=>A(J.value),onMouseEnter:()=>{f(te)},onKeyDown:O=>{(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),A(J.value))}}),children:[J.icon&&N.jsx("span",{className:"mp-agent-dropdown-item-icon",children:J.icon}),N.jsxs("span",{className:"mp-agent-dropdown-item-content",children:[N.jsx("span",{className:"mp-agent-dropdown-item-label",children:J.label}),J.description&&N.jsx("span",{className:"mp-agent-dropdown-item-description",children:J.description})]})]},J.value)),l&&P.length===0&&N.jsx("div",{className:"mp-agent-dropdown-empty","aria-label":"No results",children:"No results"})]})]})]})},cwe=K.memo(()=>{const e=nt(),t=xe(p=>p.composer),n=xe(p=>p.contextKey),r=xe(p=>p.setComposerOptions),a=e.config.models,{data:i,isLoading:o}=P3(),s=K.useMemo(()=>{const p=i&&i.length>0?i:a;return f3(p,e.config.transport).filter(h=>!h.contexts?.length||h.contexts.includes(n))},[i,a,e.config.transport,n]),l=K.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:ka,label:"Auto"},...p]},[s]),u=K.useMemo(()=>t.model!==void 0?t.model:ka,[t.model]),d=K.useCallback(p=>{p===ka?(r({model:void 0}),M2(e.config.transport,ka)):(r({model:p}),M2(e.config.transport,p))},[r,e.config.transport]);return o&&!a?.length||l.length===0?null:N.jsx(lwe,{options:l,value:u,onChange:d,placeholder:"Select model...",searchable:!0,searchPlaceholder:"Search models...",placement:"top-start",triggerClassName:"mp-agent-model-selector-trigger"})}),uwe=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):""},dwe=({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"})})},L2=e=>e.reduce((t,n)=>(t[n.agentName]={...n.tools},t),{}),Y3=({preferences:e,disabled:t})=>{const n=yn(),{upsertSingle:r}=H3(),[a,i]=K.useState(()=>L2(e)),[o,s]=K.useState({});K.useEffect(()=>{i(L2(e))},[e]);const l=r.error?.message,u=K.useMemo(()=>e.some(p=>Object.keys(p.tools).length>0),[e]),d=(p,m,h)=>{i(f=>{const y=f[p]??{},w=y,_={...y,[m]:h},k={...f,[p]:_};return s(v=>({...v,[p]:{...v[p]??{},[m]:!0}})),r.mutate({agentName:p,input:{tools:_}},{onError:()=>{i(v=>({...v,[p]:w}))},onSettled:()=>{s(v=>{const M={...v[p]??{}};if(delete M[m],Object.keys(M).length===0){const{[p]:S,...x}=v;return x}return{...v,[p]:M}})}}),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(([f,y])=>{const w=!!o[p.agentName]?.[f];return N.jsxs("label",{className:"mp-agent-preferences-tool",children:[N.jsx("span",{className:"mp-agent-preferences-tool-label",children:uwe(f)}),N.jsx(dwe,{checked:y,onChange:_=>d(p.agentName,f,_),disabled:!!t||w})]},`${p.agentName}:${f}`)})})]},p.agentName)}),l&&N.jsx("div",{className:"mp-agent-preferences-error",children:l})]})};function pwe(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 hwe=()=>{const e=yn(),t=nt(),n=xe(l=>l.contextKey),{data:r,isLoading:a,isError:i}=B3(n),o=K.useMemo(()=>pwe(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(Y3,{preferences:o,disabled:!s})},mwe=()=>{const[e,t]=K.useState(!1),n=yn(),{refs:r,floatingStyles:a,context:i,isPositioned:o}=dp({open:e,onOpenChange:t,placement:"top-start",strategy:"absolute",whileElementsMounted:ip,middleware:[op(8),lp({fallbackPlacements:["bottom-start","top-end","bottom-end"]}),sp({padding:8})]}),s=a3(i),l=up(i),u=hp(i),{getReferenceProps:d,getFloatingProps:p}=pp([s,l,u]);return N.jsxs("div",{className:"mp-agent-tool-config-dropdown",children:[N.jsx(Wn,{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(S5,{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(hwe,{})})]})},fwe=K.forwardRef(({autoFocus:e,activeChatId:t,status:n,onStop:r,onSubmit:a},i)=>{const o=yn(),s=nt(),l=K.useRef(null),u=K.useRef(null),d=xe(re=>re.activeChatId??re.draftChatKey),p=xe(re=>et(re,d).composerDraft),m=xe(re=>et(re,d).composerError),h=xe(re=>et(re,d).pageContextDismissed),f=xe(re=>re.setComposerValue),y=xe(re=>re.setComposerDraft),w=xe(re=>re.clearComposerDraft),_=xe(re=>re.setComposerError),k=xe(re=>re.addComposerAttachments),v=xe(re=>re.removeComposerAttachment),M=xe(re=>re.setPageContextDismissed),S=p.value,x=p.attachments,[$,H]=K.useState(new Map),[C,L]=K.useState(new Map),W=K.useRef(S),Z=K.useRef(x),ee=K.useRef(h),G=s.config.features?.pageContextAttachments!==!1,R=re=>re.type===exports.AgentAttachmentType.Context&&re?.metadata?.kind==="pageContext",B=x.some(R),P=()=>{if(G)return s.buildPageContextAttachment()};K.useEffect(()=>{Z.current=x},[x]),K.useEffect(()=>{W.current=S},[S]),K.useEffect(()=>{ee.current=h},[h]),K.useEffect(()=>{if(!G||h||B)return;const re=P();re&&k(d,[re])},[G,h,B,d,k]),K.useEffect(()=>{if(G&&!(typeof window>"u"))return rwe(()=>{if(ee.current)return;const re=Z.current,Ee=re.find(R);if(!Ee)return;const Qe=P();if(!Qe)return;const Je={...Qe,id:Ee.id},we=re.map(Ne=>Ne.id===Ee.id?Je:Ne);y(d,{value:W.current,attachments:we})})},[G,d,y]),K.useImperativeHandle(i,()=>({setValue:re=>{f(d,re)},getDraft:()=>({value:S,attachments:x}),setDraft:re=>{y(d,{value:re.value,attachments:re.attachments??[]})},clearDraft:()=>{w(d)}})),K.useEffect(()=>{const re=l.current;re&&(re.style.height="auto",re.style.height=`${Math.min(re.scrollHeight,200)}px`)},[S]);const D=async re=>{if(!re||re.length===0)return;const Ee=Array.from(re),Qe=X_e(),Je=Z_e(Ee,x,Qe);if(Je){L(we=>{const Ne=new Map(we);return Ee.forEach(ve=>{Ne.set(ve.name,Je.message)}),Ne});return}L(we=>{const Ne=new Map(we);return Ee.forEach(ve=>Ne.delete(ve.name)),Ne});try{const we=s.config.transport;if(we.mode!=="proxy")throw new Error("File uploads are only supported with proxy transport");const Ne={presignedUrlEndpoint:`${we.baseUrl}/files/upload/presigned`,getAuthHeaders:()=>{const Be={};return we.headers?we.headers:(we.apiKey&&(Be.Authorization=`Bearer ${we.apiKey}`),Be)}},ve=await swe(Ee,Ne,{chatId:t,userId:s.config.user?.id,onProgress:Be=>{H(pe=>{const Re=new Map(pe);return Re.set(Be.fileId,Be),Re})}});k(d,ve),setTimeout(()=>{H(Be=>{const pe=new Map(Be);return ve.forEach(Re=>pe.delete(Re.id)),pe})},2e3)}catch(we){const Ne=we instanceof Error?we.message:"Failed to upload files";L(ve=>{const Be=new Map(ve);return Ee.forEach(pe=>{Be.set(pe.name,Ne)}),Be})}},Y=()=>{u.current?.click()},A=re=>{const Ee=ewe(re);if(!Ee)return!1;if(x.some(we=>we.type===exports.AgentAttachmentType.Link&&we.url===Ee))return!0;const Qe=twe(Ee),Je={id:Rt.nanoid(),url:Ee,name:Qe,type:exports.AgentAttachmentType.Link};return k(d,[Je]),!0},J=async re=>{await D(re.target.files),re.target.value=""},te=re=>{const Ee=x.find(Qe=>Qe.id===re);Ee&&R(Ee)&&M(d,!0),v(d,re)},O=()=>{if(typeof window>"u"||typeof document>"u")return!1;const re=l3(),Ee=re?.selectedText??window.getSelection?.()?.toString()?.trim()??"";if(!Ee)return!1;const Qe=window.location?.href,Je=Ee.slice(0,20),we=Ee.length>20?Je+"...":Ee,Ne=So({kind:"webSnippet",url:Qe,title:we,selectedText:Ee,source:{app:"browser",url:Qe},...re?.target?{target:re.target}:{}});return k(d,[Ne]),!0},de=re=>{re.preventDefault();const Ee=S.trim();Ee&&(_(d,void 0),a(Ee))},ye=re=>{re.key==="Enter"&&!re.shiftKey&&(re.preventDefault(),de(re))},ke=re=>{m&&_(d,void 0),f(d,re.target.value)},Oe=re=>{if(re.nativeEvent.shiftKey)return;const Ee=re.clipboardData?.getData("text/plain")??"";if(!Ee)return;A(Ee)&&re.preventDefault()},He=!!S.trim();return N.jsxs(N.Fragment,{children:[N.jsxs("form",{onSubmit:de,className:"mp-agent-composer-input-wrapper",id:"composer-form",children:[N.jsx("input",{ref:u,type:"file",multiple:!0,style:{display:"none"},onChange:J}),N.jsx(J_e,{attachments:x,onRemove:te,uploadProgress:$,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:ye,onPaste:Oe})]}),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(cwe,{}),s.config.features?.toolConfiguration&&N.jsx(mwe,{}),N.jsx(Wn,{content:o.attachFiles,children:N.jsx("button",{type:"button",className:"mp-agent-composer-button mp-agent-composer-tool-button",onClick:Y,"aria-label":o.attachFiles,children:N.jsx(mo,{size:16})})}),N.jsx(Wn,{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(Jd,{size:16})})}),G&&!B&&N.jsx(Wn,{content:"Attach page context",children:N.jsx("button",{type:"button",className:"mp-agent-composer-button mp-agent-composer-tool-button",onClick:()=>{M(d,!1);const re=P();re&&k(d,[re])},"aria-label":"Attach page context",children:N.jsx(Qd,{size:16})})})]}),N.jsx("div",{className:"mp-agent-composer-actions-right",children:n===Cn.Streaming&&!He?N.jsx(Wn,{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(A5,{size:12})})}):N.jsx(Wn,{content:He?o.sendMessage:o.typeMessageToSend,children:N.jsx("button",{type:"submit",form:"composer-form",disabled:!He,"aria-label":o.sendMessage,className:"mp-agent-composer-button mp-agent-composer-send-button",children:N.jsx(Xd,{size:16})})})})]})]})}),Z3=({autoFocus:e})=>{const t=K.useRef({setValue:()=>{},getDraft:()=>({value:"",attachments:[]}),setDraft:()=>{},clearDraft:()=>{}}),{pendingKey:n,queuedMessages:r,activeChatStatus:a,activeChatId:i,handleSubmit:o,handleStop:s,handleQueuedClick:l,removeQueuedMessage:u}=W_e({composerFormRef:t});return N.jsx("div",{className:"mp-agent-composer-wrapper",children:N.jsxs("div",{className:"mp-agent-composer",children:[N.jsx(K_e,{queuedMessages:r,onSendQueued:l,onRemoveQueued:d=>u(n,d)}),N.jsx(fwe,{status:a,ref:t,autoFocus:e,activeChatId:i,onStop:s,onSubmit:o})]})})},X3=K.memo(()=>{const e=xe(n=>n.activeChatId??n.draftChatKey),t=xe(n=>et(n,e).composerError);return t?N.jsx("div",{className:"mp-agent-composer-error",children:t}):null});X3.displayName="ComposerError";const gwe=(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}...`}},ys=e=>{if(e===void 0)return"undefined";try{return JSON.stringify(e,null,2)??"undefined"}catch{try{return String(e)}catch{return"[unserializable]"}}},D2=({call:e})=>nt().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:ys(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:ys(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:ys(e.error)})})]})]})]}):null,ywe=({call:e})=>{const t=nt();if(!t.config.debug)return null;const r=t.tools.get(e.name)?.label??e.name,a=gwe(e,r);return N.jsx("div",{className:"mp-agent-tool-header",children:N.jsx("div",{className:"mp-agent-tool-simple-message",children:a})})},Q3=({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"})}),bwe=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}},kwe=({callId:e,input:t,isSubmitting:n,onSubmit:r})=>{const[a,i]=K.useState([]),[o,s]=K.useState(""),[l,u]=K.useState(void 0),d=K.useMemo(()=>bwe(t),[t]);K.useEffect(()=>{i([]),s(""),u(void 0)},[e,t]);const p=h=>{if(d){if(u(void 0),d.selectionMode==="single"){i([h]);return}i(f=>f.includes(h)?f.filter(y=>y!==h):[...f,h])}},m=async()=>{if(!d)return;const h=o.trim(),f=a.length>0,y=d.allowFreeText&&h.length>0;if(!f&&!y){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:v,description:M})=>({id:k,label:v,...M?{description:M}:{}})),_={question:d.question,selectionMode:d.selectionMode,selectedOptionIds:a,selectedOptions:w,...h?{freeText:h}:{}};await r(JSON.stringify(_))};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 f=`${e}-${h.id}`,y=a.includes(h.id);return N.jsxs("label",{htmlFor:f,className:"mp-agent-tool-user-action-option",children:[N.jsx("input",{id:f,type:d.selectionMode==="single"?"radio":"checkbox",name:`mp-agent-tool-user-action-${e}`,checked:y,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."})})},vwe=({call:e,messageId:t,chatId:n,onApprovalSent:r})=>{const a=nt(),i=xe(x=>x.appendMessagesToChat),[o,s]=K.useState(!1),[l,u]=K.useState(!1),[d,p]=K.useState(!1),[m,h]=K.useState(JSON.stringify(e.input??{},null,2)),[f,y]=K.useState(void 0),w=a.config.user?.id??"guest",_=e.requiresUserAction;K.useEffect(()=>{l||(h(JSON.stringify(e.input??{},null,2)),y(void 0))},[e.id,e.input,l]);const k=()=>{h(JSON.stringify(e.input??{},null,2)),y(void 0),u(!0)},v=()=>{h(JSON.stringify(e.input??{},null,2)),y(void 0),u(!1)},M=async()=>{if(!(!a.transport.updateToolCall||d||o)){y(void 0),p(!0);try{const x=JSON.parse(m);if(!x||typeof x!="object"||Array.isArray(x))throw new Error("Tool input must be a JSON object.");const $=await a.transport.updateToolCall({chatId:n,messageId:t,toolCallId:e.id,input:x});i(n,[$]),u(!1)}catch(x){y(x instanceof Error?x.message:"Failed to update tool input.")}finally{p(!1)}}},S=async(x,$)=>{if(!(!e.approvalId||o||d||l)){s(!0);try{const H={chatId:n,messageId:t,approvalId:e.approvalId,approved:x,...$?{userResponse:$}:{},userId:w},C=await a.transport.streamMessage(H,L=>{L.type===exports.StreamChunkType.Message&&L.message&&i(n,[L.message])},{streamKey:n});C?i(C.id,C.messages):r()}catch(H){console.error("Failed to send approval:",H)}finally{s(!1)}}};return e.approved!==void 0?N.jsx(Q3,{call:e}):_?N.jsx(kwe,{callId:e.id,input:e.input,isSubmitting:o,onSubmit:x=>S(!0,x)}):N.jsxs("div",{className:"mp-agent-tool-approval-buttons",children:[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"}),l?N.jsxs("div",{className:"mp-agent-tool-input-actions",children:[N.jsx(xn,{icon:"Check",size:"sm",tooltip:"Save tool input",onClick:M,disabled:d||o,"aria-label":"Save tool input"}),N.jsx(xn,{icon:"X",size:"sm",tooltip:"Cancel input edit",onClick:v,disabled:d||o,"aria-label":"Cancel tool input edit"})]}):N.jsx(xn,{icon:"Pencil",size:"sm",tooltip:"Edit tool input",onClick:k,disabled:o||d,"aria-label":"Edit tool input"})]}),l?N.jsx("textarea",{className:"mp-agent-tool-input-editor",value:m,onChange:x=>{h(x.target.value),f&&y(void 0)},rows:8,spellCheck:!1,disabled:d||o}):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:()=>S(!0),disabled:o||l||d,children:o?"Processing...":"Approve"}),N.jsx("button",{className:"mp-agent-tool-deny-button",onClick:()=>S(!1),disabled:o||d,children:o?"Processing...":"Deny"})]})]})},z2=({call:e,messageId:t,chatId:n})=>{const r=nt(),a=xe(l=>l.upsertChat),i=e.requiresConfirmation&&e.approvalId&&e.approved===void 0,o=e.requiresConfirmation&&e.approvalId&&e.approved!==void 0,s=async()=>{try{const l=await r.transport.getChat(n);a(l)}catch(l){console.error("Failed to refresh chat after approval:",l)}};return!i&&!o?null:N.jsxs("div",{className:"mp-agent-tool-approval",children:[i&&N.jsx(vwe,{call:e,messageId:t,chatId:n,onApprovalSent:s}),o&&N.jsx(Q3,{call:e})]})},_we=({call:e,contextKey:t,messageId:n,chatId:r})=>{const a=nt(),i=K.useMemo(()=>a.getToolRenderer(e),[a,e]);return i?N.jsxs("div",{className:"mp-agent-tool-panel",children:[N.jsx(i,{call:e,contextKey:t,chatId:r}),N.jsx(z2,{call:e,messageId:n,chatId:r}),N.jsx(D2,{call:e})]}):N.jsxs("div",{className:"mp-agent-tool-panel",children:[N.jsx(ywe,{call:e}),N.jsx(z2,{call:e,messageId:n,chatId:r}),N.jsx(D2,{call:e})]})},J3=K.memo(({role:e,isGrouped:t})=>{if(t)return N.jsx("div",{className:"mp-agent-message-avatar-spacer"});const n=e===exports.MessageRole.User,r=n?"You":"AI";return N.jsx("div",{className:`mp-agent-message-avatar ${n?"mp-agent-message-avatar-user":""}`,children:N.jsx("div",{className:"mp-agent-message-avatar-icon",children:r})})});J3.displayName="MessageAvatar";const wwe=e=>e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"}):"",ev=K.memo(({role:e,createdAt:t,isGrouped:n})=>{if(n)return null;const a=e===exports.MessageRole.User?"You":"Assistant";return N.jsxs("div",{className:"mp-agent-message-header",children:[N.jsx("span",{className:"mp-agent-message-role",children:a}),N.jsx("span",{className:"mp-agent-message-time",children:wwe(t)})]})});ev.displayName="MessageHeader";function $2(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 xwe(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const Ewe=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Mwe=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Swe={};function F2(e,t){return(Swe.jsx?Mwe:Ewe).test(e)}const Nwe=/[ \t\n\f\r]/g;function Awe(e){return typeof e=="object"?e.type==="text"?P2(e.value):!1:P2(e)}function P2(e){return e.replace(Nwe,"")===""}let Ka=class{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}};Ka.prototype.normal={};Ka.prototype.property={};Ka.prototype.space=void 0;function tv(e,t){const n={},r={};for(const a of e)Object.assign(n,a.property),Object.assign(r,a.normal);return new Ka(n,r,t)}function Da(e){return e.toLowerCase()}let Yt=class{constructor(t,n){this.attribute=n,this.property=t}};Yt.prototype.attribute="";Yt.prototype.booleanish=!1;Yt.prototype.boolean=!1;Yt.prototype.commaOrSpaceSeparated=!1;Yt.prototype.commaSeparated=!1;Yt.prototype.defined=!1;Yt.prototype.mustUseProperty=!1;Yt.prototype.number=!1;Yt.prototype.overloadedBoolean=!1;Yt.prototype.property="";Yt.prototype.spaceSeparated=!1;Yt.prototype.space=void 0;let Twe=0;const $e=Ir(),kt=Ir(),Ed=Ir(),ce=Ir(),st=Ir(),Jr=Ir(),Jt=Ir();function Ir(){return 2**++Twe}const Md=Object.freeze(Object.defineProperty({__proto__:null,boolean:$e,booleanish:kt,commaOrSpaceSeparated:Jt,commaSeparated:Jr,number:ce,overloadedBoolean:Ed,spaceSeparated:st},Symbol.toStringTag,{value:"Module"})),bs=Object.keys(Md);let Ep=class extends Yt{constructor(t,n,r,a){let i=-1;if(super(t,n),q2(this,"space",a),typeof r=="number")for(;++i<bs.length;){const o=bs[i];q2(this,bs[i],(r&Md[o])===Md[o])}}};Ep.prototype.defined=!0;function q2(e,t,n){n&&(e[t]=n)}function sa(e){const t={},n={};for(const[r,a]of Object.entries(e.properties)){const i=new Ep(r,e.transform(e.attributes||{},r),a,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(i.mustUseProperty=!0),t[r]=i,n[Da(r)]=r,n[Da(i.attribute)]=r}return new Ka(t,n,e.space)}const nv=sa({properties:{ariaActiveDescendant:null,ariaAtomic:kt,ariaAutoComplete:null,ariaBusy:kt,ariaChecked:kt,ariaColCount:ce,ariaColIndex:ce,ariaColSpan:ce,ariaControls:st,ariaCurrent:null,ariaDescribedBy:st,ariaDetails:null,ariaDisabled:kt,ariaDropEffect:st,ariaErrorMessage:null,ariaExpanded:kt,ariaFlowTo:st,ariaGrabbed:kt,ariaHasPopup:null,ariaHidden:kt,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:st,ariaLevel:ce,ariaLive:null,ariaModal:kt,ariaMultiLine:kt,ariaMultiSelectable:kt,ariaOrientation:null,ariaOwns:st,ariaPlaceholder:null,ariaPosInSet:ce,ariaPressed:kt,ariaReadOnly:kt,ariaRelevant:null,ariaRequired:kt,ariaRoleDescription:st,ariaRowCount:ce,ariaRowIndex:ce,ariaRowSpan:ce,ariaSelected:kt,ariaSetSize:ce,ariaSort:null,ariaValueMax:ce,ariaValueMin:ce,ariaValueNow:ce,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function rv(e,t){return t in e?e[t]:t}function av(e,t){return rv(e,t.toLowerCase())}const Cwe=sa({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Jr,acceptCharset:st,accessKey:st,action:null,allow:null,allowFullScreen:$e,allowPaymentRequest:$e,allowUserMedia:$e,alt:null,as:null,async:$e,autoCapitalize:null,autoComplete:st,autoFocus:$e,autoPlay:$e,blocking:st,capture:null,charSet:null,checked:$e,cite:null,className:st,cols:ce,colSpan:null,content:null,contentEditable:kt,controls:$e,controlsList:st,coords:ce|Jr,crossOrigin:null,data:null,dateTime:null,decoding:null,default:$e,defer:$e,dir:null,dirName:null,disabled:$e,download:Ed,draggable:kt,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:$e,formTarget:null,headers:st,height:ce,hidden:Ed,high:ce,href:null,hrefLang:null,htmlFor:st,httpEquiv:st,id:null,imageSizes:null,imageSrcSet:null,inert:$e,inputMode:null,integrity:null,is:null,isMap:$e,itemId:null,itemProp:st,itemRef:st,itemScope:$e,itemType:st,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:$e,low:ce,manifest:null,max:null,maxLength:ce,media:null,method:null,min:null,minLength:ce,multiple:$e,muted:$e,name:null,nonce:null,noModule:$e,noValidate:$e,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:$e,optimum:ce,pattern:null,ping:st,placeholder:null,playsInline:$e,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:$e,referrerPolicy:null,rel:st,required:$e,reversed:$e,rows:ce,rowSpan:ce,sandbox:st,scope:null,scoped:$e,seamless:$e,selected:$e,shadowRootClonable:$e,shadowRootDelegatesFocus:$e,shadowRootMode:null,shape:null,size:ce,sizes:null,slot:null,span:ce,spellCheck:kt,src:null,srcDoc:null,srcLang:null,srcSet:null,start:ce,step:null,style:null,tabIndex:ce,target:null,title:null,translate:null,type:null,typeMustMatch:$e,useMap:null,value:kt,width:ce,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:st,axis:null,background:null,bgColor:null,border:ce,borderColor:null,bottomMargin:ce,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:$e,declare:$e,event:null,face:null,frame:null,frameBorder:null,hSpace:ce,leftMargin:ce,link:null,longDesc:null,lowSrc:null,marginHeight:ce,marginWidth:ce,noResize:$e,noHref:$e,noShade:$e,noWrap:$e,object:null,profile:null,prompt:null,rev:null,rightMargin:ce,rules:null,scheme:null,scrolling:kt,standby:null,summary:null,text:null,topMargin:ce,valueType:null,version:null,vAlign:null,vLink:null,vSpace:ce,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:$e,disableRemotePlayback:$e,prefix:null,property:null,results:ce,security:null,unselectable:null},space:"html",transform:av}),Rwe=sa({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:Jt,accentHeight:ce,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:ce,amplitude:ce,arabicForm:null,ascent:ce,attributeName:null,attributeType:null,azimuth:ce,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:ce,by:null,calcMode:null,capHeight:ce,className:st,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:ce,diffuseConstant:ce,direction:null,display:null,dur:null,divisor:ce,dominantBaseline:null,download:$e,dx:null,dy:null,edgeMode:null,editable:null,elevation:ce,enableBackground:null,end:null,event:null,exponent:ce,externalResourcesRequired:null,fill:null,fillOpacity:ce,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:Jr,g2:Jr,glyphName:Jr,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:ce,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:ce,horizOriginX:ce,horizOriginY:ce,id:null,ideographic:ce,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:ce,k:ce,k1:ce,k2:ce,k3:ce,k4:ce,kernelMatrix:Jt,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:ce,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:ce,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:ce,overlineThickness:ce,paintOrder:null,panose1:null,path:null,pathLength:ce,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:st,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:ce,pointsAtY:ce,pointsAtZ:ce,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Jt,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Jt,rev:Jt,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Jt,requiredFeatures:Jt,requiredFonts:Jt,requiredFormats:Jt,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:ce,specularExponent:ce,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:ce,strikethroughThickness:ce,string:null,stroke:null,strokeDashArray:Jt,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:ce,strokeOpacity:ce,strokeWidth:null,style:null,surfaceScale:ce,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Jt,tabIndex:ce,tableValues:null,target:null,targetX:ce,targetY:ce,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Jt,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:ce,underlineThickness:ce,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:ce,values:null,vAlphabetic:ce,vMathematical:ce,vectorEffect:null,vHanging:ce,vIdeographic:ce,version:null,vertAdvY:ce,vertOriginX:ce,vertOriginY:ce,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:ce,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:rv}),iv=sa({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()}}),ov=sa({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:av}),sv=sa({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),Iwe={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"},Owe=/[A-Z]/g,B2=/-[a-z]/g,Lwe=/^data[-\w.:]+$/i;function lv(e,t){const n=Da(t);let r=t,a=Yt;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&Lwe.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(B2,zwe);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!B2.test(i)){let o=i.replace(Owe,Dwe);o.charAt(0)!=="-"&&(o="-"+o),t="data"+o}}a=Ep}return new a(r,t)}function Dwe(e){return"-"+e.toLowerCase()}function zwe(e){return e.charAt(1).toUpperCase()}const cv=tv([nv,Cwe,iv,ov,sv],"html"),Ro=tv([nv,Rwe,iv,ov,sv],"svg");function U2(e){const t=String(e||"").trim();return t?t.split(/[ \t\n\r\f]+/g):[]}function $we(e){return e.join(" ").trim()}var Mp={},H2=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,Fwe=/\n/g,Pwe=/^\s*/,qwe=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,Bwe=/^:\s*/,Uwe=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,Hwe=/^[;\s]*/,jwe=/^\s+|\s+$/g,Vwe=`
|
|
8323
8323
|
`,j2="/",V2="*",Sr="",Gwe="comment",Wwe="declaration";function Kwe(e,t){if(typeof e!="string")throw new TypeError("First argument must be a string");if(!e)return[];t=t||{};var n=1,r=1;function a(f){var y=f.match(Fwe);y&&(n+=y.length);var w=f.lastIndexOf(Vwe);r=~w?f.length-w:r+f.length}function i(){var f={line:n,column:r};return function(y){return y.position=new o(f),u(),y}}function o(f){this.start=f,this.end={line:n,column:r},this.source=t.source}o.prototype.content=e;function s(f){var y=new Error(t.source+":"+n+":"+r+": "+f);if(y.reason=f,y.filename=t.source,y.line=n,y.column=r,y.source=e,!t.silent)throw y}function l(f){var y=f.exec(e);if(y){var w=y[0];return a(w),e=e.slice(w.length),y}}function u(){l(Pwe)}function d(f){var y;for(f=f||[];y=p();)y!==!1&&f.push(y);return f}function p(){var f=i();if(!(j2!=e.charAt(0)||V2!=e.charAt(1))){for(var y=2;Sr!=e.charAt(y)&&(V2!=e.charAt(y)||j2!=e.charAt(y+1));)++y;if(y+=2,Sr===e.charAt(y-1))return s("End of comment missing");var w=e.slice(2,y-2);return r+=2,a(w),e=e.slice(y),r+=2,f({type:Gwe,comment:w})}}function m(){var f=i(),y=l(qwe);if(y){if(p(),!l(Bwe))return s("property missing ':'");var w=l(Uwe),_=f({type:Wwe,property:G2(y[0].replace(H2,Sr)),value:w?G2(w[0].replace(H2,Sr)):Sr});return l(Hwe),_}}function h(){var f=[];d(f);for(var y;y=m();)y!==!1&&(f.push(y),d(f));return f}return u(),h()}function G2(e){return e?e.replace(jwe,Sr):Sr}var Ywe=Kwe,Zwe=hr&&hr.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Mp,"__esModule",{value:!0});Mp.default=Qwe;const Xwe=Zwe(Ywe);function Qwe(e,t){let n=null;if(!e||typeof e!="string")return n;const r=(0,Xwe.default)(e),a=typeof t=="function";return r.forEach(i=>{if(i.type!=="declaration")return;const{property:o,value:s}=i;a?t(o,s,i):s&&(n=n||{},n[o]=s)}),n}var Io={};Object.defineProperty(Io,"__esModule",{value:!0});Io.camelCase=void 0;var Jwe=/^--[a-zA-Z0-9_-]+$/,exe=/-([a-z])/g,txe=/^[^-]+$/,nxe=/^-(webkit|moz|ms|o|khtml)-/,rxe=/^-(ms)-/,axe=function(e){return!e||txe.test(e)||Jwe.test(e)},ixe=function(e,t){return t.toUpperCase()},W2=function(e,t){return"".concat(t,"-")},oxe=function(e,t){return t===void 0&&(t={}),axe(e)?e:(e=e.toLowerCase(),t.reactCompat?e=e.replace(rxe,W2):e=e.replace(nxe,W2),e.replace(exe,ixe))};Io.camelCase=oxe;var sxe=hr&&hr.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},lxe=sxe(Mp),cxe=Io;function Sd(e,t){var n={};return!e||typeof e!="string"||(0,lxe.default)(e,function(r,a){r&&a&&(n[(0,cxe.camelCase)(r,t)]=a)}),n}Sd.default=Sd;var uxe=Sd;const dxe=po(uxe),uv=dv("end"),Sp=dv("start");function dv(e){return t;function t(n){const r=n&&n.position&&n.position[e]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function pxe(e){const t=Sp(e),n=uv(e);if(t&&n)return{start:t,end:n}}function Sa(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?K2(e.position):"start"in e||"end"in e?K2(e):"line"in e||"column"in e?Nd(e):""}function Nd(e){return Y2(e&&e.line)+":"+Y2(e&&e.column)}function K2(e){return Nd(e&&e.start)+"-"+Nd(e&&e.end)}function Y2(e){return e&&typeof e=="number"?e:1}class Lt extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let a="",i={},o=!1;if(n&&("line"in n&&"column"in n?i={place:n}:"start"in n&&"end"in n?i={place:n}:"type"in n?i={ancestors:[n],place:n.position}:i={...n}),typeof t=="string"?a=t:!i.cause&&t&&(o=!0,a=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof r=="string"){const l=r.indexOf(":");l===-1?i.ruleId=r:(i.source=r.slice(0,l),i.ruleId=r.slice(l+1))}if(!i.place&&i.ancestors&&i.ancestors){const l=i.ancestors[i.ancestors.length-1];l&&(i.place=l.position)}const s=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=s?s.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=s?s.line:void 0,this.name=Sa(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=o&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Lt.prototype.file="";Lt.prototype.name="";Lt.prototype.reason="";Lt.prototype.message="";Lt.prototype.stack="";Lt.prototype.column=void 0;Lt.prototype.line=void 0;Lt.prototype.ancestors=void 0;Lt.prototype.cause=void 0;Lt.prototype.fatal=void 0;Lt.prototype.place=void 0;Lt.prototype.ruleId=void 0;Lt.prototype.source=void 0;const Np={}.hasOwnProperty,hxe=new Map,mxe=/[A-Z]/g,fxe=new Set(["table","tbody","thead","tfoot","tr"]),gxe=new Set(["td","th"]),pv="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function yxe(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=Mxe(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=Exe(n,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?Ro:cv,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=hv(a,e,void 0);return i&&typeof i!="string"?i:a.create(e,a.Fragment,{children:i||void 0},void 0)}function hv(e,t,n){if(t.type==="element")return bxe(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return kxe(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return _xe(e,t,n);if(t.type==="mdxjsEsm")return vxe(e,t);if(t.type==="root")return wxe(e,t,n);if(t.type==="text")return xxe(e,t)}function bxe(e,t,n){const r=e.schema;let a=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(a=Ro,e.schema=a),e.ancestors.push(t);const i=fv(e,t.tagName,!1),o=Sxe(e,t);let s=Tp(e,t);return fxe.has(t.tagName)&&(s=s.filter(function(l){return typeof l=="string"?!Awe(l):!0})),mv(e,o,i,t),Ap(o,s),e.ancestors.pop(),e.schema=r,e.create(t,i,o,n)}function kxe(e,t){if(t.data&&t.data.estree&&e.evaluater){const r=t.data.estree.body[0];return r.type,e.evaluater.evaluateExpression(r.expression)}za(e,t.position)}function vxe(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);za(e,t.position)}function _xe(e,t,n){const r=e.schema;let a=r;t.name==="svg"&&r.space==="html"&&(a=Ro,e.schema=a),e.ancestors.push(t);const i=t.name===null?e.Fragment:fv(e,t.name,!0),o=Nxe(e,t),s=Tp(e,t);return mv(e,o,i,t),Ap(o,s),e.ancestors.pop(),e.schema=r,e.create(t,i,o,n)}function wxe(e,t,n){const r={};return Ap(r,Tp(e,t)),e.create(t,e.Fragment,r,n)}function xxe(e,t){return t.value}function mv(e,t,n,r){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=r)}function Ap(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function Exe(e,t,n){return r;function r(a,i,o,s){const u=Array.isArray(o.children)?n:t;return s?u(i,o,s):u(i,o)}}function Mxe(e,t){return n;function n(r,a,i,o){const s=Array.isArray(i.children),l=Sp(r);return t(a,i,o,s,{columnNumber:l?l.column-1:void 0,fileName:e,lineNumber:l?l.line:void 0},void 0)}}function Sxe(e,t){const n={};let r,a;for(a in t.properties)if(a!=="children"&&Np.call(t.properties,a)){const i=Axe(e,a,t.properties[a]);if(i){const[o,s]=i;e.tableCellAlignToStyle&&o==="align"&&typeof s=="string"&&gxe.has(t.tagName)?r=s:n[o]=s}}if(r){const i=n.style||(n.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function Nxe(e,t){const n={};for(const r of t.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&e.evaluater){const i=r.data.estree.body[0];i.type;const o=i.expression;o.type;const s=o.properties[0];s.type,Object.assign(n,e.evaluater.evaluateExpression(s.argument))}else za(e,t.position);else{const a=r.name;let i;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&e.evaluater){const s=r.value.data.estree.body[0];s.type,i=e.evaluater.evaluateExpression(s.expression)}else za(e,t.position);else i=r.value===null?!0:r.value;n[a]=i}return n}function Tp(e,t){const n=[];let r=-1;const a=e.passKeys?new Map:hxe;for(;++r<t.children.length;){const i=t.children[r];let o;if(e.passKeys){const l=i.type==="element"?i.tagName:i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement"?i.name:void 0;if(l){const u=a.get(l)||0;o=l+"-"+u,a.set(l,u+1)}}const s=hv(e,i,o);s!==void 0&&n.push(s)}return n}function Axe(e,t,n){const r=lv(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=r.commaSeparated?xwe(n):$we(n)),r.property==="style"){let a=typeof n=="object"?n:Txe(e,String(n));return e.stylePropertyNameCase==="css"&&(a=Cxe(a)),["style",a]}return[e.elementAttributeNameCase==="react"&&r.space?Iwe[r.property]||r.property:r.attribute,n]}}function Txe(e,t){try{return dxe(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const r=n,a=new Lt("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:r,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw a.file=e.filePath||void 0,a.url=pv+"#cannot-parse-style-attribute",a}}function fv(e,t,n){let r;if(!n)r={type:"Literal",value:t};else if(t.includes(".")){const a=t.split(".");let i=-1,o;for(;++i<a.length;){const s=F2(a[i])?{type:"Identifier",name:a[i]}:{type:"Literal",value:a[i]};o=o?{type:"MemberExpression",object:o,property:s,computed:!!(i&&s.type==="Literal"),optional:!1}:s}r=o}else r=F2(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(r.type==="Literal"){const a=r.value;return Np.call(e.components,a)?e.components[a]:a}if(e.evaluater)return e.evaluater.evaluateExpression(r);za(e)}function za(e,t){const n=new Lt("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw n.file=e.filePath||void 0,n.url=pv+"#cannot-handle-mdx-estrees-without-createevaluater",n}function Cxe(e){const t={};let n;for(n in e)Np.call(e,n)&&(t[Rxe(n)]=e[n]);return t}function Rxe(e){let t=e.replace(mxe,Ixe);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function Ixe(e){return"-"+e.toLowerCase()}const ks={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},Oxe={};function Cp(e,t){const n=Oxe,r=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,a=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return gv(e,r,a)}function gv(e,t,n){if(Lxe(e)){if("value"in e)return e.type==="html"&&!n?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return Z2(e.children,t,n)}return Array.isArray(e)?Z2(e,t,n):""}function Z2(e,t,n){const r=[];let a=-1;for(;++a<e.length;)r[a]=gv(e[a],t,n);return r.join("")}function Lxe(e){return!!(e&&typeof e=="object")}const X2=document.createElement("i");function $a(e){const t="&"+e+";";X2.innerHTML=t;const n=X2.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function nn(e,t,n,r){const a=e.length;let i=0,o;if(t<0?t=-t>a?0:a+t:t=t>a?a:t,n=n>0?n:0,r.length<1e4)o=Array.from(r),o.unshift(t,n),e.splice(...o);else for(n&&e.splice(t,n);i<r.length;)o=r.slice(i,i+1e4),o.unshift(t,0),e.splice(...o),i+=1e4,t+=1e4}function un(e,t){return e.length>0?(nn(e,e.length,0,t),e):t}const Q2={}.hasOwnProperty;function yv(e){const t={};let n=-1;for(;++n<e.length;)Dxe(t,e[n]);return t}function Dxe(e,t){let n;for(n in t){const a=(Q2.call(e,n)?e[n]:void 0)||(e[n]={}),i=t[n];let o;if(i)for(o in i){Q2.call(a,o)||(a[o]=[]);const s=i[o];zxe(a[o],Array.isArray(s)?s:s?[s]:[])}}}function zxe(e,t){let n=-1;const r=[];for(;++n<t.length;)(t[n].add==="after"?e:r).push(t[n]);nn(e,0,0,r)}function bv(e,t){const n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function En(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Pt=br(/[A-Za-z]/),It=br(/[\dA-Za-z]/),$xe=br(/[#-'*+\--9=?A-Z^-~]/);function Qi(e){return e!==null&&(e<32||e===127)}const Ad=br(/\d/),Fxe=br(/[\dA-Fa-f]/),Pxe=br(/[!-/:-@[-`{-~]/);function me(e){return e!==null&&e<-2}function Ye(e){return e!==null&&(e<0||e===32)}function qe(e){return e===-2||e===-1||e===32}const mr=br(/\p{P}|\p{S}/u),Mn=br(/\s/);function br(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function la(e){const t=[];let n=-1,r=0,a=0;for(;++n<e.length;){const i=e.charCodeAt(n);let o="";if(i===37&&It(e.charCodeAt(n+1))&&It(e.charCodeAt(n+2)))a=2;else if(i<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(i))||(o=String.fromCharCode(i));else if(i>55295&&i<57344){const s=e.charCodeAt(n+1);i<56320&&s>56319&&s<57344?(o=String.fromCharCode(i,s),a=1):o="�"}else o=String.fromCharCode(i);o&&(t.push(e.slice(r,n),encodeURIComponent(o)),r=n+a+1,o=""),a&&(n+=a,a=0)}return t.join("")+e.slice(r)}function De(e,t,n,r){const a=r?r-1:Number.POSITIVE_INFINITY;let i=0;return o;function o(l){return qe(l)?(e.enter(n),s(l)):t(l)}function s(l){return qe(l)&&i++<a?(e.consume(l),s):(e.exit(n),t(l))}}const qxe={tokenize:Bxe};function Bxe(e){const t=e.attempt(this.parser.constructs.contentInitial,r,a);let n;return t;function r(s){if(s===null){e.consume(s);return}return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),De(e,t,"linePrefix")}function a(s){return e.enter("paragraph"),i(s)}function i(s){const l=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=l),n=l,o(s)}function o(s){if(s===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(s);return}return me(s)?(e.consume(s),e.exit("chunkText"),i):(e.consume(s),o)}}const Uxe={tokenize:Hxe},J2={tokenize:jxe};function Hxe(e){const t=this,n=[];let r=0,a,i,o;return s;function s(v){if(r<n.length){const M=n[r];return t.containerState=M[1],e.attempt(M[0].continuation,l,u)(v)}return u(v)}function l(v){if(r++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,a&&k();const M=t.events.length;let S=M,x;for(;S--;)if(t.events[S][0]==="exit"&&t.events[S][1].type==="chunkFlow"){x=t.events[S][1].end;break}_(r);let $=M;for(;$<t.events.length;)t.events[$][1].end={...x},$++;return nn(t.events,S+1,0,t.events.slice(M)),t.events.length=$,u(v)}return s(v)}function u(v){if(r===n.length){if(!a)return m(v);if(a.currentConstruct&&a.currentConstruct.concrete)return f(v);t.interrupt=!!(a.currentConstruct&&!a._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(J2,d,p)(v)}function d(v){return a&&k(),_(r),m(v)}function p(v){return t.parser.lazy[t.now().line]=r!==n.length,o=t.now().offset,f(v)}function m(v){return t.containerState={},e.attempt(J2,h,f)(v)}function h(v){return r++,n.push([t.currentConstruct,t.containerState]),m(v)}function f(v){if(v===null){a&&k(),_(0),e.consume(v);return}return a=a||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:a,contentType:"flow",previous:i}),y(v)}function y(v){if(v===null){w(e.exit("chunkFlow"),!0),_(0),e.consume(v);return}return me(v)?(e.consume(v),w(e.exit("chunkFlow")),r=0,t.interrupt=void 0,s):(e.consume(v),y)}function w(v,M){const S=t.sliceStream(v);if(M&&S.push(null),v.previous=i,i&&(i.next=v),i=v,a.defineSkip(v.start),a.write(S),t.parser.lazy[v.start.line]){let x=a.events.length;for(;x--;)if(a.events[x][1].start.offset<o&&(!a.events[x][1].end||a.events[x][1].end.offset>o))return;const $=t.events.length;let H=$,C,L;for(;H--;)if(t.events[H][0]==="exit"&&t.events[H][1].type==="chunkFlow"){if(C){L=t.events[H][1].end;break}C=!0}for(_(r),x=$;x<t.events.length;)t.events[x][1].end={...L},x++;nn(t.events,H+1,0,t.events.slice($)),t.events.length=x}}function _(v){let M=n.length;for(;M-- >v;){const S=n[M];t.containerState=S[1],S[0].exit.call(t,e)}n.length=v}function k(){a.write([null]),i=void 0,a=void 0,t.containerState._closeFlow=void 0}}function jxe(e,t,n){return De(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function na(e){if(e===null||Ye(e)||Mn(e))return 1;if(mr(e))return 2}function Oo(e,t,n){const r=[];let a=-1;for(;++a<e.length;){const i=e[a].resolveAll;i&&!r.includes(i)&&(t=i(t,n),r.push(i))}return t}const Td={name:"attention",resolveAll:Vxe,tokenize:Gxe};function Vxe(e,t){let n=-1,r,a,i,o,s,l,u,d;for(;++n<e.length;)if(e[n][0]==="enter"&&e[n][1].type==="attentionSequence"&&e[n][1]._close){for(r=n;r--;)if(e[r][0]==="exit"&&e[r][1].type==="attentionSequence"&&e[r][1]._open&&t.sliceSerialize(e[r][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[r][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[r][1].end.offset-e[r][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;l=e[r][1].end.offset-e[r][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const p={...e[r][1].end},m={...e[n][1].start};em(p,-l),em(m,l),o={type:l>1?"strongSequence":"emphasisSequence",start:p,end:{...e[r][1].end}},s={type:l>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:m},i={type:l>1?"strongText":"emphasisText",start:{...e[r][1].end},end:{...e[n][1].start}},a={type:l>1?"strong":"emphasis",start:{...o.start},end:{...s.end}},e[r][1].end={...o.start},e[n][1].start={...s.end},u=[],e[r][1].end.offset-e[r][1].start.offset&&(u=un(u,[["enter",e[r][1],t],["exit",e[r][1],t]])),u=un(u,[["enter",a,t],["enter",o,t],["exit",o,t],["enter",i,t]]),u=un(u,Oo(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),u=un(u,[["exit",i,t],["enter",s,t],["exit",s,t],["exit",a,t]]),e[n][1].end.offset-e[n][1].start.offset?(d=2,u=un(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):d=0,nn(e,r-1,n-r+3,u),n=r+u.length-d-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function Gxe(e,t){const n=this.parser.constructs.attentionMarkers.null,r=this.previous,a=na(r);let i;return o;function o(l){return i=l,e.enter("attentionSequence"),s(l)}function s(l){if(l===i)return e.consume(l),s;const u=e.exit("attentionSequence"),d=na(l),p=!d||d===2&&a||n.includes(l),m=!a||a===2&&d||n.includes(r);return u._open=!!(i===42?p:p&&(a||!m)),u._close=!!(i===42?m:m&&(d||!p)),t(l)}}function em(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const Wxe={name:"autolink",tokenize:Kxe};function Kxe(e,t,n){let r=0;return a;function a(h){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),i}function i(h){return Pt(h)?(e.consume(h),o):h===64?n(h):u(h)}function o(h){return h===43||h===45||h===46||It(h)?(r=1,s(h)):u(h)}function s(h){return h===58?(e.consume(h),r=0,l):(h===43||h===45||h===46||It(h))&&r++<32?(e.consume(h),s):(r=0,u(h))}function l(h){return h===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),t):h===null||h===32||h===60||Qi(h)?n(h):(e.consume(h),l)}function u(h){return h===64?(e.consume(h),d):$xe(h)?(e.consume(h),u):n(h)}function d(h){return It(h)?p(h):n(h)}function p(h){return h===46?(e.consume(h),r=0,d):h===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),t):m(h)}function m(h){if((h===45||It(h))&&r++<63){const f=h===45?m:p;return e.consume(h),f}return n(h)}}const Ya={partial:!0,tokenize:Yxe};function Yxe(e,t,n){return r;function r(i){return qe(i)?De(e,a,"linePrefix")(i):a(i)}function a(i){return i===null||me(i)?t(i):n(i)}}const kv={continuation:{tokenize:Xxe},exit:Qxe,name:"blockQuote",tokenize:Zxe};function Zxe(e,t,n){const r=this;return a;function a(o){if(o===62){const s=r.containerState;return s.open||(e.enter("blockQuote",{_container:!0}),s.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(o),e.exit("blockQuoteMarker"),i}return n(o)}function i(o){return qe(o)?(e.enter("blockQuotePrefixWhitespace"),e.consume(o),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(o))}}function Xxe(e,t,n){const r=this;return a;function a(o){return qe(o)?De(e,i,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o):i(o)}function i(o){return e.attempt(kv,t,n)(o)}}function Qxe(e){e.exit("blockQuote")}const vv={name:"characterEscape",tokenize:Jxe};function Jxe(e,t,n){return r;function r(i){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(i),e.exit("escapeMarker"),a}function a(i){return Pxe(i)?(e.enter("characterEscapeValue"),e.consume(i),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(i)}}const _v={name:"characterReference",tokenize:e9e};function e9e(e,t,n){const r=this;let a=0,i,o;return s;function s(p){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(p),e.exit("characterReferenceMarker"),l}function l(p){return p===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(p),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),i=31,o=It,d(p))}function u(p){return p===88||p===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(p),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),i=6,o=Fxe,d):(e.enter("characterReferenceValue"),i=7,o=Ad,d(p))}function d(p){if(p===59&&a){const m=e.exit("characterReferenceValue");return o===It&&!$a(r.sliceSerialize(m))?n(p):(e.enter("characterReferenceMarker"),e.consume(p),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return o(p)&&a++<i?(e.consume(p),d):n(p)}}const tm={partial:!0,tokenize:n9e},nm={concrete:!0,name:"codeFenced",tokenize:t9e};function t9e(e,t,n){const r=this,a={partial:!0,tokenize:S};let i=0,o=0,s;return l;function l(x){return u(x)}function u(x){const $=r.events[r.events.length-1];return i=$&&$[1].type==="linePrefix"?$[2].sliceSerialize($[1],!0).length:0,s=x,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),d(x)}function d(x){return x===s?(o++,e.consume(x),d):o<3?n(x):(e.exit("codeFencedFenceSequence"),qe(x)?De(e,p,"whitespace")(x):p(x))}function p(x){return x===null||me(x)?(e.exit("codeFencedFence"),r.interrupt?t(x):e.check(tm,y,M)(x)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),m(x))}function m(x){return x===null||me(x)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),p(x)):qe(x)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),De(e,h,"whitespace")(x)):x===96&&x===s?n(x):(e.consume(x),m)}function h(x){return x===null||me(x)?p(x):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),f(x))}function f(x){return x===null||me(x)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),p(x)):x===96&&x===s?n(x):(e.consume(x),f)}function y(x){return e.attempt(a,M,w)(x)}function w(x){return e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),_}function _(x){return i>0&&qe(x)?De(e,k,"linePrefix",i+1)(x):k(x)}function k(x){return x===null||me(x)?e.check(tm,y,M)(x):(e.enter("codeFlowValue"),v(x))}function v(x){return x===null||me(x)?(e.exit("codeFlowValue"),k(x)):(e.consume(x),v)}function M(x){return e.exit("codeFenced"),t(x)}function S(x,$,H){let C=0;return L;function L(R){return x.enter("lineEnding"),x.consume(R),x.exit("lineEnding"),W}function W(R){return x.enter("codeFencedFence"),qe(R)?De(x,Z,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(R):Z(R)}function Z(R){return R===s?(x.enter("codeFencedFenceSequence"),ee(R)):H(R)}function ee(R){return R===s?(C++,x.consume(R),ee):C>=o?(x.exit("codeFencedFenceSequence"),qe(R)?De(x,G,"whitespace")(R):G(R)):H(R)}function G(R){return R===null||me(R)?(x.exit("codeFencedFence"),$(R)):H(R)}}}function n9e(e,t,n){const r=this;return a;function a(o){return o===null?n(o):(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),i)}function i(o){return r.parser.lazy[r.now().line]?n(o):t(o)}}const vs={name:"codeIndented",tokenize:a9e},r9e={partial:!0,tokenize:i9e};function a9e(e,t,n){const r=this;return a;function a(u){return e.enter("codeIndented"),De(e,i,"linePrefix",5)(u)}function i(u){const d=r.events[r.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?o(u):n(u)}function o(u){return u===null?l(u):me(u)?e.attempt(r9e,o,l)(u):(e.enter("codeFlowValue"),s(u))}function s(u){return u===null||me(u)?(e.exit("codeFlowValue"),o(u)):(e.consume(u),s)}function l(u){return e.exit("codeIndented"),t(u)}}function i9e(e,t,n){const r=this;return a;function a(o){return r.parser.lazy[r.now().line]?n(o):me(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),a):De(e,i,"linePrefix",5)(o)}function i(o){const s=r.events[r.events.length-1];return s&&s[1].type==="linePrefix"&&s[2].sliceSerialize(s[1],!0).length>=4?t(o):me(o)?a(o):n(o)}}const o9e={name:"codeText",previous:l9e,resolve:s9e,tokenize:c9e};function s9e(e){let t=e.length-4,n=3,r,a;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r<t;)if(e[r][1].type==="codeTextData"){e[n][1].type="codeTextPadding",e[t][1].type="codeTextPadding",n+=2,t-=2;break}}for(r=n-1,t++;++r<=t;)a===void 0?r!==t&&e[r][1].type!=="lineEnding"&&(a=r):(r===t||e[r][1].type==="lineEnding")&&(e[a][1].type="codeTextData",r!==a+2&&(e[a][1].end=e[r-1][1].end,e.splice(a+2,r-a-2),t-=r-a-2,r=a+2),a=void 0);return e}function l9e(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function c9e(e,t,n){let r=0,a,i;return o;function o(p){return e.enter("codeText"),e.enter("codeTextSequence"),s(p)}function s(p){return p===96?(e.consume(p),r++,s):(e.exit("codeTextSequence"),l(p))}function l(p){return p===null?n(p):p===32?(e.enter("space"),e.consume(p),e.exit("space"),l):p===96?(i=e.enter("codeTextSequence"),a=0,d(p)):me(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),l):(e.enter("codeTextData"),u(p))}function u(p){return p===null||p===32||p===96||me(p)?(e.exit("codeTextData"),l(p)):(e.consume(p),u)}function d(p){return p===96?(e.consume(p),a++,d):a===r?(e.exit("codeTextSequence"),e.exit("codeText"),t(p)):(i.type="codeTextData",u(p))}}class u9e{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,n){const r=n??Number.POSITIVE_INFINITY;return r<this.left.length?this.left.slice(t,r):t>this.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){const a=n||0;this.setCursor(Math.trunc(t));const i=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return r&&fa(this.left,r),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),fa(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),fa(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const n=this.left.splice(t,Number.POSITIVE_INFINITY);fa(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);fa(this.left,n.reverse())}}}function fa(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function wv(e){const t={};let n=-1,r,a,i,o,s,l,u;const d=new u9e(e);for(;++n<d.length;){for(;n in t;)n=t[n];if(r=d.get(n),n&&r[1].type==="chunkFlow"&&d.get(n-1)[1].type==="listItemPrefix"&&(l=r[1]._tokenizer.events,i=0,i<l.length&&l[i][1].type==="lineEndingBlank"&&(i+=2),i<l.length&&l[i][1].type==="content"))for(;++i<l.length&&l[i][1].type!=="content";)l[i][1].type==="chunkText"&&(l[i][1]._isInFirstContentOfListItem=!0,i++);if(r[0]==="enter")r[1].contentType&&(Object.assign(t,d9e(d,n)),n=t[n],u=!0);else if(r[1]._container){for(i=n,a=void 0;i--;)if(o=d.get(i),o[1].type==="lineEnding"||o[1].type==="lineEndingBlank")o[0]==="enter"&&(a&&(d.get(a)[1].type="lineEndingBlank"),o[1].type="lineEnding",a=i);else if(!(o[1].type==="linePrefix"||o[1].type==="listItemIndent"))break;a&&(r[1].end={...d.get(a)[1].start},s=d.slice(a,n),s.unshift(r),d.splice(a,n-a+1,s))}}return nn(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!u}function d9e(e,t){const n=e.get(t)[1],r=e.get(t)[2];let a=t-1;const i=[];let o=n._tokenizer;o||(o=r.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(o._contentTypeTextTrailing=!0));const s=o.events,l=[],u={};let d,p,m=-1,h=n,f=0,y=0;const w=[y];for(;h;){for(;e.get(++a)[1]!==h;);i.push(a),h._tokenizer||(d=r.sliceStream(h),h.next||d.push(null),p&&o.defineSkip(h.start),h._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(d),h._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),p=h,h=h.next}for(h=n;++m<s.length;)s[m][0]==="exit"&&s[m-1][0]==="enter"&&s[m][1].type===s[m-1][1].type&&s[m][1].start.line!==s[m][1].end.line&&(y=m+1,w.push(y),h._tokenizer=void 0,h.previous=void 0,h=h.next);for(o.events=[],h?(h._tokenizer=void 0,h.previous=void 0):w.pop(),m=w.length;m--;){const _=s.slice(w[m],w[m+1]),k=i.pop();l.push([k,k+_.length-1]),e.splice(k,2,_)}for(l.reverse(),m=-1;++m<l.length;)u[f+l[m][0]]=f+l[m][1],f+=l[m][1]-l[m][0]-1;return u}const p9e={resolve:m9e,tokenize:f9e},h9e={partial:!0,tokenize:g9e};function m9e(e){return wv(e),e}function f9e(e,t){let n;return r;function r(s){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),a(s)}function a(s){return s===null?i(s):me(s)?e.check(h9e,o,i)(s):(e.consume(s),a)}function i(s){return e.exit("chunkContent"),e.exit("content"),t(s)}function o(s){return e.consume(s),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,a}}function g9e(e,t,n){const r=this;return a;function a(o){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),De(e,i,"linePrefix")}function i(o){if(o===null||me(o))return n(o);const s=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes("codeIndented")&&s&&s[1].type==="linePrefix"&&s[2].sliceSerialize(s[1],!0).length>=4?t(o):e.interrupt(r.parser.constructs.flow,n,t)(o)}}function xv(e,t,n,r,a,i,o,s,l){const u=l||Number.POSITIVE_INFINITY;let d=0;return p;function p(_){return _===60?(e.enter(r),e.enter(a),e.enter(i),e.consume(_),e.exit(i),m):_===null||_===32||_===41||Qi(_)?n(_):(e.enter(r),e.enter(o),e.enter(s),e.enter("chunkString",{contentType:"string"}),y(_))}function m(_){return _===62?(e.enter(i),e.consume(_),e.exit(i),e.exit(a),e.exit(r),t):(e.enter(s),e.enter("chunkString",{contentType:"string"}),h(_))}function h(_){return _===62?(e.exit("chunkString"),e.exit(s),m(_)):_===null||_===60||me(_)?n(_):(e.consume(_),_===92?f:h)}function f(_){return _===60||_===62||_===92?(e.consume(_),h):h(_)}function y(_){return!d&&(_===null||_===41||Ye(_))?(e.exit("chunkString"),e.exit(s),e.exit(o),e.exit(r),t(_)):d<u&&_===40?(e.consume(_),d++,y):_===41?(e.consume(_),d--,y):_===null||_===32||_===40||Qi(_)?n(_):(e.consume(_),_===92?w:y)}function w(_){return _===40||_===41||_===92?(e.consume(_),y):y(_)}}function Ev(e,t,n,r,a,i){const o=this;let s=0,l;return u;function u(h){return e.enter(r),e.enter(a),e.consume(h),e.exit(a),e.enter(i),d}function d(h){return s>999||h===null||h===91||h===93&&!l||h===94&&!s&&"_hiddenFootnoteSupport"in o.parser.constructs?n(h):h===93?(e.exit(i),e.enter(a),e.consume(h),e.exit(a),e.exit(r),t):me(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),d):(e.enter("chunkString",{contentType:"string"}),p(h))}function p(h){return h===null||h===91||h===93||me(h)||s++>999?(e.exit("chunkString"),d(h)):(e.consume(h),l||(l=!qe(h)),h===92?m:p)}function m(h){return h===91||h===92||h===93?(e.consume(h),s++,p):p(h)}}function Mv(e,t,n,r,a,i){let o;return s;function s(m){return m===34||m===39||m===40?(e.enter(r),e.enter(a),e.consume(m),e.exit(a),o=m===40?41:m,l):n(m)}function l(m){return m===o?(e.enter(a),e.consume(m),e.exit(a),e.exit(r),t):(e.enter(i),u(m))}function u(m){return m===o?(e.exit(i),l(o)):m===null?n(m):me(m)?(e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),De(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),d(m))}function d(m){return m===o||m===null||me(m)?(e.exit("chunkString"),u(m)):(e.consume(m),m===92?p:d)}function p(m){return m===o||m===92?(e.consume(m),d):d(m)}}function Kn(e,t){let n;return r;function r(a){return me(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),n=!0,r):qe(a)?De(e,r,n?"linePrefix":"lineSuffix")(a):t(a)}}const y9e={name:"definition",tokenize:k9e},b9e={partial:!0,tokenize:v9e};function k9e(e,t,n){const r=this;let a;return i;function i(h){return e.enter("definition"),o(h)}function o(h){return Ev.call(r,e,s,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(h)}function s(h){return a=En(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),h===58?(e.enter("definitionMarker"),e.consume(h),e.exit("definitionMarker"),l):n(h)}function l(h){return Ye(h)?Kn(e,u)(h):u(h)}function u(h){return xv(e,d,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(h)}function d(h){return e.attempt(b9e,p,p)(h)}function p(h){return qe(h)?De(e,m,"whitespace")(h):m(h)}function m(h){return h===null||me(h)?(e.exit("definition"),r.parser.defined.push(a),t(h)):n(h)}}function v9e(e,t,n){return r;function r(s){return Ye(s)?Kn(e,a)(s):n(s)}function a(s){return Mv(e,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(s)}function i(s){return qe(s)?De(e,o,"whitespace")(s):o(s)}function o(s){return s===null||me(s)?t(s):n(s)}}const _9e={name:"hardBreakEscape",tokenize:w9e};function w9e(e,t,n){return r;function r(i){return e.enter("hardBreakEscape"),e.consume(i),a}function a(i){return me(i)?(e.exit("hardBreakEscape"),t(i)):n(i)}}const x9e={name:"headingAtx",resolve:E9e,tokenize:M9e};function E9e(e,t){let n=e.length-2,r=3,a,i;return e[r][1].type==="whitespace"&&(r+=2),n-2>r&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&e[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(a={type:"atxHeadingText",start:e[r][1].start,end:e[n][1].end},i={type:"chunkText",start:e[r][1].start,end:e[n][1].end,contentType:"text"},nn(e,r,n-r+1,[["enter",a,t],["enter",i,t],["exit",i,t],["exit",a,t]])),e}function M9e(e,t,n){let r=0;return a;function a(d){return e.enter("atxHeading"),i(d)}function i(d){return e.enter("atxHeadingSequence"),o(d)}function o(d){return d===35&&r++<6?(e.consume(d),o):d===null||Ye(d)?(e.exit("atxHeadingSequence"),s(d)):n(d)}function s(d){return d===35?(e.enter("atxHeadingSequence"),l(d)):d===null||me(d)?(e.exit("atxHeading"),t(d)):qe(d)?De(e,s,"whitespace")(d):(e.enter("atxHeadingText"),u(d))}function l(d){return d===35?(e.consume(d),l):(e.exit("atxHeadingSequence"),s(d))}function u(d){return d===null||d===35||Ye(d)?(e.exit("atxHeadingText"),s(d)):(e.consume(d),u)}}const S9e=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],rm=["pre","script","style","textarea"],N9e={concrete:!0,name:"htmlFlow",resolveTo:C9e,tokenize:R9e},A9e={partial:!0,tokenize:O9e},T9e={partial:!0,tokenize:I9e};function C9e(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function R9e(e,t,n){const r=this;let a,i,o,s,l;return u;function u(O){return d(O)}function d(O){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(O),p}function p(O){return O===33?(e.consume(O),m):O===47?(e.consume(O),i=!0,y):O===63?(e.consume(O),a=3,r.interrupt?t:A):Pt(O)?(e.consume(O),o=String.fromCharCode(O),w):n(O)}function m(O){return O===45?(e.consume(O),a=2,h):O===91?(e.consume(O),a=5,s=0,f):Pt(O)?(e.consume(O),a=4,r.interrupt?t:A):n(O)}function h(O){return O===45?(e.consume(O),r.interrupt?t:A):n(O)}function f(O){const de="CDATA[";return O===de.charCodeAt(s++)?(e.consume(O),s===de.length?r.interrupt?t:Z:f):n(O)}function y(O){return Pt(O)?(e.consume(O),o=String.fromCharCode(O),w):n(O)}function w(O){if(O===null||O===47||O===62||Ye(O)){const de=O===47,ye=o.toLowerCase();return!de&&!i&&rm.includes(ye)?(a=1,r.interrupt?t(O):Z(O)):S9e.includes(o.toLowerCase())?(a=6,de?(e.consume(O),_):r.interrupt?t(O):Z(O)):(a=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(O):i?k(O):v(O))}return O===45||It(O)?(e.consume(O),o+=String.fromCharCode(O),w):n(O)}function _(O){return O===62?(e.consume(O),r.interrupt?t:Z):n(O)}function k(O){return qe(O)?(e.consume(O),k):L(O)}function v(O){return O===47?(e.consume(O),L):O===58||O===95||Pt(O)?(e.consume(O),M):qe(O)?(e.consume(O),v):L(O)}function M(O){return O===45||O===46||O===58||O===95||It(O)?(e.consume(O),M):S(O)}function S(O){return O===61?(e.consume(O),x):qe(O)?(e.consume(O),S):v(O)}function x(O){return O===null||O===60||O===61||O===62||O===96?n(O):O===34||O===39?(e.consume(O),l=O,$):qe(O)?(e.consume(O),x):H(O)}function $(O){return O===l?(e.consume(O),l=null,C):O===null||me(O)?n(O):(e.consume(O),$)}function H(O){return O===null||O===34||O===39||O===47||O===60||O===61||O===62||O===96||Ye(O)?S(O):(e.consume(O),H)}function C(O){return O===47||O===62||qe(O)?v(O):n(O)}function L(O){return O===62?(e.consume(O),W):n(O)}function W(O){return O===null||me(O)?Z(O):qe(O)?(e.consume(O),W):n(O)}function Z(O){return O===45&&a===2?(e.consume(O),B):O===60&&a===1?(e.consume(O),P):O===62&&a===4?(e.consume(O),J):O===63&&a===3?(e.consume(O),A):O===93&&a===5?(e.consume(O),Y):me(O)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(A9e,te,ee)(O)):O===null||me(O)?(e.exit("htmlFlowData"),ee(O)):(e.consume(O),Z)}function ee(O){return e.check(T9e,G,te)(O)}function G(O){return e.enter("lineEnding"),e.consume(O),e.exit("lineEnding"),R}function R(O){return O===null||me(O)?ee(O):(e.enter("htmlFlowData"),Z(O))}function B(O){return O===45?(e.consume(O),A):Z(O)}function P(O){return O===47?(e.consume(O),o="",D):Z(O)}function D(O){if(O===62){const de=o.toLowerCase();return rm.includes(de)?(e.consume(O),J):Z(O)}return Pt(O)&&o.length<8?(e.consume(O),o+=String.fromCharCode(O),D):Z(O)}function Y(O){return O===93?(e.consume(O),A):Z(O)}function A(O){return O===62?(e.consume(O),J):O===45&&a===2?(e.consume(O),A):Z(O)}function J(O){return O===null||me(O)?(e.exit("htmlFlowData"),te(O)):(e.consume(O),J)}function te(O){return e.exit("htmlFlow"),t(O)}}function I9e(e,t,n){const r=this;return a;function a(o){return me(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),i):n(o)}function i(o){return r.parser.lazy[r.now().line]?n(o):t(o)}}function O9e(e,t,n){return r;function r(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(Ya,t,n)}}const L9e={name:"htmlText",tokenize:D9e};function D9e(e,t,n){const r=this;let a,i,o;return s;function s(A){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(A),l}function l(A){return A===33?(e.consume(A),u):A===47?(e.consume(A),S):A===63?(e.consume(A),v):Pt(A)?(e.consume(A),H):n(A)}function u(A){return A===45?(e.consume(A),d):A===91?(e.consume(A),i=0,f):Pt(A)?(e.consume(A),k):n(A)}function d(A){return A===45?(e.consume(A),h):n(A)}function p(A){return A===null?n(A):A===45?(e.consume(A),m):me(A)?(o=p,P(A)):(e.consume(A),p)}function m(A){return A===45?(e.consume(A),h):p(A)}function h(A){return A===62?B(A):A===45?m(A):p(A)}function f(A){const J="CDATA[";return A===J.charCodeAt(i++)?(e.consume(A),i===J.length?y:f):n(A)}function y(A){return A===null?n(A):A===93?(e.consume(A),w):me(A)?(o=y,P(A)):(e.consume(A),y)}function w(A){return A===93?(e.consume(A),_):y(A)}function _(A){return A===62?B(A):A===93?(e.consume(A),_):y(A)}function k(A){return A===null||A===62?B(A):me(A)?(o=k,P(A)):(e.consume(A),k)}function v(A){return A===null?n(A):A===63?(e.consume(A),M):me(A)?(o=v,P(A)):(e.consume(A),v)}function M(A){return A===62?B(A):v(A)}function S(A){return Pt(A)?(e.consume(A),x):n(A)}function x(A){return A===45||It(A)?(e.consume(A),x):$(A)}function $(A){return me(A)?(o=$,P(A)):qe(A)?(e.consume(A),$):B(A)}function H(A){return A===45||It(A)?(e.consume(A),H):A===47||A===62||Ye(A)?C(A):n(A)}function C(A){return A===47?(e.consume(A),B):A===58||A===95||Pt(A)?(e.consume(A),L):me(A)?(o=C,P(A)):qe(A)?(e.consume(A),C):B(A)}function L(A){return A===45||A===46||A===58||A===95||It(A)?(e.consume(A),L):W(A)}function W(A){return A===61?(e.consume(A),Z):me(A)?(o=W,P(A)):qe(A)?(e.consume(A),W):C(A)}function Z(A){return A===null||A===60||A===61||A===62||A===96?n(A):A===34||A===39?(e.consume(A),a=A,ee):me(A)?(o=Z,P(A)):qe(A)?(e.consume(A),Z):(e.consume(A),G)}function ee(A){return A===a?(e.consume(A),a=void 0,R):A===null?n(A):me(A)?(o=ee,P(A)):(e.consume(A),ee)}function G(A){return A===null||A===34||A===39||A===60||A===61||A===96?n(A):A===47||A===62||Ye(A)?C(A):(e.consume(A),G)}function R(A){return A===47||A===62||Ye(A)?C(A):n(A)}function B(A){return A===62?(e.consume(A),e.exit("htmlTextData"),e.exit("htmlText"),t):n(A)}function P(A){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(A),e.exit("lineEnding"),D}function D(A){return qe(A)?De(e,Y,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):Y(A)}function Y(A){return e.enter("htmlTextData"),o(A)}}const Rp={name:"labelEnd",resolveAll:P9e,resolveTo:q9e,tokenize:B9e},z9e={tokenize:U9e},$9e={tokenize:H9e},F9e={tokenize:j9e};function P9e(e){let t=-1;const n=[];for(;++t<e.length;){const r=e[t][1];if(n.push(e[t]),r.type==="labelImage"||r.type==="labelLink"||r.type==="labelEnd"){const a=r.type==="labelImage"?4:2;r.type="data",t+=a}}return e.length!==n.length&&nn(e,0,e.length,n),e}function q9e(e,t){let n=e.length,r=0,a,i,o,s;for(;n--;)if(a=e[n][1],i){if(a.type==="link"||a.type==="labelLink"&&a._inactive)break;e[n][0]==="enter"&&a.type==="labelLink"&&(a._inactive=!0)}else if(o){if(e[n][0]==="enter"&&(a.type==="labelImage"||a.type==="labelLink")&&!a._balanced&&(i=n,a.type!=="labelLink")){r=2;break}}else a.type==="labelEnd"&&(o=n);const l={type:e[i][1].type==="labelLink"?"link":"image",start:{...e[i][1].start},end:{...e[e.length-1][1].end}},u={type:"label",start:{...e[i][1].start},end:{...e[o][1].end}},d={type:"labelText",start:{...e[i+r+2][1].end},end:{...e[o-2][1].start}};return s=[["enter",l,t],["enter",u,t]],s=un(s,e.slice(i+1,i+r+3)),s=un(s,[["enter",d,t]]),s=un(s,Oo(t.parser.constructs.insideSpan.null,e.slice(i+r+4,o-3),t)),s=un(s,[["exit",d,t],e[o-2],e[o-1],["exit",u,t]]),s=un(s,e.slice(o+1)),s=un(s,[["exit",l,t]]),nn(e,i,e.length,s),e}function B9e(e,t,n){const r=this;let a=r.events.length,i,o;for(;a--;)if((r.events[a][1].type==="labelImage"||r.events[a][1].type==="labelLink")&&!r.events[a][1]._balanced){i=r.events[a][1];break}return s;function s(m){return i?i._inactive?p(m):(o=r.parser.defined.includes(En(r.sliceSerialize({start:i.end,end:r.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(m),e.exit("labelMarker"),e.exit("labelEnd"),l):n(m)}function l(m){return m===40?e.attempt(z9e,d,o?d:p)(m):m===91?e.attempt($9e,d,o?u:p)(m):o?d(m):p(m)}function u(m){return e.attempt(F9e,d,p)(m)}function d(m){return t(m)}function p(m){return i._balanced=!0,n(m)}}function U9e(e,t,n){return r;function r(p){return e.enter("resource"),e.enter("resourceMarker"),e.consume(p),e.exit("resourceMarker"),a}function a(p){return Ye(p)?Kn(e,i)(p):i(p)}function i(p){return p===41?d(p):xv(e,o,s,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(p)}function o(p){return Ye(p)?Kn(e,l)(p):d(p)}function s(p){return n(p)}function l(p){return p===34||p===39||p===40?Mv(e,u,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(p):d(p)}function u(p){return Ye(p)?Kn(e,d)(p):d(p)}function d(p){return p===41?(e.enter("resourceMarker"),e.consume(p),e.exit("resourceMarker"),e.exit("resource"),t):n(p)}}function H9e(e,t,n){const r=this;return a;function a(s){return Ev.call(r,e,i,o,"reference","referenceMarker","referenceString")(s)}function i(s){return r.parser.defined.includes(En(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(s):n(s)}function o(s){return n(s)}}function j9e(e,t,n){return r;function r(i){return e.enter("reference"),e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),a}function a(i){return i===93?(e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),e.exit("reference"),t):n(i)}}const V9e={name:"labelStartImage",resolveAll:Rp.resolveAll,tokenize:G9e};function G9e(e,t,n){const r=this;return a;function a(s){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(s),e.exit("labelImageMarker"),i}function i(s){return s===91?(e.enter("labelMarker"),e.consume(s),e.exit("labelMarker"),e.exit("labelImage"),o):n(s)}function o(s){return s===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(s):t(s)}}const W9e={name:"labelStartLink",resolveAll:Rp.resolveAll,tokenize:K9e};function K9e(e,t,n){const r=this;return a;function a(o){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelLink"),i}function i(o){return o===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(o):t(o)}}const _s={name:"lineEnding",tokenize:Y9e};function Y9e(e,t){return n;function n(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),De(e,t,"linePrefix")}}const Pi={name:"thematicBreak",tokenize:Z9e};function Z9e(e,t,n){let r=0,a;return i;function i(u){return e.enter("thematicBreak"),o(u)}function o(u){return a=u,s(u)}function s(u){return u===a?(e.enter("thematicBreakSequence"),l(u)):r>=3&&(u===null||me(u))?(e.exit("thematicBreak"),t(u)):n(u)}function l(u){return u===a?(e.consume(u),r++,l):(e.exit("thematicBreakSequence"),qe(u)?De(e,s,"whitespace")(u):s(u))}}const Gt={continuation:{tokenize:eEe},exit:nEe,name:"list",tokenize:J9e},X9e={partial:!0,tokenize:rEe},Q9e={partial:!0,tokenize:tEe};function J9e(e,t,n){const r=this,a=r.events[r.events.length-1];let i=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,o=0;return s;function s(h){const f=r.containerState.type||(h===42||h===43||h===45?"listUnordered":"listOrdered");if(f==="listUnordered"?!r.containerState.marker||h===r.containerState.marker:Ad(h)){if(r.containerState.type||(r.containerState.type=f,e.enter(f,{_container:!0})),f==="listUnordered")return e.enter("listItemPrefix"),h===42||h===45?e.check(Pi,n,u)(h):u(h);if(!r.interrupt||h===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),l(h)}return n(h)}function l(h){return Ad(h)&&++o<10?(e.consume(h),l):(!r.interrupt||o<2)&&(r.containerState.marker?h===r.containerState.marker:h===41||h===46)?(e.exit("listItemValue"),u(h)):n(h)}function u(h){return e.enter("listItemMarker"),e.consume(h),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||h,e.check(Ya,r.interrupt?n:d,e.attempt(X9e,m,p))}function d(h){return r.containerState.initialBlankLine=!0,i++,m(h)}function p(h){return qe(h)?(e.enter("listItemPrefixWhitespace"),e.consume(h),e.exit("listItemPrefixWhitespace"),m):n(h)}function m(h){return r.containerState.size=i+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(h)}}function eEe(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(Ya,a,i);function a(s){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,De(e,t,"listItemIndent",r.containerState.size+1)(s)}function i(s){return r.containerState.furtherBlankLines||!qe(s)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,o(s)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(Q9e,t,o)(s))}function o(s){return r.containerState._closeFlow=!0,r.interrupt=void 0,De(e,e.attempt(Gt,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(s)}}function tEe(e,t,n){const r=this;return De(e,a,"listItemIndent",r.containerState.size+1);function a(i){const o=r.events[r.events.length-1];return o&&o[1].type==="listItemIndent"&&o[2].sliceSerialize(o[1],!0).length===r.containerState.size?t(i):n(i)}}function nEe(e){e.exit(this.containerState.type)}function rEe(e,t,n){const r=this;return De(e,a,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(i){const o=r.events[r.events.length-1];return!qe(i)&&o&&o[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const am={name:"setextUnderline",resolveTo:aEe,tokenize:iEe};function aEe(e,t){let n=e.length,r,a,i;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){r=n;break}e[n][1].type==="paragraph"&&(a=n)}else e[n][1].type==="content"&&e.splice(n,1),!i&&e[n][1].type==="definition"&&(i=n);const o={type:"setextHeading",start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[a][1].type="setextHeadingText",i?(e.splice(a,0,["enter",o,t]),e.splice(i+1,0,["exit",e[r][1],t]),e[r][1].end={...e[i][1].end}):e[r][1]=o,e.push(["exit",o,t]),e}function iEe(e,t,n){const r=this;let a;return i;function i(u){let d=r.events.length,p;for(;d--;)if(r.events[d][1].type!=="lineEnding"&&r.events[d][1].type!=="linePrefix"&&r.events[d][1].type!=="content"){p=r.events[d][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||p)?(e.enter("setextHeadingLine"),a=u,o(u)):n(u)}function o(u){return e.enter("setextHeadingLineSequence"),s(u)}function s(u){return u===a?(e.consume(u),s):(e.exit("setextHeadingLineSequence"),qe(u)?De(e,l,"lineSuffix")(u):l(u))}function l(u){return u===null||me(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const oEe={tokenize:sEe};function sEe(e){const t=this,n=e.attempt(Ya,r,e.attempt(this.parser.constructs.flowInitial,a,De(e,e.attempt(this.parser.constructs.flow,a,e.attempt(p9e,a)),"linePrefix")));return n;function r(i){if(i===null){e.consume(i);return}return e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function a(i){if(i===null){e.consume(i);return}return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const lEe={resolveAll:Nv()},cEe=Sv("string"),uEe=Sv("text");function Sv(e){return{resolveAll:Nv(e==="text"?dEe:void 0),tokenize:t};function t(n){const r=this,a=this.parser.constructs[e],i=n.attempt(a,o,s);return o;function o(d){return u(d)?i(d):s(d)}function s(d){if(d===null){n.consume(d);return}return n.enter("data"),n.consume(d),l}function l(d){return u(d)?(n.exit("data"),i(d)):(n.consume(d),l)}function u(d){if(d===null)return!0;const p=a[d];let m=-1;if(p)for(;++m<p.length;){const h=p[m];if(!h.previous||h.previous.call(r,r.previous))return!0}return!1}}}function Nv(e){return t;function t(n,r){let a=-1,i;for(;++a<=n.length;)i===void 0?n[a]&&n[a][1].type==="data"&&(i=a,a++):(!n[a]||n[a][1].type!=="data")&&(a!==i+2&&(n[i][1].end=n[a-1][1].end,n.splice(i+2,a-i-2),a=i+2),i=void 0);return e?e(n,r):n}}function dEe(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type==="lineEnding")&&e[n-1][1].type==="data"){const r=e[n-1][1],a=t.sliceStream(r);let i=a.length,o=-1,s=0,l;for(;i--;){const u=a[i];if(typeof u=="string"){for(o=u.length;u.charCodeAt(o-1)===32;)s++,o--;if(o)break;o=-1}else if(u===-2)l=!0,s++;else if(u!==-1){i++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(s=0),s){const u={type:n===e.length||l||s<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:i?o:r.start._bufferIndex+o,_index:r.start._index+i,line:r.end.line,column:r.end.column-s,offset:r.end.offset-s},end:{...r.end}};r.end={...u.start},r.start.offset===r.end.offset?Object.assign(r,u):(e.splice(n,0,["enter",u,t],["exit",u,t]),n+=2)}n++}return e}const pEe={42:Gt,43:Gt,45:Gt,48:Gt,49:Gt,50:Gt,51:Gt,52:Gt,53:Gt,54:Gt,55:Gt,56:Gt,57:Gt,62:kv},hEe={91:y9e},mEe={[-2]:vs,[-1]:vs,32:vs},fEe={35:x9e,42:Pi,45:[am,Pi],60:N9e,61:am,95:Pi,96:nm,126:nm},gEe={38:_v,92:vv},yEe={[-5]:_s,[-4]:_s,[-3]:_s,33:V9e,38:_v,42:Td,60:[Wxe,L9e],91:W9e,92:[_9e,vv],93:Rp,95:Td,96:o9e},bEe={null:[Td,lEe]},kEe={null:[42,95]},vEe={null:[]},_Ee=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:kEe,contentInitial:hEe,disable:vEe,document:pEe,flow:fEe,flowInitial:mEe,insideSpan:bEe,string:gEe,text:yEe},Symbol.toStringTag,{value:"Module"}));function wEe(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const a={},i=[];let o=[],s=[];const l={attempt:$(S),check:$(x),consume:k,enter:v,exit:M,interrupt:$(x,{interrupt:!0})},u={code:null,containerState:{},defineSkip:y,events:[],now:f,parser:e,previous:null,sliceSerialize:m,sliceStream:h,write:p};let d=t.tokenize.call(u,l);return t.resolveAll&&i.push(t),u;function p(W){return o=un(o,W),w(),o[o.length-1]!==null?[]:(H(t,0),u.events=Oo(i,u.events,u),u.events)}function m(W,Z){return EEe(h(W),Z)}function h(W){return xEe(o,W)}function f(){const{_bufferIndex:W,_index:Z,line:ee,column:G,offset:R}=r;return{_bufferIndex:W,_index:Z,line:ee,column:G,offset:R}}function y(W){a[W.line]=W.column,L()}function w(){let W;for(;r._index<o.length;){const Z=o[r._index];if(typeof Z=="string")for(W=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===W&&r._bufferIndex<Z.length;)_(Z.charCodeAt(r._bufferIndex));else _(Z)}}function _(W){d=d(W)}function k(W){me(W)?(r.line++,r.column=1,r.offset+=W===-3?2:1,L()):W!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===o[r._index].length&&(r._bufferIndex=-1,r._index++)),u.previous=W}function v(W,Z){const ee=Z||{};return ee.type=W,ee.start=f(),u.events.push(["enter",ee,u]),s.push(ee),ee}function M(W){const Z=s.pop();return Z.end=f(),u.events.push(["exit",Z,u]),Z}function S(W,Z){H(W,Z.from)}function x(W,Z){Z.restore()}function $(W,Z){return ee;function ee(G,R,B){let P,D,Y,A;return Array.isArray(G)?te(G):"tokenize"in G?te([G]):J(G);function J(ke){return Oe;function Oe(ze){const He=ze!==null&&ke[ze],re=ze!==null&&ke.null,Ee=[...Array.isArray(He)?He:He?[He]:[],...Array.isArray(re)?re:re?[re]:[]];return te(Ee)(ze)}}function te(ke){return P=ke,D=0,ke.length===0?B:O(ke[D])}function O(ke){return Oe;function Oe(ze){return A=C(),Y=ke,ke.partial||(u.currentConstruct=ke),ke.name&&u.parser.constructs.disable.null.includes(ke.name)?ye():ke.tokenize.call(Z?Object.assign(Object.create(u),Z):u,l,de,ye)(ze)}}function de(ke){return W(Y,A),R}function ye(ke){return A.restore(),++D<P.length?O(P[D]):B}}}function H(W,Z){W.resolveAll&&!i.includes(W)&&i.push(W),W.resolve&&nn(u.events,Z,u.events.length-Z,W.resolve(u.events.slice(Z),u)),W.resolveTo&&(u.events=W.resolveTo(u.events,u))}function C(){const W=f(),Z=u.previous,ee=u.currentConstruct,G=u.events.length,R=Array.from(s);return{from:G,restore:B};function B(){r=W,u.previous=Z,u.currentConstruct=ee,u.events.length=G,s=R,L()}}function L(){r.line in a&&r.column<2&&(r.column=a[r.line],r.offset+=a[r.line]-1)}}function xEe(e,t){const n=t.start._index,r=t.start._bufferIndex,a=t.end._index,i=t.end._bufferIndex;let o;if(n===a)o=[e[n].slice(r,i)];else{if(o=e.slice(n,a),r>-1){const s=o[0];typeof s=="string"?o[0]=s.slice(r):o.shift()}i>0&&o.push(e[a].slice(0,i))}return o}function EEe(e,t){let n=-1;const r=[];let a;for(;++n<e.length;){const i=e[n];let o;if(typeof i=="string")o=i;else switch(i){case-5:{o="\r";break}case-4:{o=`
|
|
8324
8324
|
`;break}case-3:{o=`\r
|
|
8325
8325
|
`;break}case-2:{o=t?" ":" ";break}case-1:{if(!t&&a)continue;o=" ";break}default:o=String.fromCharCode(i)}a=i===-2,r.push(o)}return r.join("")}function MEe(e){const r={constructs:yv([_Ee,...(e||{}).extensions||[]]),content:a(qxe),defined:[],document:a(Uxe),flow:a(oEe),lazy:{},string:a(cEe),text:a(uEe)};return r;function a(i){return o;function o(s){return wEe(r,i,s)}}}function SEe(e){for(;!wv(e););return e}const im=/[\0\t\n\r]/g;function NEe(){let e=1,t="",n=!0,r;return a;function a(i,o,s){const l=[];let u,d,p,m,h;for(i=t+(typeof i=="string"?i.toString():new TextDecoder(o||void 0).decode(i)),p=0,t="",n&&(i.charCodeAt(0)===65279&&p++,n=void 0);p<i.length;){if(im.lastIndex=p,u=im.exec(i),m=u&&u.index!==void 0?u.index:i.length,h=i.charCodeAt(m),!u){t=i.slice(p);break}if(h===10&&p===m&&r)l.push(-3),r=void 0;else switch(r&&(l.push(-5),r=void 0),p<m&&(l.push(i.slice(p,m)),e+=m-p),h){case 0:{l.push(65533),e++;break}case 9:{for(d=Math.ceil(e/4)*4,l.push(-2);e++<d;)l.push(-1);break}case 10:{l.push(-4),e=1;break}default:r=!0,e=1}p=m+1}return s&&(r&&l.push(-5),t&&l.push(t),l.push(null)),l}}const AEe=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function TEe(e){return e.replace(AEe,CEe)}function CEe(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const a=n.charCodeAt(1),i=a===120||a===88;return bv(n.slice(i?2:1),i?16:10)}return $a(n)||e}const Av={}.hasOwnProperty;function REe(e,t,n){return typeof t!="string"&&(n=t,t=void 0),IEe(n)(SEe(MEe(n).document().write(NEe()(e,t,!0))))}function IEe(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:i(Re),autolinkProtocol:C,autolinkEmail:C,atxHeading:i(Ne),blockQuote:i(re),characterEscape:C,characterReference:C,codeFenced:i(Ee),codeFencedFenceInfo:o,codeFencedFenceMeta:o,codeIndented:i(Ee,o),codeText:i(Qe,o),codeTextData:C,data:C,codeFlowValue:C,definition:i(Je),definitionDestinationString:o,definitionLabelString:o,definitionTitleString:o,emphasis:i(we),hardBreakEscape:i(ve),hardBreakTrailing:i(ve),htmlFlow:i(Be,o),htmlFlowData:C,htmlText:i(Be,o),htmlTextData:C,image:i(pe),label:o,link:i(Re),listItem:i(We),listItemValue:m,listOrdered:i(rt,p),listUnordered:i(rt),paragraph:i(_e),reference:O,referenceString:o,resourceDestinationString:o,resourceTitleString:o,setextHeading:i(Ne),strong:i(Pe),thematicBreak:i(Ze)},exit:{atxHeading:l(),atxHeadingSequence:S,autolink:l(),autolinkEmail:He,autolinkProtocol:ze,blockQuote:l(),characterEscapeValue:L,characterReferenceMarkerHexadecimal:ye,characterReferenceMarkerNumeric:ye,characterReferenceValue:ke,characterReference:Oe,codeFenced:l(w),codeFencedFence:y,codeFencedFenceInfo:h,codeFencedFenceMeta:f,codeFlowValue:L,codeIndented:l(_),codeText:l(R),codeTextData:L,data:L,definition:l(),definitionDestinationString:M,definitionLabelString:k,definitionTitleString:v,emphasis:l(),hardBreakEscape:l(Z),hardBreakTrailing:l(Z),htmlFlow:l(ee),htmlFlowData:L,htmlText:l(G),htmlTextData:L,image:l(P),label:Y,labelText:D,lineEnding:W,link:l(B),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:de,resourceDestinationString:A,resourceTitleString:J,resource:te,setextHeading:l(H),setextHeadingLineSequence:$,setextHeadingText:x,strong:l(),thematicBreak:l()}};Tv(t,(e||{}).mdastExtensions||[]);const n={};return r;function r(q){let X={type:"root",children:[]};const le={stack:[X],tokenStack:[],config:t,enter:s,exit:u,buffer:o,resume:d,data:n},he=[];let Ae=-1;for(;++Ae<q.length;)if(q[Ae][1].type==="listOrdered"||q[Ae][1].type==="listUnordered")if(q[Ae][0]==="enter")he.push(Ae);else{const je=he.pop();Ae=a(q,je,Ae)}for(Ae=-1;++Ae<q.length;){const je=t[q[Ae][0]];Av.call(je,q[Ae][1].type)&&je[q[Ae][1].type].call(Object.assign({sliceSerialize:q[Ae][2].sliceSerialize},le),q[Ae][1])}if(le.tokenStack.length>0){const je=le.tokenStack[le.tokenStack.length-1];(je[1]||om).call(le,void 0,je[0])}for(X.position={start:ar(q.length>0?q[0][1].start:{line:1,column:1,offset:0}),end:ar(q.length>0?q[q.length-2][1].end:{line:1,column:1,offset:0})},Ae=-1;++Ae<t.transforms.length;)X=t.transforms[Ae](X)||X;return X}function a(q,X,le){let he=X-1,Ae=-1,je=!1,xt,Mt,Sn,Nn;for(;++he<=le;){const yt=q[he];switch(yt[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{yt[0]==="enter"?Ae++:Ae--,Nn=void 0;break}case"lineEndingBlank":{yt[0]==="enter"&&(xt&&!Nn&&!Ae&&!Sn&&(Sn=he),Nn=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Nn=void 0}if(!Ae&&yt[0]==="enter"&&yt[1].type==="listItemPrefix"||Ae===-1&&yt[0]==="exit"&&(yt[1].type==="listUnordered"||yt[1].type==="listOrdered")){if(xt){let Nt=he;for(Mt=void 0;Nt--;){const St=q[Nt];if(St[1].type==="lineEnding"||St[1].type==="lineEndingBlank"){if(St[0]==="exit")continue;Mt&&(q[Mt][1].type="lineEndingBlank",je=!0),St[1].type="lineEnding",Mt=Nt}else if(!(St[1].type==="linePrefix"||St[1].type==="blockQuotePrefix"||St[1].type==="blockQuotePrefixWhitespace"||St[1].type==="blockQuoteMarker"||St[1].type==="listItemIndent"))break}Sn&&(!Mt||Sn<Mt)&&(xt._spread=!0),xt.end=Object.assign({},Mt?q[Mt][1].start:yt[1].end),q.splice(Mt||he,0,["exit",xt,yt[2]]),he++,le++}if(yt[1].type==="listItemPrefix"){const Nt={type:"listItem",_spread:!1,start:Object.assign({},yt[1].start),end:void 0};xt=Nt,q.splice(he,0,["enter",Nt,yt[2]]),he++,le++,Sn=void 0,Nn=!0}}}return q[X][1]._spread=je,le}function i(q,X){return le;function le(he){s.call(this,q(he),he),X&&X.call(this,he)}}function o(){this.stack.push({type:"fragment",children:[]})}function s(q,X,le){this.stack[this.stack.length-1].children.push(q),this.stack.push(q),this.tokenStack.push([X,le||void 0]),q.position={start:ar(X.start),end:void 0}}function l(q){return X;function X(le){q&&q.call(this,le),u.call(this,le)}}function u(q,X){const le=this.stack.pop(),he=this.tokenStack.pop();if(he)he[0].type!==q.type&&(X?X.call(this,q,he[0]):(he[1]||om).call(this,q,he[0]));else throw new Error("Cannot close `"+q.type+"` ("+Sa({start:q.start,end:q.end})+"): it’s not open");le.position.end=ar(q.end)}function d(){return Cp(this.stack.pop())}function p(){this.data.expectingFirstListItemValue=!0}function m(q){if(this.data.expectingFirstListItemValue){const X=this.stack[this.stack.length-2];X.start=Number.parseInt(this.sliceSerialize(q),10),this.data.expectingFirstListItemValue=void 0}}function h(){const q=this.resume(),X=this.stack[this.stack.length-1];X.lang=q}function f(){const q=this.resume(),X=this.stack[this.stack.length-1];X.meta=q}function y(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function w(){const q=this.resume(),X=this.stack[this.stack.length-1];X.value=q.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function _(){const q=this.resume(),X=this.stack[this.stack.length-1];X.value=q.replace(/(\r?\n|\r)$/g,"")}function k(q){const X=this.resume(),le=this.stack[this.stack.length-1];le.label=X,le.identifier=En(this.sliceSerialize(q)).toLowerCase()}function v(){const q=this.resume(),X=this.stack[this.stack.length-1];X.title=q}function M(){const q=this.resume(),X=this.stack[this.stack.length-1];X.url=q}function S(q){const X=this.stack[this.stack.length-1];if(!X.depth){const le=this.sliceSerialize(q).length;X.depth=le}}function x(){this.data.setextHeadingSlurpLineEnding=!0}function $(q){const X=this.stack[this.stack.length-1];X.depth=this.sliceSerialize(q).codePointAt(0)===61?1:2}function H(){this.data.setextHeadingSlurpLineEnding=void 0}function C(q){const le=this.stack[this.stack.length-1].children;let he=le[le.length-1];(!he||he.type!=="text")&&(he=Me(),he.position={start:ar(q.start),end:void 0},le.push(he)),this.stack.push(he)}function L(q){const X=this.stack.pop();X.value+=this.sliceSerialize(q),X.position.end=ar(q.end)}function W(q){const X=this.stack[this.stack.length-1];if(this.data.atHardBreak){const le=X.children[X.children.length-1];le.position.end=ar(q.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(X.type)&&(C.call(this,q),L.call(this,q))}function Z(){this.data.atHardBreak=!0}function ee(){const q=this.resume(),X=this.stack[this.stack.length-1];X.value=q}function G(){const q=this.resume(),X=this.stack[this.stack.length-1];X.value=q}function R(){const q=this.resume(),X=this.stack[this.stack.length-1];X.value=q}function B(){const q=this.stack[this.stack.length-1];if(this.data.inReference){const X=this.data.referenceType||"shortcut";q.type+="Reference",q.referenceType=X,delete q.url,delete q.title}else delete q.identifier,delete q.label;this.data.referenceType=void 0}function P(){const q=this.stack[this.stack.length-1];if(this.data.inReference){const X=this.data.referenceType||"shortcut";q.type+="Reference",q.referenceType=X,delete q.url,delete q.title}else delete q.identifier,delete q.label;this.data.referenceType=void 0}function D(q){const X=this.sliceSerialize(q),le=this.stack[this.stack.length-2];le.label=TEe(X),le.identifier=En(X).toLowerCase()}function Y(){const q=this.stack[this.stack.length-1],X=this.resume(),le=this.stack[this.stack.length-1];if(this.data.inReference=!0,le.type==="link"){const he=q.children;le.children=he}else le.alt=X}function A(){const q=this.resume(),X=this.stack[this.stack.length-1];X.url=q}function J(){const q=this.resume(),X=this.stack[this.stack.length-1];X.title=q}function te(){this.data.inReference=void 0}function O(){this.data.referenceType="collapsed"}function de(q){const X=this.resume(),le=this.stack[this.stack.length-1];le.label=X,le.identifier=En(this.sliceSerialize(q)).toLowerCase(),this.data.referenceType="full"}function ye(q){this.data.characterReferenceType=q.type}function ke(q){const X=this.sliceSerialize(q),le=this.data.characterReferenceType;let he;le?(he=bv(X,le==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):he=$a(X);const Ae=this.stack[this.stack.length-1];Ae.value+=he}function Oe(q){const X=this.stack.pop();X.position.end=ar(q.end)}function ze(q){L.call(this,q);const X=this.stack[this.stack.length-1];X.url=this.sliceSerialize(q)}function He(q){L.call(this,q);const X=this.stack[this.stack.length-1];X.url="mailto:"+this.sliceSerialize(q)}function re(){return{type:"blockquote",children:[]}}function Ee(){return{type:"code",lang:null,meta:null,value:""}}function Qe(){return{type:"inlineCode",value:""}}function Je(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function we(){return{type:"emphasis",children:[]}}function Ne(){return{type:"heading",depth:0,children:[]}}function ve(){return{type:"break"}}function Be(){return{type:"html",value:""}}function pe(){return{type:"image",title:null,url:"",alt:null}}function Re(){return{type:"link",title:null,url:"",children:[]}}function rt(q){return{type:"list",ordered:q.type==="listOrdered",start:null,spread:q._spread,children:[]}}function We(q){return{type:"listItem",spread:q._spread,checked:null,children:[]}}function _e(){return{type:"paragraph",children:[]}}function Pe(){return{type:"strong",children:[]}}function Me(){return{type:"text",value:""}}function Ze(){return{type:"thematicBreak"}}}function ar(e){return{line:e.line,column:e.column,offset:e.offset}}function Tv(e,t){let n=-1;for(;++n<t.length;){const r=t[n];Array.isArray(r)?Tv(e,r):OEe(e,r)}}function OEe(e,t){let n;for(n in t)if(Av.call(t,n))switch(n){case"canContainEols":{const r=t[n];r&&e[n].push(...r);break}case"transforms":{const r=t[n];r&&e[n].push(...r);break}case"enter":case"exit":{const r=t[n];r&&Object.assign(e[n],r);break}}}function om(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+Sa({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+Sa({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+Sa({start:t.start,end:t.end})+") is still open")}function LEe(e){const t=this;t.parser=n;function n(r){return REe(r,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function DEe(e,t){const n={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)}function zEe(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
|