@artooi/ag-ui-web-component 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,69 +1,69 @@
1
- var fu=Object.defineProperty;var ms=(e,t)=>{for(var n in t)fu(e,n,{get:t[n],enumerable:!0})};var gr="ag-ui-chat",gs="ag-ui-submit",vs="ag-ui-toggle",We={USER:"user",ASSISTANT:"assistant"},Nn="x-destructive",ys="x-confirm",Xe="x-summary",Rn="x-navigates",bs=10,de={PENDING:"pending",DONE:"done",ERROR:"error",DECLINED:"declined"},Ze={MINIMAL:"minimal",COMPACT:"compact",FULL:"full"};var hu=/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;function va(e,t){let n=[];return{text:e.replace(hu,(o,s)=>{let i=t[s];return i==null||i===""?(n.includes(s)||n.push(s),o):String(i)}),missing:n}}function mu(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.name=="string"&&typeof t.title=="string"&&typeof t.prompt=="string"}function xs(e){return Array.isArray(e)?e.filter(mu):[]}var On=class{#e=new Map;register(t){this.#e.set(t.name,t)}has(t){return this.#e.has(t)}get(t){let n=this.#e.get(t);if(n===void 0)throw new Error(`tool "${t}" is not registered`);return n}tools(){return[...this.#e.values()].map(t=>({name:t.name,description:t.description,parameters:t.parameters}))}};function Es(e){return e[Nn]===!0}function _s(e){return e[Rn]===!0}function Ts(e,t){return!t||e===null?[]:[{description:"page_map",value:JSON.stringify(e())}]}function Ss(e){let t={};if(!Array.isArray(e))return t;for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=r.name,s=r.summary;typeof o=="string"&&typeof s=="string"&&(t[o]=s)}return t}var ya=/:([A-Za-z_][A-Za-z0-9_]*)/g;function gu(e){let t=[];for(let n of e.matchAll(ya)){let r=n[1];r!==void 0&&t.push(r)}return t}function vu(e,t,n){let r={...n};return{path:t.replace(ya,(s,i)=>{let a=n[i];if(a==null||String(a)==="")throw new Error(`route "${e}" requires path param "${i}"`);return delete r[i],encodeURIComponent(String(a))}),leftover:r}}function yu(e,t){let n=new URLSearchParams;for(let[o,s]of Object.entries(t))n.set(o,String(s));let r=n.toString();return r===""?e:`${e}?${r}`}function ws(e,t){return[{name:"list_routes",description:"List the routes the app can navigate to. Each route's `pathParams` names the dynamic segments to pass as `params` to `navigate_to_route`.",parameters:{type:"object",properties:{},required:[],[Xe]:"List pages"},handler:()=>e().map(n=>({...n,pathParams:gu(n.path)}))},{name:"navigate_to_route",description:"Navigate to one of the app's routes by its id, filling any dynamic `:name` path segments (and extra query params) from `params`.",parameters:{type:"object",properties:{route_id:{type:"string"},params:{type:"object"}},required:["route_id"],[Rn]:!0,[Xe]:"Navigate"},handler:n=>{let r=n.route_id,o=e().find(p=>p.id===r);if(o===void 0)throw new Error(`unknown route "${String(r)}"`);let s=n.params??{},{path:i,leftover:a}=vu(o.id,o.path,s),u=yu(i,a),c=t();return c!==null?c(u):window.location.assign(u),{navigated:!0,path:u}}}]}function ks(e){let t=[{name:`read_${e.name}`,description:`Read the "${e.name}" state.`,parameters:{type:"object",properties:{},required:[],[Xe]:`Read ${e.name}`},handler:()=>e.read()}],n=e.write;return n!==void 0&&t.push({name:`set_${e.name}`,description:`Update the "${e.name}" state.`,parameters:{...e.schema??{type:"object"},[Nn]:!0,[Xe]:`Update ${e.name}`},handler:r=>n(r)}),t}function ba(e,t){let n=document.createElement("button");return n.type="button",n.className=`confirm-btn confirm-btn--${e}`,n.textContent=t,n}function As(e,t){return new Promise(n=>{let r=document.createElement("div");r.className="confirm",r.setAttribute("data-tool-name",t.toolName),r.setAttribute("role","group"),r.setAttribute("aria-label","Confirm action");let o=document.createElement("div");o.className="confirm-body",o.textContent=t.message??`Run \u201C${t.toolName}\u201D?`;let s=document.createElement("pre");s.className="confirm-args",s.textContent=JSON.stringify(t.args,null,2);let i=document.createElement("div");i.className="confirm-actions";let a=ba("cancel","Cancel"),u=ba("confirm","Confirm"),c=p=>{a.disabled=!0,u.disabled=!0,r.setAttribute("data-resolved",p?"confirmed":"declined"),n(p)};a.addEventListener("click",()=>c(!1)),u.addEventListener("click",()=>c(!0)),i.append(a,u),r.append(o,s,i),e.appendChild(r),u.focus()})}function Is(e){let t=e.replace(/[._-]+/g," ").trim();return t===""?e:t.charAt(0).toUpperCase()+t.slice(1)}function xa(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function bu(e){if(Array.isArray(e))return e}function xu(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,o,s,i,a=[],u=!0,c=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(u=(r=s.call(n)).done)&&(a.push(r.value),a.length!==t);u=!0);}catch(p){c=!0,o=p}finally{try{if(!u&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(c)throw o}}return a}}function Eu(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
2
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _u(e,t){return bu(e)||xu(e,t)||Tu(e,t)||Eu()}function Tu(e,t){if(e){if(typeof e=="string")return xa(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?xa(e,t):void 0}}var Ma=Object.entries,Ea=Object.setPrototypeOf,Su=Object.isFrozen,wu=Object.getPrototypeOf,ku=Object.getOwnPropertyDescriptor,Se=Object.freeze,Ne=Object.seal,on=Object.create,La=typeof Reflect<"u"&&Reflect,Ls=La.apply,Ps=La.construct;Se||(Se=function(t){return t});Ne||(Ne=function(t){return t});Ls||(Ls=function(t,n){for(var r=arguments.length,o=new Array(r>2?r-2:0),s=2;s<r;s++)o[s-2]=arguments[s];return t.apply(n,o)});Ps||(Ps=function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return new t(...r)});var tn=ce(Array.prototype.forEach),Au=ce(Array.prototype.lastIndexOf),_a=ce(Array.prototype.pop),nn=ce(Array.prototype.push),Iu=ce(Array.prototype.splice),Te=Array.isArray,Pn=ce(String.prototype.toLowerCase),Cs=ce(String.prototype.toString),Ta=ce(String.prototype.match),rn=ce(String.prototype.replace),Sa=ce(String.prototype.indexOf),Cu=ce(String.prototype.trim),Nu=ce(Number.prototype.toString),Ru=ce(Boolean.prototype.toString),wa=typeof BigInt>"u"?null:ce(BigInt.prototype.toString),ka=typeof Symbol>"u"?null:ce(Symbol.prototype.toString),ne=ce(Object.prototype.hasOwnProperty),Mn=ce(Object.prototype.toString),ge=ce(RegExp.prototype.test),Ln=Ou(TypeError);function ce(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return Ls(e,t,r)}}function Ou(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return Ps(e,n)}}function P(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Pn;if(Ea&&Ea(e,null),!Te(t))return e;let r=t.length;for(;r--;){let o=t[r];if(typeof o=="string"){let s=n(o);s!==o&&(Su(t)||(t[r]=s),o=s)}e[o]=!0}return e}function Mu(e){for(let t=0;t<e.length;t++)ne(e,t)||(e[t]=null);return e}function xe(e){let t=on(null);for(let r of Ma(e)){var n=_u(r,2);let o=n[0],s=n[1];ne(e,o)&&(Te(s)?t[o]=Mu(s):s&&typeof s=="object"&&s.constructor===Object?t[o]=xe(s):t[o]=s)}return t}function Lu(e){switch(typeof e){case"string":return e;case"number":return Nu(e);case"boolean":return Ru(e);case"bigint":return wa?wa(e):"0";case"symbol":return ka?ka(e):"Symbol()";case"undefined":return Mn(e);case"function":case"object":{if(e===null)return Mn(e);let t=e,n=Ye(t,"toString");if(typeof n=="function"){let r=n(t);return typeof r=="string"?r:Mn(r)}return Mn(e)}default:return Mn(e)}}function Ye(e,t){for(;e!==null;){let r=ku(e,t);if(r){if(r.get)return ce(r.get);if(typeof r.value=="function")return ce(r.value)}e=wu(e)}function n(){return null}return n}function Pu(e){try{return ge(e,""),!0}catch{return!1}}var Aa=Se(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Ns=Se(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Rs=Se(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Du=Se(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Os=Se(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Uu=Se(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Ia=Se(["#text"]),Ca=Se(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Ms=Se(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Na=Se(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),vr=Se(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Gu=Ne(/{{[\w\W]*|^[\w\W]*}}/g),Fu=Ne(/<%[\w\W]*|^[\w\W]*%>/g),Hu=Ne(/\${[\w\W]*/g),$u=Ne(/^data-[\-\w.\u00B7-\uFFFF]+$/),zu=Ne(/^aria-[\-\w]+$/),Ra=Ne(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Bu=Ne(/^(?:\w+script|data):/i),Vu=Ne(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),ju=Ne(/^html$/i),Wu=Ne(/^[a-z][.\w]*(-[.\w]+)+$/i),Ke={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Xu=function(){return typeof window>"u"?null:window},Zu=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let r=null,o="data-tt-policy-suffix";n&&n.hasAttribute(o)&&(r=n.getAttribute(o));let s="dompurify"+(r?"#"+r:"");try{return t.createPolicy(s,{createHTML(i){return i},createScriptURL(i){return i}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},Oa=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Pa(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Xu(),t=C=>Pa(C);if(t.version="3.4.7",t.removed=[],!e||!e.document||e.document.nodeType!==Ke.document||!e.Element)return t.isSupported=!1,t;let n=e.document,r=n,o=r.currentScript;e.DocumentFragment;let s=e.HTMLTemplateElement,i=e.Node,a=e.Element,u=e.NodeFilter,c=e.NamedNodeMap;c===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;let p=e.DOMParser,m=e.trustedTypes,x=a.prototype,f=Ye(x,"cloneNode"),h=Ye(x,"remove"),g=Ye(x,"nextSibling"),_=Ye(x,"childNodes"),S=Ye(x,"parentNode"),b=Ye(x,"shadowRoot"),F=Ye(x,"attributes"),X=i&&i.prototype?Ye(i.prototype,"nodeType"):null,ae=i&&i.prototype?Ye(i.prototype,"nodeName"):null;if(typeof s=="function"){let C=n.createElement("template");C.content&&C.content.ownerDocument&&(n=C.content.ownerDocument)}let ee,ut="",or=n,es=or.implementation,Xi=or.createNodeIterator,Qc=or.createDocumentFragment,eu=or.getElementsByTagName,tu=r.importNode,pe=Oa();t.isSupported=typeof Ma=="function"&&typeof S=="function"&&es&&es.createHTMLDocument!==void 0;let sr=Gu,ir=Fu,ar=Hu,nu=$u,ru=zu,ou=Bu,Zi=Vu,su=Wu,Ki=Ra,oe=null,ts=P({},[...Aa,...Ns,...Rs,...Os,...Ia]),le=null,ns=P({},[...Ca,...Ms,...Na,...vr]),se=Object.seal(on(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),wn=null,lr=null,dt=Object.seal(on(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),Yi=!0,rs=!0,qi=!1,Ji=!0,pt=!1,kn=!0,xt=!1,os=!1,ss=!1,Yt=!1,cr=!1,ur=!1,Qi=!0,ea=!1,ta="user-content-",is=!0,An=!1,qt={},Be=null,as=P({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),na=null,ra=P({},["audio","video","img","source","image","track"]),ls=null,oa=P({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),dr="http://www.w3.org/1998/Math/MathML",pr="http://www.w3.org/2000/svg",Ve="http://www.w3.org/1999/xhtml",Jt=Ve,cs=!1,us=null,iu=P({},[dr,pr,Ve],Cs),ds=P({},["mi","mo","mn","ms","mtext"]),ps=P({},["annotation-xml"]),au=P({},["title","style","font","a","script"]),In=null,lu=["application/xhtml+xml","text/html"],cu="text/html",ie=null,Qt=null,uu=n.createElement("form"),sa=function(d){return d instanceof RegExp||d instanceof Function},fs=function(){let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Qt&&Qt===d)return;(!d||typeof d!="object")&&(d={}),d=xe(d),In=lu.indexOf(d.PARSER_MEDIA_TYPE)===-1?cu:d.PARSER_MEDIA_TYPE,ie=In==="application/xhtml+xml"?Cs:Pn,oe=ne(d,"ALLOWED_TAGS")&&Te(d.ALLOWED_TAGS)?P({},d.ALLOWED_TAGS,ie):ts,le=ne(d,"ALLOWED_ATTR")&&Te(d.ALLOWED_ATTR)?P({},d.ALLOWED_ATTR,ie):ns,us=ne(d,"ALLOWED_NAMESPACES")&&Te(d.ALLOWED_NAMESPACES)?P({},d.ALLOWED_NAMESPACES,Cs):iu,ls=ne(d,"ADD_URI_SAFE_ATTR")&&Te(d.ADD_URI_SAFE_ATTR)?P(xe(oa),d.ADD_URI_SAFE_ATTR,ie):oa,na=ne(d,"ADD_DATA_URI_TAGS")&&Te(d.ADD_DATA_URI_TAGS)?P(xe(ra),d.ADD_DATA_URI_TAGS,ie):ra,Be=ne(d,"FORBID_CONTENTS")&&Te(d.FORBID_CONTENTS)?P({},d.FORBID_CONTENTS,ie):as,wn=ne(d,"FORBID_TAGS")&&Te(d.FORBID_TAGS)?P({},d.FORBID_TAGS,ie):xe({}),lr=ne(d,"FORBID_ATTR")&&Te(d.FORBID_ATTR)?P({},d.FORBID_ATTR,ie):xe({}),qt=ne(d,"USE_PROFILES")?d.USE_PROFILES&&typeof d.USE_PROFILES=="object"?xe(d.USE_PROFILES):d.USE_PROFILES:!1,Yi=d.ALLOW_ARIA_ATTR!==!1,rs=d.ALLOW_DATA_ATTR!==!1,qi=d.ALLOW_UNKNOWN_PROTOCOLS||!1,Ji=d.ALLOW_SELF_CLOSE_IN_ATTR!==!1,pt=d.SAFE_FOR_TEMPLATES||!1,kn=d.SAFE_FOR_XML!==!1,xt=d.WHOLE_DOCUMENT||!1,Yt=d.RETURN_DOM||!1,cr=d.RETURN_DOM_FRAGMENT||!1,ur=d.RETURN_TRUSTED_TYPE||!1,ss=d.FORCE_BODY||!1,Qi=d.SANITIZE_DOM!==!1,ea=d.SANITIZE_NAMED_PROPS||!1,is=d.KEEP_CONTENT!==!1,An=d.IN_PLACE||!1,Ki=Pu(d.ALLOWED_URI_REGEXP)?d.ALLOWED_URI_REGEXP:Ra,Jt=typeof d.NAMESPACE=="string"?d.NAMESPACE:Ve,ds=ne(d,"MATHML_TEXT_INTEGRATION_POINTS")&&d.MATHML_TEXT_INTEGRATION_POINTS&&typeof d.MATHML_TEXT_INTEGRATION_POINTS=="object"?xe(d.MATHML_TEXT_INTEGRATION_POINTS):P({},["mi","mo","mn","ms","mtext"]),ps=ne(d,"HTML_INTEGRATION_POINTS")&&d.HTML_INTEGRATION_POINTS&&typeof d.HTML_INTEGRATION_POINTS=="object"?xe(d.HTML_INTEGRATION_POINTS):P({},["annotation-xml"]);let y=ne(d,"CUSTOM_ELEMENT_HANDLING")&&d.CUSTOM_ELEMENT_HANDLING&&typeof d.CUSTOM_ELEMENT_HANDLING=="object"?xe(d.CUSTOM_ELEMENT_HANDLING):on(null);if(se=on(null),ne(y,"tagNameCheck")&&sa(y.tagNameCheck)&&(se.tagNameCheck=y.tagNameCheck),ne(y,"attributeNameCheck")&&sa(y.attributeNameCheck)&&(se.attributeNameCheck=y.attributeNameCheck),ne(y,"allowCustomizedBuiltInElements")&&typeof y.allowCustomizedBuiltInElements=="boolean"&&(se.allowCustomizedBuiltInElements=y.allowCustomizedBuiltInElements),pt&&(rs=!1),cr&&(Yt=!0),qt&&(oe=P({},Ia),le=on(null),qt.html===!0&&(P(oe,Aa),P(le,Ca)),qt.svg===!0&&(P(oe,Ns),P(le,Ms),P(le,vr)),qt.svgFilters===!0&&(P(oe,Rs),P(le,Ms),P(le,vr)),qt.mathMl===!0&&(P(oe,Os),P(le,Na),P(le,vr))),dt.tagCheck=null,dt.attributeCheck=null,ne(d,"ADD_TAGS")&&(typeof d.ADD_TAGS=="function"?dt.tagCheck=d.ADD_TAGS:Te(d.ADD_TAGS)&&(oe===ts&&(oe=xe(oe)),P(oe,d.ADD_TAGS,ie))),ne(d,"ADD_ATTR")&&(typeof d.ADD_ATTR=="function"?dt.attributeCheck=d.ADD_ATTR:Te(d.ADD_ATTR)&&(le===ns&&(le=xe(le)),P(le,d.ADD_ATTR,ie))),ne(d,"ADD_URI_SAFE_ATTR")&&Te(d.ADD_URI_SAFE_ATTR)&&P(ls,d.ADD_URI_SAFE_ATTR,ie),ne(d,"FORBID_CONTENTS")&&Te(d.FORBID_CONTENTS)&&(Be===as&&(Be=xe(Be)),P(Be,d.FORBID_CONTENTS,ie)),ne(d,"ADD_FORBID_CONTENTS")&&Te(d.ADD_FORBID_CONTENTS)&&(Be===as&&(Be=xe(Be)),P(Be,d.ADD_FORBID_CONTENTS,ie)),is&&(oe["#text"]=!0),xt&&P(oe,["html","head","body"]),oe.table&&(P(oe,["tbody"]),delete wn.tbody),d.TRUSTED_TYPES_POLICY){if(typeof d.TRUSTED_TYPES_POLICY.createHTML!="function")throw Ln('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof d.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Ln('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');ee=d.TRUSTED_TYPES_POLICY,ut=ee.createHTML("")}else ee===void 0&&(ee=Zu(m,o)),ee!==null&&typeof ut=="string"&&(ut=ee.createHTML(""));(pe.uponSanitizeElement.length>0||pe.uponSanitizeAttribute.length>0)&&oe===ts&&(oe=xe(oe)),pe.uponSanitizeAttribute.length>0&&le===ns&&(le=xe(le)),Se&&Se(d),Qt=d},ia=P({},[...Ns,...Rs,...Du]),aa=P({},[...Os,...Uu]),du=function(d){let y=S(d);(!y||!y.tagName)&&(y={namespaceURI:Jt,tagName:"template"});let k=Pn(d.tagName),j=Pn(y.tagName);return us[d.namespaceURI]?d.namespaceURI===pr?y.namespaceURI===Ve?k==="svg":y.namespaceURI===dr?k==="svg"&&(j==="annotation-xml"||ds[j]):!!ia[k]:d.namespaceURI===dr?y.namespaceURI===Ve?k==="math":y.namespaceURI===pr?k==="math"&&ps[j]:!!aa[k]:d.namespaceURI===Ve?y.namespaceURI===pr&&!ps[j]||y.namespaceURI===dr&&!ds[j]?!1:!aa[k]&&(au[k]||!ia[k]):!!(In==="application/xhtml+xml"&&us[d.namespaceURI]):!1},Pe=function(d){nn(t.removed,{element:d});try{S(d).removeChild(d)}catch{h(d)}},Et=function(d,y){try{nn(t.removed,{attribute:y.getAttributeNode(d),from:y})}catch{nn(t.removed,{attribute:null,from:y})}if(y.removeAttribute(d),d==="is")if(Yt||cr)try{Pe(y)}catch{}else try{y.setAttribute(d,"")}catch{}},la=function(d){let y=null,k=null;if(ss)d="<remove></remove>"+d;else{let Y=Ta(d,/^[\r\n\t ]+/);k=Y&&Y[0]}In==="application/xhtml+xml"&&Jt===Ve&&(d='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+d+"</body></html>");let j=ee?ee.createHTML(d):d;if(Jt===Ve)try{y=new p().parseFromString(j,In)}catch{}if(!y||!y.documentElement){y=es.createDocument(Jt,"template",null);try{y.documentElement.innerHTML=cs?ut:j}catch{}}let $=y.body||y.documentElement;return d&&k&&$.insertBefore(n.createTextNode(k),$.childNodes[0]||null),Jt===Ve?eu.call(y,xt?"html":"body")[0]:xt?y.documentElement:$},ca=function(d){return Xi.call(d.ownerDocument||d,d,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT|u.SHOW_PROCESSING_INSTRUCTION|u.SHOW_CDATA_SECTION,null)},ua=function(d){d.normalize();let y=Xi.call(d.ownerDocument||d,d,u.SHOW_TEXT|u.SHOW_COMMENT|u.SHOW_CDATA_SECTION|u.SHOW_PROCESSING_INSTRUCTION,null),k=y.nextNode();for(;k;){let j=k.data;tn([sr,ir,ar],$=>{j=rn(j,$," ")}),k.data=j,k=y.nextNode()}},fr=function(d){let y=ae?ae(d):null;return typeof y!="string"||ie(y)!=="form"?!1:typeof d.nodeName!="string"||typeof d.textContent!="string"||typeof d.removeChild!="function"||d.attributes!==F(d)||typeof d.removeAttribute!="function"||typeof d.setAttribute!="function"||typeof d.namespaceURI!="string"||typeof d.insertBefore!="function"||typeof d.hasChildNodes!="function"||d.nodeType!==X(d)||d.childNodes!==_(d)},Cn=function(d){if(!X||typeof d!="object"||d===null)return!1;try{return X(d)===Ke.documentFragment}catch{return!1}},hr=function(d){if(!X||typeof d!="object"||d===null)return!1;try{return typeof X(d)=="number"}catch{return!1}};function ot(C,d,y){tn(C,k=>{k.call(t,d,y,Qt)})}let da=function(d){let y=null;if(ot(pe.beforeSanitizeElements,d,null),fr(d))return Pe(d),!0;let k=ie(d.nodeName);if(ot(pe.uponSanitizeElement,d,{tagName:k,allowedTags:oe}),kn&&d.hasChildNodes()&&!hr(d.firstElementChild)&&ge(/<[/\w!]/g,d.innerHTML)&&ge(/<[/\w!]/g,d.textContent)||kn&&d.namespaceURI===Ve&&k==="style"&&hr(d.firstElementChild)||d.nodeType===Ke.progressingInstruction||kn&&d.nodeType===Ke.comment&&ge(/<[/\w]/g,d.data))return Pe(d),!0;if(wn[k]||!(dt.tagCheck instanceof Function&&dt.tagCheck(k))&&!oe[k]){if(!wn[k]&&fa(k)&&(se.tagNameCheck instanceof RegExp&&ge(se.tagNameCheck,k)||se.tagNameCheck instanceof Function&&se.tagNameCheck(k)))return!1;if(is&&!Be[k]){let $=S(d),Y=_(d);if(Y&&$){let Ce=Y.length;for(let je=Ce-1;je>=0;--je){let De=f(Y[je],!0);$.insertBefore(De,g(d))}}}return Pe(d),!0}return(X?X(d):d.nodeType)===Ke.element&&!du(d)||(k==="noscript"||k==="noembed"||k==="noframes")&&ge(/<\/no(script|embed|frames)/i,d.innerHTML)?(Pe(d),!0):(pt&&d.nodeType===Ke.text&&(y=d.textContent,tn([sr,ir,ar],$=>{y=rn(y,$," ")}),d.textContent!==y&&(nn(t.removed,{element:d.cloneNode()}),d.textContent=y)),ot(pe.afterSanitizeElements,d,null),!1)},pa=function(d,y,k){if(lr[y]||Qi&&(y==="id"||y==="name")&&(k in n||k in uu))return!1;let j=le[y]||dt.attributeCheck instanceof Function&&dt.attributeCheck(y,d);if(!(rs&&!lr[y]&&ge(nu,y))){if(!(Yi&&ge(ru,y))){if(!j||lr[y]){if(!(fa(d)&&(se.tagNameCheck instanceof RegExp&&ge(se.tagNameCheck,d)||se.tagNameCheck instanceof Function&&se.tagNameCheck(d))&&(se.attributeNameCheck instanceof RegExp&&ge(se.attributeNameCheck,y)||se.attributeNameCheck instanceof Function&&se.attributeNameCheck(y,d))||y==="is"&&se.allowCustomizedBuiltInElements&&(se.tagNameCheck instanceof RegExp&&ge(se.tagNameCheck,k)||se.tagNameCheck instanceof Function&&se.tagNameCheck(k))))return!1}else if(!ls[y]){if(!ge(Ki,rn(k,Zi,""))){if(!((y==="src"||y==="xlink:href"||y==="href")&&d!=="script"&&Sa(k,"data:")===0&&na[d])){if(!(qi&&!ge(ou,rn(k,Zi,"")))){if(k)return!1}}}}}}return!0},pu=P({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),fa=function(d){return!pu[Pn(d)]&&ge(su,d)},ha=function(d){ot(pe.beforeSanitizeAttributes,d,null);let y=d.attributes;if(!y||fr(d))return;let k={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:le,forceKeepAttr:void 0},j=y.length;for(;j--;){let $=y[j],Y=$.name,Ce=$.namespaceURI,je=$.value,De=ie(Y),hs=je,fe=Y==="value"?hs:Cu(hs);if(k.attrName=De,k.attrValue=fe,k.keepAttr=!0,k.forceKeepAttr=void 0,ot(pe.uponSanitizeAttribute,d,k),fe=k.attrValue,ea&&(De==="id"||De==="name")&&Sa(fe,ta)!==0&&(Et(Y,d),fe=ta+fe),kn&&ge(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,fe)){Et(Y,d);continue}if(De==="attributename"&&Ta(fe,"href")){Et(Y,d);continue}if(k.forceKeepAttr)continue;if(!k.keepAttr){Et(Y,d);continue}if(!Ji&&ge(/\/>/i,fe)){Et(Y,d);continue}pt&&tn([sr,ir,ar],ga=>{fe=rn(fe,ga," ")});let ma=ie(d.nodeName);if(!pa(ma,De,fe)){Et(Y,d);continue}if(ee&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!Ce)switch(m.getAttributeType(ma,De)){case"TrustedHTML":{fe=ee.createHTML(fe);break}case"TrustedScriptURL":{fe=ee.createScriptURL(fe);break}}if(fe!==hs)try{Ce?d.setAttributeNS(Ce,Y,fe):d.setAttribute(Y,fe),fr(d)?Pe(d):_a(t.removed)}catch{Et(Y,d)}}ot(pe.afterSanitizeAttributes,d,null)},mr=function(d){let y=null,k=ca(d);for(ot(pe.beforeSanitizeShadowDOM,d,null);y=k.nextNode();)if(ot(pe.uponSanitizeShadowNode,y,null),da(y),ha(y),Cn(y.content)&&mr(y.content),(X?X(y):y.nodeType)===Ke.element){let $=b?b(y):y.shadowRoot;Cn($)&&(en($),mr($))}ot(pe.afterSanitizeShadowDOM,d,null)},en=function(d){let y=X?X(d):d.nodeType;if(y===Ke.element){let $=b?b(d):d.shadowRoot;Cn($)&&(en($),mr($))}let k=_?_(d):d.childNodes;if(!k)return;let j=[];tn(k,$=>{nn(j,$)});for(let $ of j)en($);if(y===Ke.element){let $=ae?ae(d):null;if(typeof $=="string"&&ie($)==="template"){let Y=d.content;Cn(Y)&&en(Y)}}};return t.sanitize=function(C){let d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},y=null,k=null,j=null,$=null;if(cs=!C,cs&&(C="<!-->"),typeof C!="string"&&!hr(C)&&(C=Lu(C),typeof C!="string"))throw Ln("dirty is not a string, aborting");if(!t.isSupported)return C;if(os||fs(d),t.removed=[],typeof C=="string"&&(An=!1),An){let je=ae?ae(C):C.nodeName;if(typeof je=="string"){let De=ie(je);if(!oe[De]||wn[De])throw Ln("root node is forbidden and cannot be sanitized in-place")}if(fr(C))throw Ln("root node is clobbered and cannot be sanitized in-place");en(C)}else if(hr(C))y=la("<!---->"),k=y.ownerDocument.importNode(C,!0),k.nodeType===Ke.element&&k.nodeName==="BODY"||k.nodeName==="HTML"?y=k:y.appendChild(k),en(k);else{if(!Yt&&!pt&&!xt&&C.indexOf("<")===-1)return ee&&ur?ee.createHTML(C):C;if(y=la(C),!y)return Yt?null:ur?ut:""}y&&ss&&Pe(y.firstChild);let Y=ca(An?C:y);for(;j=Y.nextNode();)da(j),ha(j),Cn(j.content)&&mr(j.content);if(An)return pt&&ua(C),C;if(Yt){if(pt&&ua(y),cr)for($=Qc.call(y.ownerDocument);y.firstChild;)$.appendChild(y.firstChild);else $=y;return(le.shadowroot||le.shadowrootmode)&&($=tu.call(r,$,!0)),$}let Ce=xt?y.outerHTML:y.innerHTML;return xt&&oe["!doctype"]&&y.ownerDocument&&y.ownerDocument.doctype&&y.ownerDocument.doctype.name&&ge(ju,y.ownerDocument.doctype.name)&&(Ce="<!DOCTYPE "+y.ownerDocument.doctype.name+`>
3
- `+Ce),pt&&tn([sr,ir,ar],je=>{Ce=rn(Ce,je," ")}),ee&&ur?ee.createHTML(Ce):Ce},t.setConfig=function(){let C=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};fs(C),os=!0},t.clearConfig=function(){Qt=null,os=!1},t.isValidAttribute=function(C,d,y){Qt||fs({});let k=ie(C),j=ie(d);return pa(k,j,y)},t.addHook=function(C,d){typeof d=="function"&&nn(pe[C],d)},t.removeHook=function(C,d){if(d!==void 0){let y=Au(pe[C],d);return y===-1?void 0:Iu(pe[C],y,1)[0]}return _a(pe[C])},t.removeHooks=function(C){pe[C]=[]},t.removeAllHooks=function(){pe=Oa()},t}var Da=Pa();function Fs(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var St=Fs();function Va(e){St=e}var _t={exec:()=>null};function sn(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),o=t[r];return o||(o=e(r),t[r]=o),o}}function z(e,t=""){let n=typeof e=="string"?e:e.source,r={replace:(o,s)=>{let i=typeof s=="string"?s:s.source;return i=i.replace(Ee.caret,"$1"),n=n.replace(o,i),r},getRegex:()=>new RegExp(n,t)};return r}var Ku=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),Ee={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:sn(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:sn(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:sn(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:sn(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:sn(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:sn(e=>new RegExp(`^ {0,${e}}>`))},Yu=/^(?:[ \t]*(?:\n|$))+/,qu=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Ju=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Gn=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Qu=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Hs=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,ja=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Wa=z(ja).replace(/bull/g,Hs).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),ed=z(ja).replace(/bull/g,Hs).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),$s=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,td=/^[^\n]+/,zs=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,nd=z(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",zs).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),rd=z(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Hs).getRegex(),_r="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Bs=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,od=z("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Bs).replace("tag",_r).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Xa=z($s).replace("hr",Gn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_r).getRegex(),sd=z(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Xa).getRegex(),Vs={blockquote:sd,code:qu,def:nd,fences:Ju,heading:Qu,hr:Gn,html:od,lheading:Wa,list:rd,newline:Yu,paragraph:Xa,table:_t,text:td},Ua=z("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Gn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_r).getRegex(),id={...Vs,lheading:ed,table:Ua,paragraph:z($s).replace("hr",Gn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Ua).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_r).getRegex()},ad={...Vs,html:z(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Bs).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:_t,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:z($s).replace("hr",Gn).replace("heading",` *#{1,6} *[^
4
- ]`).replace("lheading",Wa).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},ld=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,cd=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Za=/^( {2,}|\\)\n(?!\s*$)/,ud=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,an=/[\p{P}\p{S}]/u,Tr=/[\s\p{P}\p{S}]/u,js=/[^\s\p{P}\p{S}]/u,dd=z(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Tr).getRegex(),Ka=/(?!~)[\p{P}\p{S}]/u,pd=/(?!~)[\s\p{P}\p{S}]/u,fd=/(?:[^\s\p{P}\p{S}]|~)/u,hd=z(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Ku?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Ya=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,md=z(Ya,"u").replace(/punct/g,an).getRegex(),gd=z(Ya,"u").replace(/punct/g,Ka).getRegex(),qa="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",vd=z(qa,"gu").replace(/notPunctSpace/g,js).replace(/punctSpace/g,Tr).replace(/punct/g,an).getRegex(),yd=z(qa,"gu").replace(/notPunctSpace/g,fd).replace(/punctSpace/g,pd).replace(/punct/g,Ka).getRegex(),bd=z("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,js).replace(/punctSpace/g,Tr).replace(/punct/g,an).getRegex(),xd=z(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,an).getRegex(),Ed="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",_d=z(Ed,"gu").replace(/notPunctSpace/g,js).replace(/punctSpace/g,Tr).replace(/punct/g,an).getRegex(),Td=z(/\\(punct)/,"gu").replace(/punct/g,an).getRegex(),Sd=z(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),wd=z(Bs).replace("(?:-->|$)","-->").getRegex(),kd=z("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",wd).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),br=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Ad=z(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",br).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Ja=z(/^!?\[(label)\]\[(ref)\]/).replace("label",br).replace("ref",zs).getRegex(),Qa=z(/^!?\[(ref)\](?:\[\])?/).replace("ref",zs).getRegex(),Id=z("reflink|nolink(?!\\()","g").replace("reflink",Ja).replace("nolink",Qa).getRegex(),Ga=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Ws={_backpedal:_t,anyPunctuation:Td,autolink:Sd,blockSkip:hd,br:Za,code:cd,del:_t,delLDelim:_t,delRDelim:_t,emStrongLDelim:md,emStrongRDelimAst:vd,emStrongRDelimUnd:bd,escape:ld,link:Ad,nolink:Qa,punctuation:dd,reflink:Ja,reflinkSearch:Id,tag:kd,text:ud,url:_t},Cd={...Ws,link:z(/^!?\[(label)\]\((.*?)\)/).replace("label",br).getRegex(),reflink:z(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",br).getRegex()},Ds={...Ws,emStrongRDelimAst:yd,emStrongLDelim:gd,delLDelim:xd,delRDelim:_d,url:z(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Ga).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:z(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Ga).getRegex()},Nd={...Ds,br:z(Za).replace("{2,}","*").getRegex(),text:z(Ds.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},yr={normal:Vs,gfm:id,pedantic:ad},Dn={normal:Ws,gfm:Ds,breaks:Nd,pedantic:Cd},Rd={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Fa=e=>Rd[e];function qe(e,t){if(t){if(Ee.escapeTest.test(e))return e.replace(Ee.escapeReplace,Fa)}else if(Ee.escapeTestNoEncode.test(e))return e.replace(Ee.escapeReplaceNoEncode,Fa);return e}function Ha(e){try{e=encodeURI(e).replace(Ee.percentDecode,"%")}catch{return null}return e}function $a(e,t){let n=e.replace(Ee.findPipe,(s,i,a)=>{let u=!1,c=i;for(;--c>=0&&a[c]==="\\";)u=!u;return u?"|":" |"}),r=n.split(Ee.splitPipe),o=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),t)if(r.length>t)r.splice(t);else for(;r.length<t;)r.push("");for(;o<r.length;o++)r[o]=r[o].trim().replace(Ee.slashPipe,"|");return r}function ft(e,t,n){let r=e.length;if(r===0)return"";let o=0;for(;o<r;){let s=e.charAt(r-o-1);if(s===t&&!n)o++;else if(s!==t&&n)o++;else break}return e.slice(0,r-o)}function za(e){let t=e.split(`
5
- `),n=t.length-1;for(;n>=0&&Ee.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
6
- `)}function Od(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]==="\\")r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function Md(e,t=0){let n=t,r="";for(let o of e)if(o===" "){let s=4-n%4;r+=" ".repeat(s),n+=s}else r+=o,n++;return r}function Ba(e,t,n,r,o){let s=t.href,i=t.title||null,a=e[1].replace(o.other.outputLinkReplace,"$1");r.state.inLink=!0;let u={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:s,title:i,text:a,tokens:r.inlineTokens(a)};return r.state.inLink=!1,u}function Ld(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let o=r[1];return t.split(`
1
+ var xu=Object.defineProperty;var ys=(t,e)=>{for(var n in e)xu(t,n,{get:e[n],enumerable:!0})};var yr="ag-ui-chat",bs="ag-ui-submit",xs="ag-ui-toggle",We={USER:"user",ASSISTANT:"assistant"},Rn="x-destructive",Es="x-confirm",Xe="x-summary",On="x-navigates",Ts=10,de={PENDING:"pending",DONE:"done",ERROR:"error",DECLINED:"declined"},Ze={MINIMAL:"minimal",COMPACT:"compact",FULL:"full"};var Eu=/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;function xa(t,e){let n=[];return{text:t.replace(Eu,(o,s)=>{let i=e[s];return i==null||i===""?(n.includes(s)||n.push(s),o):String(i)}),missing:n}}function Tu(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.name=="string"&&typeof e.title=="string"&&typeof e.prompt=="string"}function _s(t){return Array.isArray(t)?t.filter(Tu):[]}var Mn=class{#e=new Map;register(e){this.#e.set(e.name,e)}has(e){return this.#e.has(e)}get(e){let n=this.#e.get(e);if(n===void 0)throw new Error(`tool "${e}" is not registered`);return n}tools(){return[...this.#e.values()].map(e=>({name:e.name,description:e.description,parameters:e.parameters}))}};function Ss(t){return t[Rn]===!0}function ws(t){return t[On]===!0}function ks(t,e){return!e||t===null?[]:[{description:"page_map",value:JSON.stringify(t())}]}function As(t){let e={};if(!Array.isArray(t))return e;for(let n of t){if(n===null||typeof n!="object")continue;let r=n,o=r.name,s=r.summary;typeof o=="string"&&typeof s=="string"&&(e[o]=s)}return e}var Ea=/:([A-Za-z_][A-Za-z0-9_]*)/g;function _u(t){let e=[];for(let n of t.matchAll(Ea)){let r=n[1];r!==void 0&&e.push(r)}return e}function Su(t,e,n){let r={...n};return{path:e.replace(Ea,(s,i)=>{let a=n[i];if(a==null||String(a)==="")throw new Error(`route "${t}" requires path param "${i}"`);return delete r[i],encodeURIComponent(String(a))}),leftover:r}}function wu(t,e){let n=new URLSearchParams;for(let[o,s]of Object.entries(e))n.set(o,String(s));let r=n.toString();return r===""?t:`${t}?${r}`}function Is(t,e){return[{name:"list_routes",description:"List the routes the app can navigate to. Each route's `pathParams` names the dynamic segments to pass as `params` to `navigate_to_route`.",parameters:{type:"object",properties:{},required:[],[Xe]:"List pages"},handler:()=>t().map(n=>({...n,pathParams:_u(n.path)}))},{name:"navigate_to_route",description:"Navigate to one of the app's routes by its id, filling any dynamic `:name` path segments (and extra query params) from `params`.",parameters:{type:"object",properties:{route_id:{type:"string"},params:{type:"object"}},required:["route_id"],[On]:!0,[Xe]:"Navigate"},handler:n=>{let r=n.route_id,o=t().find(p=>p.id===r);if(o===void 0)throw new Error(`unknown route "${String(r)}"`);let s=n.params??{},{path:i,leftover:a}=Su(o.id,o.path,s),u=wu(i,a),l=e();return l!==null?l(u):window.location.assign(u),{navigated:!0,path:u}}}]}function Cs(t){let e=[{name:`read_${t.name}`,description:`Read the "${t.name}" state.`,parameters:{type:"object",properties:{},required:[],[Xe]:`Read ${t.name}`},handler:()=>t.read()}],n=t.write;return n!==void 0&&e.push({name:`set_${t.name}`,description:`Update the "${t.name}" state.`,parameters:{...t.schema??{type:"object"},[Rn]:!0,[Xe]:`Update ${t.name}`},handler:r=>n(r)}),e}function Ta(t,e){let n=document.createElement("button");return n.type="button",n.className=`confirm-btn confirm-btn--${t}`,n.textContent=e,n}function Ns(t,e,n={}){return new Promise(r=>{let o=document.createElement("div");o.className="confirm",o.setAttribute("data-tool-name",e.toolName),o.setAttribute("role","group"),o.setAttribute("aria-label","Confirm action");let s=document.createElement("div");s.className="confirm-body",s.textContent=e.message??`Run \u201C${e.toolName}\u201D?`;let i=document.createElement("pre");i.className="confirm-args",i.textContent=JSON.stringify(e.args,null,2);let a=document.createElement("div");a.className="confirm-actions";let u=Ta("cancel","Cancel"),l=Ta("confirm","Confirm"),p=!1,m=x=>{p||(p=!0,u.disabled=!0,l.disabled=!0,o.setAttribute("data-resolved",x?"confirmed":"declined"),r(x))};if(u.addEventListener("click",()=>m(!1)),l.addEventListener("click",()=>m(!0)),n.signal?.addEventListener("abort",()=>m(!1),{once:!0}),a.append(u,l),o.append(s,i,a),t.appendChild(o),n.signal?.aborted===!0){m(!1);return}l.focus()})}function Rs(t){let e=t.replace(/[._-]+/g," ").trim();return e===""?t:e.charAt(0).toUpperCase()+e.slice(1)}function _a(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function ku(t){if(Array.isArray(t))return t}function Au(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r,o,s,i,a=[],u=!0,l=!1;try{if(s=(n=n.call(t)).next,e!==0)for(;!(u=(r=s.call(n)).done)&&(a.push(r.value),a.length!==e);u=!0);}catch(p){l=!0,o=p}finally{try{if(!u&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(l)throw o}}return a}}function Iu(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
2
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Cu(t,e){return ku(t)||Au(t,e)||Nu(t,e)||Iu()}function Nu(t,e){if(t){if(typeof t=="string")return _a(t,e);var n={}.toString.call(t).slice(8,-1);return n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set"?Array.from(t):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_a(t,e):void 0}}var Da=Object.entries,Sa=Object.setPrototypeOf,Ru=Object.isFrozen,Ou=Object.getPrototypeOf,Mu=Object.getOwnPropertyDescriptor,Se=Object.freeze,Ne=Object.seal,sn=Object.create,Ua=typeof Reflect<"u"&&Reflect,Us=Ua.apply,Gs=Ua.construct;Se||(Se=function(e){return e});Ne||(Ne=function(e){return e});Us||(Us=function(e,n){for(var r=arguments.length,o=new Array(r>2?r-2:0),s=2;s<r;s++)o[s-2]=arguments[s];return e.apply(n,o)});Gs||(Gs=function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return new e(...r)});var nn=ce(Array.prototype.forEach),Lu=ce(Array.prototype.lastIndexOf),wa=ce(Array.prototype.pop),rn=ce(Array.prototype.push),Pu=ce(Array.prototype.splice),_e=Array.isArray,Dn=ce(String.prototype.toLowerCase),Os=ce(String.prototype.toString),ka=ce(String.prototype.match),on=ce(String.prototype.replace),Aa=ce(String.prototype.indexOf),Du=ce(String.prototype.trim),Uu=ce(Number.prototype.toString),Gu=ce(Boolean.prototype.toString),Ia=typeof BigInt>"u"?null:ce(BigInt.prototype.toString),Ca=typeof Symbol>"u"?null:ce(Symbol.prototype.toString),ne=ce(Object.prototype.hasOwnProperty),Ln=ce(Object.prototype.toString),ge=ce(RegExp.prototype.test),Pn=Hu(TypeError);function ce(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return Us(t,e,r)}}function Hu(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return Gs(t,n)}}function P(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Dn;if(Sa&&Sa(t,null),!_e(e))return t;let r=e.length;for(;r--;){let o=e[r];if(typeof o=="string"){let s=n(o);s!==o&&(Ru(e)||(e[r]=s),o=s)}t[o]=!0}return t}function Fu(t){for(let e=0;e<t.length;e++)ne(t,e)||(t[e]=null);return t}function xe(t){let e=sn(null);for(let r of Da(t)){var n=Cu(r,2);let o=n[0],s=n[1];ne(t,o)&&(_e(s)?e[o]=Fu(s):s&&typeof s=="object"&&s.constructor===Object?e[o]=xe(s):e[o]=s)}return e}function $u(t){switch(typeof t){case"string":return t;case"number":return Uu(t);case"boolean":return Gu(t);case"bigint":return Ia?Ia(t):"0";case"symbol":return Ca?Ca(t):"Symbol()";case"undefined":return Ln(t);case"function":case"object":{if(t===null)return Ln(t);let e=t,n=Ye(e,"toString");if(typeof n=="function"){let r=n(e);return typeof r=="string"?r:Ln(r)}return Ln(t)}default:return Ln(t)}}function Ye(t,e){for(;t!==null;){let r=Mu(t,e);if(r){if(r.get)return ce(r.get);if(typeof r.value=="function")return ce(r.value)}t=Ou(t)}function n(){return null}return n}function zu(t){try{return ge(t,""),!0}catch{return!1}}var Na=Se(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Ms=Se(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Ls=Se(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Bu=Se(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Ps=Se(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Vu=Se(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Ra=Se(["#text"]),Oa=Se(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Ds=Se(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Ma=Se(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),br=Se(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),ju=Ne(/{{[\w\W]*|^[\w\W]*}}/g),Wu=Ne(/<%[\w\W]*|^[\w\W]*%>/g),Xu=Ne(/\${[\w\W]*/g),Zu=Ne(/^data-[\-\w.\u00B7-\uFFFF]+$/),Ku=Ne(/^aria-[\-\w]+$/),La=Ne(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Yu=Ne(/^(?:\w+script|data):/i),qu=Ne(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Ju=Ne(/^html$/i),Qu=Ne(/^[a-z][.\w]*(-[.\w]+)+$/i),Ke={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},ed=function(){return typeof window>"u"?null:window},td=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null,o="data-tt-policy-suffix";n&&n.hasAttribute(o)&&(r=n.getAttribute(o));let s="dompurify"+(r?"#"+r:"");try{return e.createPolicy(s,{createHTML(i){return i},createScriptURL(i){return i}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},Pa=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Ga(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:ed(),e=C=>Ga(C);if(e.version="3.4.7",e.removed=[],!t||!t.document||t.document.nodeType!==Ke.document||!t.Element)return e.isSupported=!1,e;let n=t.document,r=n,o=r.currentScript;t.DocumentFragment;let s=t.HTMLTemplateElement,i=t.Node,a=t.Element,u=t.NodeFilter,l=t.NamedNodeMap;l===void 0&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;let p=t.DOMParser,m=t.trustedTypes,x=a.prototype,f=Ye(x,"cloneNode"),h=Ye(x,"remove"),g=Ye(x,"nextSibling"),T=Ye(x,"childNodes"),S=Ye(x,"parentNode"),b=Ye(x,"shadowRoot"),H=Ye(x,"attributes"),X=i&&i.prototype?Ye(i.prototype,"nodeType"):null,ae=i&&i.prototype?Ye(i.prototype,"nodeName"):null;if(typeof s=="function"){let C=n.createElement("template");C.content&&C.content.ownerDocument&&(n=C.content.ownerDocument)}let ee,ut="",ir=n,rs=ir.implementation,Yi=ir.createNodeIterator,iu=ir.createDocumentFragment,au=ir.getElementsByTagName,lu=r.importNode,pe=Pa();e.isSupported=typeof Da=="function"&&typeof S=="function"&&rs&&rs.createHTMLDocument!==void 0;let ar=ju,lr=Wu,cr=Xu,cu=Zu,uu=Ku,du=Yu,qi=qu,pu=Qu,Ji=La,oe=null,os=P({},[...Na,...Ms,...Ls,...Ps,...Ra]),le=null,ss=P({},[...Oa,...Ds,...Ma,...br]),se=Object.seal(sn(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),kn=null,ur=null,dt=Object.seal(sn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),Qi=!0,is=!0,ea=!1,ta=!0,pt=!1,An=!0,xt=!1,as=!1,ls=!1,qt=!1,dr=!1,pr=!1,na=!0,ra=!1,oa="user-content-",cs=!0,In=!1,Jt={},Be=null,us=P({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),sa=null,ia=P({},["audio","video","img","source","image","track"]),ds=null,aa=P({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),fr="http://www.w3.org/1998/Math/MathML",hr="http://www.w3.org/2000/svg",Ve="http://www.w3.org/1999/xhtml",Qt=Ve,ps=!1,fs=null,fu=P({},[fr,hr,Ve],Os),hs=P({},["mi","mo","mn","ms","mtext"]),ms=P({},["annotation-xml"]),hu=P({},["title","style","font","a","script"]),Cn=null,mu=["application/xhtml+xml","text/html"],gu="text/html",ie=null,en=null,vu=n.createElement("form"),la=function(d){return d instanceof RegExp||d instanceof Function},gs=function(){let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(en&&en===d)return;(!d||typeof d!="object")&&(d={}),d=xe(d),Cn=mu.indexOf(d.PARSER_MEDIA_TYPE)===-1?gu:d.PARSER_MEDIA_TYPE,ie=Cn==="application/xhtml+xml"?Os:Dn,oe=ne(d,"ALLOWED_TAGS")&&_e(d.ALLOWED_TAGS)?P({},d.ALLOWED_TAGS,ie):os,le=ne(d,"ALLOWED_ATTR")&&_e(d.ALLOWED_ATTR)?P({},d.ALLOWED_ATTR,ie):ss,fs=ne(d,"ALLOWED_NAMESPACES")&&_e(d.ALLOWED_NAMESPACES)?P({},d.ALLOWED_NAMESPACES,Os):fu,ds=ne(d,"ADD_URI_SAFE_ATTR")&&_e(d.ADD_URI_SAFE_ATTR)?P(xe(aa),d.ADD_URI_SAFE_ATTR,ie):aa,sa=ne(d,"ADD_DATA_URI_TAGS")&&_e(d.ADD_DATA_URI_TAGS)?P(xe(ia),d.ADD_DATA_URI_TAGS,ie):ia,Be=ne(d,"FORBID_CONTENTS")&&_e(d.FORBID_CONTENTS)?P({},d.FORBID_CONTENTS,ie):us,kn=ne(d,"FORBID_TAGS")&&_e(d.FORBID_TAGS)?P({},d.FORBID_TAGS,ie):xe({}),ur=ne(d,"FORBID_ATTR")&&_e(d.FORBID_ATTR)?P({},d.FORBID_ATTR,ie):xe({}),Jt=ne(d,"USE_PROFILES")?d.USE_PROFILES&&typeof d.USE_PROFILES=="object"?xe(d.USE_PROFILES):d.USE_PROFILES:!1,Qi=d.ALLOW_ARIA_ATTR!==!1,is=d.ALLOW_DATA_ATTR!==!1,ea=d.ALLOW_UNKNOWN_PROTOCOLS||!1,ta=d.ALLOW_SELF_CLOSE_IN_ATTR!==!1,pt=d.SAFE_FOR_TEMPLATES||!1,An=d.SAFE_FOR_XML!==!1,xt=d.WHOLE_DOCUMENT||!1,qt=d.RETURN_DOM||!1,dr=d.RETURN_DOM_FRAGMENT||!1,pr=d.RETURN_TRUSTED_TYPE||!1,ls=d.FORCE_BODY||!1,na=d.SANITIZE_DOM!==!1,ra=d.SANITIZE_NAMED_PROPS||!1,cs=d.KEEP_CONTENT!==!1,In=d.IN_PLACE||!1,Ji=zu(d.ALLOWED_URI_REGEXP)?d.ALLOWED_URI_REGEXP:La,Qt=typeof d.NAMESPACE=="string"?d.NAMESPACE:Ve,hs=ne(d,"MATHML_TEXT_INTEGRATION_POINTS")&&d.MATHML_TEXT_INTEGRATION_POINTS&&typeof d.MATHML_TEXT_INTEGRATION_POINTS=="object"?xe(d.MATHML_TEXT_INTEGRATION_POINTS):P({},["mi","mo","mn","ms","mtext"]),ms=ne(d,"HTML_INTEGRATION_POINTS")&&d.HTML_INTEGRATION_POINTS&&typeof d.HTML_INTEGRATION_POINTS=="object"?xe(d.HTML_INTEGRATION_POINTS):P({},["annotation-xml"]);let y=ne(d,"CUSTOM_ELEMENT_HANDLING")&&d.CUSTOM_ELEMENT_HANDLING&&typeof d.CUSTOM_ELEMENT_HANDLING=="object"?xe(d.CUSTOM_ELEMENT_HANDLING):sn(null);if(se=sn(null),ne(y,"tagNameCheck")&&la(y.tagNameCheck)&&(se.tagNameCheck=y.tagNameCheck),ne(y,"attributeNameCheck")&&la(y.attributeNameCheck)&&(se.attributeNameCheck=y.attributeNameCheck),ne(y,"allowCustomizedBuiltInElements")&&typeof y.allowCustomizedBuiltInElements=="boolean"&&(se.allowCustomizedBuiltInElements=y.allowCustomizedBuiltInElements),pt&&(is=!1),dr&&(qt=!0),Jt&&(oe=P({},Ra),le=sn(null),Jt.html===!0&&(P(oe,Na),P(le,Oa)),Jt.svg===!0&&(P(oe,Ms),P(le,Ds),P(le,br)),Jt.svgFilters===!0&&(P(oe,Ls),P(le,Ds),P(le,br)),Jt.mathMl===!0&&(P(oe,Ps),P(le,Ma),P(le,br))),dt.tagCheck=null,dt.attributeCheck=null,ne(d,"ADD_TAGS")&&(typeof d.ADD_TAGS=="function"?dt.tagCheck=d.ADD_TAGS:_e(d.ADD_TAGS)&&(oe===os&&(oe=xe(oe)),P(oe,d.ADD_TAGS,ie))),ne(d,"ADD_ATTR")&&(typeof d.ADD_ATTR=="function"?dt.attributeCheck=d.ADD_ATTR:_e(d.ADD_ATTR)&&(le===ss&&(le=xe(le)),P(le,d.ADD_ATTR,ie))),ne(d,"ADD_URI_SAFE_ATTR")&&_e(d.ADD_URI_SAFE_ATTR)&&P(ds,d.ADD_URI_SAFE_ATTR,ie),ne(d,"FORBID_CONTENTS")&&_e(d.FORBID_CONTENTS)&&(Be===us&&(Be=xe(Be)),P(Be,d.FORBID_CONTENTS,ie)),ne(d,"ADD_FORBID_CONTENTS")&&_e(d.ADD_FORBID_CONTENTS)&&(Be===us&&(Be=xe(Be)),P(Be,d.ADD_FORBID_CONTENTS,ie)),cs&&(oe["#text"]=!0),xt&&P(oe,["html","head","body"]),oe.table&&(P(oe,["tbody"]),delete kn.tbody),d.TRUSTED_TYPES_POLICY){if(typeof d.TRUSTED_TYPES_POLICY.createHTML!="function")throw Pn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof d.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Pn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');ee=d.TRUSTED_TYPES_POLICY,ut=ee.createHTML("")}else ee===void 0&&(ee=td(m,o)),ee!==null&&typeof ut=="string"&&(ut=ee.createHTML(""));(pe.uponSanitizeElement.length>0||pe.uponSanitizeAttribute.length>0)&&oe===os&&(oe=xe(oe)),pe.uponSanitizeAttribute.length>0&&le===ss&&(le=xe(le)),Se&&Se(d),en=d},ca=P({},[...Ms,...Ls,...Bu]),ua=P({},[...Ps,...Vu]),yu=function(d){let y=S(d);(!y||!y.tagName)&&(y={namespaceURI:Qt,tagName:"template"});let k=Dn(d.tagName),j=Dn(y.tagName);return fs[d.namespaceURI]?d.namespaceURI===hr?y.namespaceURI===Ve?k==="svg":y.namespaceURI===fr?k==="svg"&&(j==="annotation-xml"||hs[j]):!!ca[k]:d.namespaceURI===fr?y.namespaceURI===Ve?k==="math":y.namespaceURI===hr?k==="math"&&ms[j]:!!ua[k]:d.namespaceURI===Ve?y.namespaceURI===hr&&!ms[j]||y.namespaceURI===fr&&!hs[j]?!1:!ua[k]&&(hu[k]||!ca[k]):!!(Cn==="application/xhtml+xml"&&fs[d.namespaceURI]):!1},Pe=function(d){rn(e.removed,{element:d});try{S(d).removeChild(d)}catch{h(d)}},Et=function(d,y){try{rn(e.removed,{attribute:y.getAttributeNode(d),from:y})}catch{rn(e.removed,{attribute:null,from:y})}if(y.removeAttribute(d),d==="is")if(qt||dr)try{Pe(y)}catch{}else try{y.setAttribute(d,"")}catch{}},da=function(d){let y=null,k=null;if(ls)d="<remove></remove>"+d;else{let Y=ka(d,/^[\r\n\t ]+/);k=Y&&Y[0]}Cn==="application/xhtml+xml"&&Qt===Ve&&(d='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+d+"</body></html>");let j=ee?ee.createHTML(d):d;if(Qt===Ve)try{y=new p().parseFromString(j,Cn)}catch{}if(!y||!y.documentElement){y=rs.createDocument(Qt,"template",null);try{y.documentElement.innerHTML=ps?ut:j}catch{}}let $=y.body||y.documentElement;return d&&k&&$.insertBefore(n.createTextNode(k),$.childNodes[0]||null),Qt===Ve?au.call(y,xt?"html":"body")[0]:xt?y.documentElement:$},pa=function(d){return Yi.call(d.ownerDocument||d,d,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT|u.SHOW_PROCESSING_INSTRUCTION|u.SHOW_CDATA_SECTION,null)},fa=function(d){d.normalize();let y=Yi.call(d.ownerDocument||d,d,u.SHOW_TEXT|u.SHOW_COMMENT|u.SHOW_CDATA_SECTION|u.SHOW_PROCESSING_INSTRUCTION,null),k=y.nextNode();for(;k;){let j=k.data;nn([ar,lr,cr],$=>{j=on(j,$," ")}),k.data=j,k=y.nextNode()}},mr=function(d){let y=ae?ae(d):null;return typeof y!="string"||ie(y)!=="form"?!1:typeof d.nodeName!="string"||typeof d.textContent!="string"||typeof d.removeChild!="function"||d.attributes!==H(d)||typeof d.removeAttribute!="function"||typeof d.setAttribute!="function"||typeof d.namespaceURI!="string"||typeof d.insertBefore!="function"||typeof d.hasChildNodes!="function"||d.nodeType!==X(d)||d.childNodes!==T(d)},Nn=function(d){if(!X||typeof d!="object"||d===null)return!1;try{return X(d)===Ke.documentFragment}catch{return!1}},gr=function(d){if(!X||typeof d!="object"||d===null)return!1;try{return typeof X(d)=="number"}catch{return!1}};function ot(C,d,y){nn(C,k=>{k.call(e,d,y,en)})}let ha=function(d){let y=null;if(ot(pe.beforeSanitizeElements,d,null),mr(d))return Pe(d),!0;let k=ie(d.nodeName);if(ot(pe.uponSanitizeElement,d,{tagName:k,allowedTags:oe}),An&&d.hasChildNodes()&&!gr(d.firstElementChild)&&ge(/<[/\w!]/g,d.innerHTML)&&ge(/<[/\w!]/g,d.textContent)||An&&d.namespaceURI===Ve&&k==="style"&&gr(d.firstElementChild)||d.nodeType===Ke.progressingInstruction||An&&d.nodeType===Ke.comment&&ge(/<[/\w]/g,d.data))return Pe(d),!0;if(kn[k]||!(dt.tagCheck instanceof Function&&dt.tagCheck(k))&&!oe[k]){if(!kn[k]&&ga(k)&&(se.tagNameCheck instanceof RegExp&&ge(se.tagNameCheck,k)||se.tagNameCheck instanceof Function&&se.tagNameCheck(k)))return!1;if(cs&&!Be[k]){let $=S(d),Y=T(d);if(Y&&$){let Ce=Y.length;for(let je=Ce-1;je>=0;--je){let De=f(Y[je],!0);$.insertBefore(De,g(d))}}}return Pe(d),!0}return(X?X(d):d.nodeType)===Ke.element&&!yu(d)||(k==="noscript"||k==="noembed"||k==="noframes")&&ge(/<\/no(script|embed|frames)/i,d.innerHTML)?(Pe(d),!0):(pt&&d.nodeType===Ke.text&&(y=d.textContent,nn([ar,lr,cr],$=>{y=on(y,$," ")}),d.textContent!==y&&(rn(e.removed,{element:d.cloneNode()}),d.textContent=y)),ot(pe.afterSanitizeElements,d,null),!1)},ma=function(d,y,k){if(ur[y]||na&&(y==="id"||y==="name")&&(k in n||k in vu))return!1;let j=le[y]||dt.attributeCheck instanceof Function&&dt.attributeCheck(y,d);if(!(is&&!ur[y]&&ge(cu,y))){if(!(Qi&&ge(uu,y))){if(!j||ur[y]){if(!(ga(d)&&(se.tagNameCheck instanceof RegExp&&ge(se.tagNameCheck,d)||se.tagNameCheck instanceof Function&&se.tagNameCheck(d))&&(se.attributeNameCheck instanceof RegExp&&ge(se.attributeNameCheck,y)||se.attributeNameCheck instanceof Function&&se.attributeNameCheck(y,d))||y==="is"&&se.allowCustomizedBuiltInElements&&(se.tagNameCheck instanceof RegExp&&ge(se.tagNameCheck,k)||se.tagNameCheck instanceof Function&&se.tagNameCheck(k))))return!1}else if(!ds[y]){if(!ge(Ji,on(k,qi,""))){if(!((y==="src"||y==="xlink:href"||y==="href")&&d!=="script"&&Aa(k,"data:")===0&&sa[d])){if(!(ea&&!ge(du,on(k,qi,"")))){if(k)return!1}}}}}}return!0},bu=P({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),ga=function(d){return!bu[Dn(d)]&&ge(pu,d)},va=function(d){ot(pe.beforeSanitizeAttributes,d,null);let y=d.attributes;if(!y||mr(d))return;let k={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:le,forceKeepAttr:void 0},j=y.length;for(;j--;){let $=y[j],Y=$.name,Ce=$.namespaceURI,je=$.value,De=ie(Y),vs=je,fe=Y==="value"?vs:Du(vs);if(k.attrName=De,k.attrValue=fe,k.keepAttr=!0,k.forceKeepAttr=void 0,ot(pe.uponSanitizeAttribute,d,k),fe=k.attrValue,ra&&(De==="id"||De==="name")&&Aa(fe,oa)!==0&&(Et(Y,d),fe=oa+fe),An&&ge(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,fe)){Et(Y,d);continue}if(De==="attributename"&&ka(fe,"href")){Et(Y,d);continue}if(k.forceKeepAttr)continue;if(!k.keepAttr){Et(Y,d);continue}if(!ta&&ge(/\/>/i,fe)){Et(Y,d);continue}pt&&nn([ar,lr,cr],ba=>{fe=on(fe,ba," ")});let ya=ie(d.nodeName);if(!ma(ya,De,fe)){Et(Y,d);continue}if(ee&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!Ce)switch(m.getAttributeType(ya,De)){case"TrustedHTML":{fe=ee.createHTML(fe);break}case"TrustedScriptURL":{fe=ee.createScriptURL(fe);break}}if(fe!==vs)try{Ce?d.setAttributeNS(Ce,Y,fe):d.setAttribute(Y,fe),mr(d)?Pe(d):wa(e.removed)}catch{Et(Y,d)}}ot(pe.afterSanitizeAttributes,d,null)},vr=function(d){let y=null,k=pa(d);for(ot(pe.beforeSanitizeShadowDOM,d,null);y=k.nextNode();)if(ot(pe.uponSanitizeShadowNode,y,null),ha(y),va(y),Nn(y.content)&&vr(y.content),(X?X(y):y.nodeType)===Ke.element){let $=b?b(y):y.shadowRoot;Nn($)&&(tn($),vr($))}ot(pe.afterSanitizeShadowDOM,d,null)},tn=function(d){let y=X?X(d):d.nodeType;if(y===Ke.element){let $=b?b(d):d.shadowRoot;Nn($)&&(tn($),vr($))}let k=T?T(d):d.childNodes;if(!k)return;let j=[];nn(k,$=>{rn(j,$)});for(let $ of j)tn($);if(y===Ke.element){let $=ae?ae(d):null;if(typeof $=="string"&&ie($)==="template"){let Y=d.content;Nn(Y)&&tn(Y)}}};return e.sanitize=function(C){let d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},y=null,k=null,j=null,$=null;if(ps=!C,ps&&(C="<!-->"),typeof C!="string"&&!gr(C)&&(C=$u(C),typeof C!="string"))throw Pn("dirty is not a string, aborting");if(!e.isSupported)return C;if(as||gs(d),e.removed=[],typeof C=="string"&&(In=!1),In){let je=ae?ae(C):C.nodeName;if(typeof je=="string"){let De=ie(je);if(!oe[De]||kn[De])throw Pn("root node is forbidden and cannot be sanitized in-place")}if(mr(C))throw Pn("root node is clobbered and cannot be sanitized in-place");tn(C)}else if(gr(C))y=da("<!---->"),k=y.ownerDocument.importNode(C,!0),k.nodeType===Ke.element&&k.nodeName==="BODY"||k.nodeName==="HTML"?y=k:y.appendChild(k),tn(k);else{if(!qt&&!pt&&!xt&&C.indexOf("<")===-1)return ee&&pr?ee.createHTML(C):C;if(y=da(C),!y)return qt?null:pr?ut:""}y&&ls&&Pe(y.firstChild);let Y=pa(In?C:y);for(;j=Y.nextNode();)ha(j),va(j),Nn(j.content)&&vr(j.content);if(In)return pt&&fa(C),C;if(qt){if(pt&&fa(y),dr)for($=iu.call(y.ownerDocument);y.firstChild;)$.appendChild(y.firstChild);else $=y;return(le.shadowroot||le.shadowrootmode)&&($=lu.call(r,$,!0)),$}let Ce=xt?y.outerHTML:y.innerHTML;return xt&&oe["!doctype"]&&y.ownerDocument&&y.ownerDocument.doctype&&y.ownerDocument.doctype.name&&ge(Ju,y.ownerDocument.doctype.name)&&(Ce="<!DOCTYPE "+y.ownerDocument.doctype.name+`>
3
+ `+Ce),pt&&nn([ar,lr,cr],je=>{Ce=on(Ce,je," ")}),ee&&pr?ee.createHTML(Ce):Ce},e.setConfig=function(){let C=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};gs(C),as=!0},e.clearConfig=function(){en=null,as=!1},e.isValidAttribute=function(C,d,y){en||gs({});let k=ie(C),j=ie(d);return ma(k,j,y)},e.addHook=function(C,d){typeof d=="function"&&rn(pe[C],d)},e.removeHook=function(C,d){if(d!==void 0){let y=Lu(pe[C],d);return y===-1?void 0:Pu(pe[C],y,1)[0]}return wa(pe[C])},e.removeHooks=function(C){pe[C]=[]},e.removeAllHooks=function(){pe=Pa()},e}var Ha=Ga();function zs(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var St=zs();function Xa(t){St=t}var Tt={exec:()=>null};function an(t){let e=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),o=e[r];return o||(o=t(r),e[r]=o),o}}function z(t,e=""){let n=typeof t=="string"?t:t.source,r={replace:(o,s)=>{let i=typeof s=="string"?s:s.source;return i=i.replace(Ee.caret,"$1"),n=n.replace(o,i),r},getRegex:()=>new RegExp(n,e)};return r}var nd=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),Ee={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:an(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:an(t=>new RegExp(`^ {0,${t}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:an(t=>new RegExp(`^ {0,${t}}(?:\`\`\`|~~~)`)),headingBeginRegex:an(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:an(t=>new RegExp(`^ {0,${t}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:an(t=>new RegExp(`^ {0,${t}}>`))},rd=/^(?:[ \t]*(?:\n|$))+/,od=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,sd=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Hn=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,id=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Bs=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Za=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Ka=z(Za).replace(/bull/g,Bs).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),ad=z(Za).replace(/bull/g,Bs).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Vs=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,ld=/^[^\n]+/,js=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,cd=z(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",js).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),ud=z(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Bs).getRegex(),Sr="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Ws=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,dd=z("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Ws).replace("tag",Sr).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Ya=z(Vs).replace("hr",Hn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Sr).getRegex(),pd=z(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ya).getRegex(),Xs={blockquote:pd,code:od,def:cd,fences:sd,heading:id,hr:Hn,html:dd,lheading:Ka,list:ud,newline:rd,paragraph:Ya,table:Tt,text:ld},Fa=z("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Hn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Sr).getRegex(),fd={...Xs,lheading:ad,table:Fa,paragraph:z(Vs).replace("hr",Hn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Fa).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Sr).getRegex()},hd={...Xs,html:z(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Ws).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Tt,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:z(Vs).replace("hr",Hn).replace("heading",` *#{1,6} *[^
4
+ ]`).replace("lheading",Ka).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},md=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,gd=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,qa=/^( {2,}|\\)\n(?!\s*$)/,vd=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,ln=/[\p{P}\p{S}]/u,wr=/[\s\p{P}\p{S}]/u,Zs=/[^\s\p{P}\p{S}]/u,yd=z(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,wr).getRegex(),Ja=/(?!~)[\p{P}\p{S}]/u,bd=/(?!~)[\s\p{P}\p{S}]/u,xd=/(?:[^\s\p{P}\p{S}]|~)/u,Ed=z(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",nd?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Qa=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Td=z(Qa,"u").replace(/punct/g,ln).getRegex(),_d=z(Qa,"u").replace(/punct/g,Ja).getRegex(),el="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Sd=z(el,"gu").replace(/notPunctSpace/g,Zs).replace(/punctSpace/g,wr).replace(/punct/g,ln).getRegex(),wd=z(el,"gu").replace(/notPunctSpace/g,xd).replace(/punctSpace/g,bd).replace(/punct/g,Ja).getRegex(),kd=z("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Zs).replace(/punctSpace/g,wr).replace(/punct/g,ln).getRegex(),Ad=z(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,ln).getRegex(),Id="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Cd=z(Id,"gu").replace(/notPunctSpace/g,Zs).replace(/punctSpace/g,wr).replace(/punct/g,ln).getRegex(),Nd=z(/\\(punct)/,"gu").replace(/punct/g,ln).getRegex(),Rd=z(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Od=z(Ws).replace("(?:-->|$)","-->").getRegex(),Md=z("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Od).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Er=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Ld=z(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Er).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),tl=z(/^!?\[(label)\]\[(ref)\]/).replace("label",Er).replace("ref",js).getRegex(),nl=z(/^!?\[(ref)\](?:\[\])?/).replace("ref",js).getRegex(),Pd=z("reflink|nolink(?!\\()","g").replace("reflink",tl).replace("nolink",nl).getRegex(),$a=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Ks={_backpedal:Tt,anyPunctuation:Nd,autolink:Rd,blockSkip:Ed,br:qa,code:gd,del:Tt,delLDelim:Tt,delRDelim:Tt,emStrongLDelim:Td,emStrongRDelimAst:Sd,emStrongRDelimUnd:kd,escape:md,link:Ld,nolink:nl,punctuation:yd,reflink:tl,reflinkSearch:Pd,tag:Md,text:vd,url:Tt},Dd={...Ks,link:z(/^!?\[(label)\]\((.*?)\)/).replace("label",Er).getRegex(),reflink:z(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Er).getRegex()},Hs={...Ks,emStrongRDelimAst:wd,emStrongLDelim:_d,delLDelim:Ad,delRDelim:Cd,url:z(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",$a).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:z(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",$a).getRegex()},Ud={...Hs,br:z(qa).replace("{2,}","*").getRegex(),text:z(Hs.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},xr={normal:Xs,gfm:fd,pedantic:hd},Un={normal:Ks,gfm:Hs,breaks:Ud,pedantic:Dd},Gd={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},za=t=>Gd[t];function qe(t,e){if(e){if(Ee.escapeTest.test(t))return t.replace(Ee.escapeReplace,za)}else if(Ee.escapeTestNoEncode.test(t))return t.replace(Ee.escapeReplaceNoEncode,za);return t}function Ba(t){try{t=encodeURI(t).replace(Ee.percentDecode,"%")}catch{return null}return t}function Va(t,e){let n=t.replace(Ee.findPipe,(s,i,a)=>{let u=!1,l=i;for(;--l>=0&&a[l]==="\\";)u=!u;return u?"|":" |"}),r=n.split(Ee.splitPipe),o=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),e)if(r.length>e)r.splice(e);else for(;r.length<e;)r.push("");for(;o<r.length;o++)r[o]=r[o].trim().replace(Ee.slashPipe,"|");return r}function ft(t,e,n){let r=t.length;if(r===0)return"";let o=0;for(;o<r;){let s=t.charAt(r-o-1);if(s===e&&!n)o++;else if(s!==e&&n)o++;else break}return t.slice(0,r-o)}function ja(t){let e=t.split(`
5
+ `),n=e.length-1;for(;n>=0&&Ee.blankLine.test(e[n]);)n--;return e.length-n<=2?t:e.slice(0,n+1).join(`
6
+ `)}function Hd(t,e){if(t.indexOf(e[1])===-1)return-1;let n=0;for(let r=0;r<t.length;r++)if(t[r]==="\\")r++;else if(t[r]===e[0])n++;else if(t[r]===e[1]&&(n--,n<0))return r;return n>0?-2:-1}function Fd(t,e=0){let n=e,r="";for(let o of t)if(o===" "){let s=4-n%4;r+=" ".repeat(s),n+=s}else r+=o,n++;return r}function Wa(t,e,n,r,o){let s=e.href,i=e.title||null,a=t[1].replace(o.other.outputLinkReplace,"$1");r.state.inLink=!0;let u={type:t[0].charAt(0)==="!"?"image":"link",raw:n,href:s,title:i,text:a,tokens:r.inlineTokens(a)};return r.state.inLink=!1,u}function $d(t,e,n){let r=t.match(n.other.indentCodeCompensation);if(r===null)return e;let o=r[1];return e.split(`
7
7
  `).map(s=>{let i=s.match(n.other.beginningSpace);if(i===null)return s;let[a]=i;return a.length>=o.length?s.slice(o.length):s}).join(`
8
- `)}var xr=class{options;rules;lexer;constructor(e){this.options=e||St}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:za(t[0]),r=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:r}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],r=Ld(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:r}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let r=ft(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:ft(t[0],`
9
- `),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:ft(t[0],`
10
- `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=ft(t[0],`
8
+ `)}var Tr=class{options;rules;lexer;constructor(t){this.options=t||St}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let n=this.options.pedantic?e[0]:ja(e[0]),r=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:r}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let n=e[0],r=$d(n,e[3]||"",this.rules);return{type:"code",raw:n,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:r}}}heading(t){let e=this.rules.block.heading.exec(t);if(e){let n=e[2].trim();if(this.rules.other.endingHash.test(n)){let r=ft(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:ft(e[0],`
9
+ `),depth:e[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(t){let e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:ft(e[0],`
10
+ `)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=ft(e[0],`
11
11
  `).split(`
12
- `),r="",o="",s=[];for(;n.length>0;){let i=!1,a=[],u;for(u=0;u<n.length;u++)if(this.rules.other.blockquoteStart.test(n[u]))a.push(n[u]),i=!0;else if(!i)a.push(n[u]);else break;n=n.slice(u);let c=a.join(`
13
- `),p=c.replace(this.rules.other.blockquoteSetextReplace,`
12
+ `),r="",o="",s=[];for(;n.length>0;){let i=!1,a=[],u;for(u=0;u<n.length;u++)if(this.rules.other.blockquoteStart.test(n[u]))a.push(n[u]),i=!0;else if(!i)a.push(n[u]);else break;n=n.slice(u);let l=a.join(`
13
+ `),p=l.replace(this.rules.other.blockquoteSetextReplace,`
14
14
  $1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
15
- ${c}`:c,o=o?`${o}
15
+ ${l}`:l,o=o?`${o}
16
16
  ${p}`:p;let m=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(p,s,!0),this.lexer.state.top=m,n.length===0)break;let x=s.at(-1);if(x?.type==="code")break;if(x?.type==="blockquote"){let f=x,h=f.raw+`
17
17
  `+n.join(`
18
18
  `),g=this.blockquote(h);s[s.length-1]=g,r=r.substring(0,r.length-f.raw.length)+g.raw,o=o.substring(0,o.length-f.text.length)+g.text;break}else if(x?.type==="list"){let f=x,h=f.raw+`
19
19
  `+n.join(`
20
20
  `),g=this.list(h);s[s.length-1]=g,r=r.substring(0,r.length-x.raw.length)+g.raw,o=o.substring(0,o.length-f.raw.length)+g.raw,n=h.substring(s.at(-1).raw.length).split(`
21
- `);continue}}return{type:"blockquote",raw:r,tokens:s,text:o}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),r=n.length>1,o={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let s=this.rules.other.listItemRegex(n),i=!1;for(;e;){let u=!1,c="",p="";if(!(t=s.exec(e))||this.rules.block.hr.test(e))break;c=t[0],e=e.substring(c.length);let m=Md(t[2].split(`
22
- `,1)[0],t[1].length),x=e.split(`
23
- `,1)[0],f=!m.trim(),h=0;if(this.options.pedantic?(h=2,p=m.trimStart()):f?h=t[1].length+1:(h=m.search(this.rules.other.nonSpaceChar),h=h>4?1:h,p=m.slice(h),h+=t[1].length),f&&this.rules.other.blankLine.test(x)&&(c+=x+`
24
- `,e=e.substring(x.length+1),u=!0),!u){let g=this.rules.other.nextBulletRegex(h),_=this.rules.other.hrRegex(h),S=this.rules.other.fencesBeginRegex(h),b=this.rules.other.headingBeginRegex(h),F=this.rules.other.htmlBeginRegex(h),X=this.rules.other.blockquoteBeginRegex(h);for(;e;){let ae=e.split(`
25
- `,1)[0],ee;if(x=ae,this.options.pedantic?(x=x.replace(this.rules.other.listReplaceNesting," "),ee=x):ee=x.replace(this.rules.other.tabCharGlobal," "),S.test(x)||b.test(x)||F.test(x)||X.test(x)||g.test(x)||_.test(x))break;if(ee.search(this.rules.other.nonSpaceChar)>=h||!x.trim())p+=`
26
- `+ee.slice(h);else{if(f||m.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||S.test(m)||b.test(m)||_.test(m))break;p+=`
27
- `+x}f=!x.trim(),c+=ae+`
28
- `,e=e.substring(ae.length+1),m=ee.slice(h)}}o.loose||(i?o.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(i=!0)),o.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(p),loose:!1,text:p,tokens:[]}),o.raw+=c}let a=o.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let u of o.items){this.lexer.state.top=!1,u.tokens=this.lexer.blockTokens(u.text,[]);let c=u.tokens[0];if(u.task&&(c?.type==="text"||c?.type==="paragraph")){u.text=u.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let m=this.lexer.inlineQueue.length-1;m>=0;m--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[m].src)){this.lexer.inlineQueue[m].src=this.lexer.inlineQueue[m].src.replace(this.rules.other.listReplaceTask,"");break}let p=this.rules.other.listTaskCheckbox.exec(u.raw);if(p){let m={type:"checkbox",raw:p[0]+" ",checked:p[0]!=="[ ]"};u.checked=m.checked,o.loose?u.tokens[0]&&["paragraph","text"].includes(u.tokens[0].type)&&"tokens"in u.tokens[0]&&u.tokens[0].tokens?(u.tokens[0].raw=m.raw+u.tokens[0].raw,u.tokens[0].text=m.raw+u.tokens[0].text,u.tokens[0].tokens.unshift(m)):u.tokens.unshift({type:"paragraph",raw:m.raw,text:m.raw,tokens:[m]}):u.tokens.unshift(m)}}else u.task&&(u.task=!1);if(!o.loose){let p=u.tokens.filter(x=>x.type==="space"),m=p.length>0&&p.some(x=>this.rules.other.anyLine.test(x.raw));o.loose=m}}if(o.loose)for(let u of o.items){u.loose=!0;for(let c of u.tokens)c.type==="text"&&(c.type="paragraph")}return o}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=za(t[0]);return{type:"html",block:!0,raw:n,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",o=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:ft(t[0],`
29
- `),href:r,title:o}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=$a(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
30
- `):[],s={type:"table",raw:ft(t[0],`
31
- `),header:[],align:[],rows:[]};if(n.length===r.length){for(let i of r)this.rules.other.tableAlignRight.test(i)?s.align.push("right"):this.rules.other.tableAlignCenter.test(i)?s.align.push("center"):this.rules.other.tableAlignLeft.test(i)?s.align.push("left"):s.align.push(null);for(let i=0;i<n.length;i++)s.header.push({text:n[i],tokens:this.lexer.inline(n[i]),header:!0,align:s.align[i]});for(let i of o)s.rows.push($a(i,s.header.length).map((a,u)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:s.align[u]})));return s}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:ft(t[0],`
32
- `),depth:t[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
33
- `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let s=ft(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=Od(t[2],"()");if(s===-2)return;if(s>-1){let i=(t[0].indexOf("!")===0?5:4)+t[1].length+s;t[2]=t[2].substring(0,s),t[0]=t[0].substring(0,i).trim(),t[3]=""}}let r=t[2],o="";if(this.options.pedantic){let s=this.rules.other.pedanticHrefTitle.exec(r);s&&(r=s[1],o=s[3])}else o=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),Ba(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=t[r.toLowerCase()];if(!o){let s=n[0].charAt(0);return{type:"text",raw:s,text:s}}return Ba(n,o,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let o=[...r[0]].length-1,s,i,a=o,u=0,c=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+o);(r=c.exec(t))!==null;){if(s=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!s)continue;if(i=[...s].length,r[3]||r[4]){a+=i;continue}else if((r[5]||r[6])&&o%3&&!((o+i)%3)){u+=i;continue}if(a-=i,a>0)continue;i=Math.min(i,i+a+u);let p=[...r[0]][0].length,m=e.slice(0,o+r.index+p+i);if(Math.min(o,i)%2){let f=m.slice(1,-1);return{type:"em",raw:m,text:f,tokens:this.lexer.inlineTokens(f)}}let x=m.slice(2,-2);return{type:"strong",raw:m,text:x,tokens:this.lexer.inlineTokens(x)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),o=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&o&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let o=[...r[0]].length-1,s,i,a=o,u=this.rules.inline.delRDelim;for(u.lastIndex=0,t=t.slice(-1*e.length+o);(r=u.exec(t))!==null;){if(s=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!s||(i=[...s].length,i!==o))continue;if(r[3]||r[4]){a+=i;continue}if(a-=i,a>0)continue;i=Math.min(i,i+a);let c=[...r[0]][0].length,p=e.slice(0,o+r.index+c+i),m=p.slice(o,-o);return{type:"del",raw:p,text:m,tokens:this.lexer.inlineTokens(m)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,r;return t[2]==="@"?(n=t[1],r="mailto:"+n):(n=t[1],r=n),{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,r;if(t[2]==="@")n=t[0],r="mailto:"+n;else{let o;do o=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(o!==t[0]);n=t[0],t[1]==="www."?r="http://"+t[0]:r=t[0]}return{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},Ue=class Us{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||St,this.options.tokenizer=this.options.tokenizer||new xr,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:Ee,block:yr.normal,inline:Dn.normal};this.options.pedantic?(n.block=yr.pedantic,n.inline=Dn.pedantic):this.options.gfm&&(n.block=yr.gfm,this.options.breaks?n.inline=Dn.breaks:n.inline=Dn.gfm),this.tokenizer.rules=n}static get rules(){return{block:yr,inline:Dn}}static lex(t,n){return new Us(n).lex(t)}static lexInline(t,n){return new Us(n).inlineTokens(t)}lex(t){t=t.replace(Ee.carriageReturn,`
34
- `),this.blockTokens(t,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,n=[],r=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(Ee.tabCharGlobal," ").replace(Ee.spaceLine,""));let o=1/0;for(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let s;if(this.options.extensions?.block?.some(a=>(s=a.call({lexer:this},t,n))?(t=t.substring(s.raw.length),n.push(s),!0):!1))continue;if(s=this.tokenizer.space(t)){t=t.substring(s.raw.length);let a=n.at(-1);s.raw.length===1&&a!==void 0?a.raw+=`
35
- `:n.push(s);continue}if(s=this.tokenizer.code(t)){t=t.substring(s.raw.length);let a=n.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
21
+ `);continue}}return{type:"blockquote",raw:r,tokens:s,text:o}}}list(t){let e=this.rules.block.list.exec(t);if(e){let n=e[1].trim(),r=n.length>1,o={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let s=this.rules.other.listItemRegex(n),i=!1;for(;t;){let u=!1,l="",p="";if(!(e=s.exec(t))||this.rules.block.hr.test(t))break;l=e[0],t=t.substring(l.length);let m=Fd(e[2].split(`
22
+ `,1)[0],e[1].length),x=t.split(`
23
+ `,1)[0],f=!m.trim(),h=0;if(this.options.pedantic?(h=2,p=m.trimStart()):f?h=e[1].length+1:(h=m.search(this.rules.other.nonSpaceChar),h=h>4?1:h,p=m.slice(h),h+=e[1].length),f&&this.rules.other.blankLine.test(x)&&(l+=x+`
24
+ `,t=t.substring(x.length+1),u=!0),!u){let g=this.rules.other.nextBulletRegex(h),T=this.rules.other.hrRegex(h),S=this.rules.other.fencesBeginRegex(h),b=this.rules.other.headingBeginRegex(h),H=this.rules.other.htmlBeginRegex(h),X=this.rules.other.blockquoteBeginRegex(h);for(;t;){let ae=t.split(`
25
+ `,1)[0],ee;if(x=ae,this.options.pedantic?(x=x.replace(this.rules.other.listReplaceNesting," "),ee=x):ee=x.replace(this.rules.other.tabCharGlobal," "),S.test(x)||b.test(x)||H.test(x)||X.test(x)||g.test(x)||T.test(x))break;if(ee.search(this.rules.other.nonSpaceChar)>=h||!x.trim())p+=`
26
+ `+ee.slice(h);else{if(f||m.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||S.test(m)||b.test(m)||T.test(m))break;p+=`
27
+ `+x}f=!x.trim(),l+=ae+`
28
+ `,t=t.substring(ae.length+1),m=ee.slice(h)}}o.loose||(i?o.loose=!0:this.rules.other.doubleBlankLine.test(l)&&(i=!0)),o.items.push({type:"list_item",raw:l,task:!!this.options.gfm&&this.rules.other.listIsTask.test(p),loose:!1,text:p,tokens:[]}),o.raw+=l}let a=o.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let u of o.items){this.lexer.state.top=!1,u.tokens=this.lexer.blockTokens(u.text,[]);let l=u.tokens[0];if(u.task&&(l?.type==="text"||l?.type==="paragraph")){u.text=u.text.replace(this.rules.other.listReplaceTask,""),l.raw=l.raw.replace(this.rules.other.listReplaceTask,""),l.text=l.text.replace(this.rules.other.listReplaceTask,"");for(let m=this.lexer.inlineQueue.length-1;m>=0;m--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[m].src)){this.lexer.inlineQueue[m].src=this.lexer.inlineQueue[m].src.replace(this.rules.other.listReplaceTask,"");break}let p=this.rules.other.listTaskCheckbox.exec(u.raw);if(p){let m={type:"checkbox",raw:p[0]+" ",checked:p[0]!=="[ ]"};u.checked=m.checked,o.loose?u.tokens[0]&&["paragraph","text"].includes(u.tokens[0].type)&&"tokens"in u.tokens[0]&&u.tokens[0].tokens?(u.tokens[0].raw=m.raw+u.tokens[0].raw,u.tokens[0].text=m.raw+u.tokens[0].text,u.tokens[0].tokens.unshift(m)):u.tokens.unshift({type:"paragraph",raw:m.raw,text:m.raw,tokens:[m]}):u.tokens.unshift(m)}}else u.task&&(u.task=!1);if(!o.loose){let p=u.tokens.filter(x=>x.type==="space"),m=p.length>0&&p.some(x=>this.rules.other.anyLine.test(x.raw));o.loose=m}}if(o.loose)for(let u of o.items){u.loose=!0;for(let l of u.tokens)l.type==="text"&&(l.type="paragraph")}return o}}html(t){let e=this.rules.block.html.exec(t);if(e){let n=ja(e[0]);return{type:"html",block:!0,raw:n,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:n}}}def(t){let e=this.rules.block.def.exec(t);if(e){let n=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",o=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:n,raw:ft(e[0],`
29
+ `),href:r,title:o}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let n=Va(e[1]),r=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
30
+ `):[],s={type:"table",raw:ft(e[0],`
31
+ `),header:[],align:[],rows:[]};if(n.length===r.length){for(let i of r)this.rules.other.tableAlignRight.test(i)?s.align.push("right"):this.rules.other.tableAlignCenter.test(i)?s.align.push("center"):this.rules.other.tableAlignLeft.test(i)?s.align.push("left"):s.align.push(null);for(let i=0;i<n.length;i++)s.header.push({text:n[i],tokens:this.lexer.inline(n[i]),header:!0,align:s.align[i]});for(let i of o)s.rows.push(Va(i,s.header.length).map((a,u)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:s.align[u]})));return s}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let n=e[1].trim();return{type:"heading",raw:ft(e[0],`
32
+ `),depth:e[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(t){let e=this.rules.block.paragraph.exec(t);if(e){let n=e[1].charAt(e[1].length-1)===`
33
+ `?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:n,tokens:this.lexer.inline(n)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let n=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let s=ft(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=Hd(e[2],"()");if(s===-2)return;if(s>-1){let i=(e[0].indexOf("!")===0?5:4)+e[1].length+s;e[2]=e[2].substring(0,s),e[0]=e[0].substring(0,i).trim(),e[3]=""}}let r=e[2],o="";if(this.options.pedantic){let s=this.rules.other.pedanticHrefTitle.exec(r);s&&(r=s[1],o=s[3])}else o=e[3]?e[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),Wa(e,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=e[r.toLowerCase()];if(!o){let s=n[0].charAt(0);return{type:"text",raw:s,text:s}}return Wa(n,o,n[0],this.lexer,this.rules)}}emStrong(t,e,n=""){let r=this.rules.inline.emStrongLDelim.exec(t);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let o=[...r[0]].length-1,s,i,a=o,u=0,l=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(l.lastIndex=0,e=e.slice(-1*t.length+o);(r=l.exec(e))!==null;){if(s=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!s)continue;if(i=[...s].length,r[3]||r[4]){a+=i;continue}else if((r[5]||r[6])&&o%3&&!((o+i)%3)){u+=i;continue}if(a-=i,a>0)continue;i=Math.min(i,i+a+u);let p=[...r[0]][0].length,m=t.slice(0,o+r.index+p+i);if(Math.min(o,i)%2){let f=m.slice(1,-1);return{type:"em",raw:m,text:f,tokens:this.lexer.inlineTokens(f)}}let x=m.slice(2,-2);return{type:"strong",raw:m,text:x,tokens:this.lexer.inlineTokens(x)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let n=e[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),o=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&o&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:e[0],text:n}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t,e,n=""){let r=this.rules.inline.delLDelim.exec(t);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let o=[...r[0]].length-1,s,i,a=o,u=this.rules.inline.delRDelim;for(u.lastIndex=0,e=e.slice(-1*t.length+o);(r=u.exec(e))!==null;){if(s=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!s||(i=[...s].length,i!==o))continue;if(r[3]||r[4]){a+=i;continue}if(a-=i,a>0)continue;i=Math.min(i,i+a);let l=[...r[0]][0].length,p=t.slice(0,o+r.index+l+i),m=p.slice(o,-o);return{type:"del",raw:p,text:m,tokens:this.lexer.inlineTokens(m)}}}}autolink(t){let e=this.rules.inline.autolink.exec(t);if(e){let n,r;return e[2]==="@"?(n=e[1],r="mailto:"+n):(n=e[1],r=n),{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let n,r;if(e[2]==="@")n=e[0],r="mailto:"+n;else{let o;do o=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(o!==e[0]);n=e[0],e[1]==="www."?r="http://"+e[0]:r=e[0]}return{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let n=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:n}}}},Ue=class Fs{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||St,this.options.tokenizer=this.options.tokenizer||new Tr,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:Ee,block:xr.normal,inline:Un.normal};this.options.pedantic?(n.block=xr.pedantic,n.inline=Un.pedantic):this.options.gfm&&(n.block=xr.gfm,this.options.breaks?n.inline=Un.breaks:n.inline=Un.gfm),this.tokenizer.rules=n}static get rules(){return{block:xr,inline:Un}}static lex(e,n){return new Fs(n).lex(e)}static lexInline(e,n){return new Fs(n).inlineTokens(e)}lex(e){e=e.replace(Ee.carriageReturn,`
34
+ `),this.blockTokens(e,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,n=[],r=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(Ee.tabCharGlobal," ").replace(Ee.spaceLine,""));let o=1/0;for(;e;){if(e.length<o)o=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let s;if(this.options.extensions?.block?.some(a=>(s=a.call({lexer:this},e,n))?(e=e.substring(s.raw.length),n.push(s),!0):!1))continue;if(s=this.tokenizer.space(e)){e=e.substring(s.raw.length);let a=n.at(-1);s.raw.length===1&&a!==void 0?a.raw+=`
35
+ `:n.push(s);continue}if(s=this.tokenizer.code(e)){e=e.substring(s.raw.length);let a=n.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
36
36
  `)?"":`
37
37
  `)+s.raw,a.text+=`
38
- `+s.text,this.inlineQueue.at(-1).src=a.text):n.push(s);continue}if(s=this.tokenizer.fences(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.heading(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.hr(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.blockquote(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.list(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.html(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.def(t)){t=t.substring(s.raw.length);let a=n.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
38
+ `+s.text,this.inlineQueue.at(-1).src=a.text):n.push(s);continue}if(s=this.tokenizer.fences(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.heading(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.hr(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.blockquote(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.list(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.html(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.def(e)){e=e.substring(s.raw.length);let a=n.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
39
39
  `)?"":`
40
40
  `)+s.raw,a.text+=`
41
- `+s.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[s.tag]||(this.tokens.links[s.tag]={href:s.href,title:s.title},n.push(s));continue}if(s=this.tokenizer.table(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.lheading(t)){t=t.substring(s.raw.length),n.push(s);continue}let i=t;if(this.options.extensions?.startBlock){let a=1/0,u=t.slice(1),c;this.options.extensions.startBlock.forEach(p=>{c=p.call({lexer:this},u),typeof c=="number"&&c>=0&&(a=Math.min(a,c))}),a<1/0&&a>=0&&(i=t.substring(0,a+1))}if(this.state.top&&(s=this.tokenizer.paragraph(i))){let a=n.at(-1);r&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
41
+ `+s.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[s.tag]||(this.tokens.links[s.tag]={href:s.href,title:s.title},n.push(s));continue}if(s=this.tokenizer.table(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.lheading(e)){e=e.substring(s.raw.length),n.push(s);continue}let i=e;if(this.options.extensions?.startBlock){let a=1/0,u=e.slice(1),l;this.options.extensions.startBlock.forEach(p=>{l=p.call({lexer:this},u),typeof l=="number"&&l>=0&&(a=Math.min(a,l))}),a<1/0&&a>=0&&(i=e.substring(0,a+1))}if(this.state.top&&(s=this.tokenizer.paragraph(i))){let a=n.at(-1);r&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
42
42
  `)?"":`
43
43
  `)+s.raw,a.text+=`
44
- `+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(s),r=i.length!==t.length,t=t.substring(s.raw.length);continue}if(s=this.tokenizer.text(t)){t=t.substring(s.raw.length);let a=n.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
44
+ `+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(s),r=i.length!==e.length,e=e.substring(s.raw.length);continue}if(s=this.tokenizer.text(e)){e=e.substring(s.raw.length);let a=n.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
45
45
  `)?"":`
46
46
  `)+s.raw,a.text+=`
47
- `+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(s);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){this.tokenizer.lexer=this;let r=t,o=null;if(this.tokens.links){let c=Object.keys(this.tokens.links);if(c.length>0)for(;(o=this.tokenizer.rules.inline.reflinkSearch.exec(r))!==null;)c.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(o=this.tokenizer.rules.inline.anyPunctuation.exec(r))!==null;)r=r.slice(0,o.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let s;for(;(o=this.tokenizer.rules.inline.blockSkip.exec(r))!==null;)s=o[2]?o[2].length:0,r=r.slice(0,o.index+s)+"["+"a".repeat(o[0].length-s-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let i=!1,a="",u=1/0;for(;t;){if(t.length<u)u=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}i||(a=""),i=!1;let c;if(this.options.extensions?.inline?.some(m=>(c=m.call({lexer:this},t,n))?(t=t.substring(c.raw.length),n.push(c),!0):!1))continue;if(c=this.tokenizer.escape(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.tag(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.link(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(c.raw.length);let m=n.at(-1);c.type==="text"&&m?.type==="text"?(m.raw+=c.raw,m.text+=c.text):n.push(c);continue}if(c=this.tokenizer.emStrong(t,r,a)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.codespan(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.br(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.del(t,r,a)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.autolink(t)){t=t.substring(c.raw.length),n.push(c);continue}if(!this.state.inLink&&(c=this.tokenizer.url(t))){t=t.substring(c.raw.length),n.push(c);continue}let p=t;if(this.options.extensions?.startInline){let m=1/0,x=t.slice(1),f;this.options.extensions.startInline.forEach(h=>{f=h.call({lexer:this},x),typeof f=="number"&&f>=0&&(m=Math.min(m,f))}),m<1/0&&m>=0&&(p=t.substring(0,m+1))}if(c=this.tokenizer.inlineText(p)){t=t.substring(c.raw.length),c.raw.slice(-1)!=="_"&&(a=c.raw.slice(-1)),i=!0;let m=n.at(-1);m?.type==="text"?(m.raw+=c.raw,m.text+=c.text):n.push(c);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return n}infiniteLoopError(t){let n="Infinite loop on byte: "+t;if(this.options.silent)console.error(n);else throw new Error(n)}},Er=class{options;parser;constructor(e){this.options=e||St}space(e){return""}code({text:e,lang:t,escaped:n}){let r=(t||"").match(Ee.notSpaceStart)?.[0],o=e.replace(Ee.endingNewline,"")+`
47
+ `+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(s);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,n}inline(e,n=[]){return this.inlineQueue.push({src:e,tokens:n}),n}inlineTokens(e,n=[]){this.tokenizer.lexer=this;let r=e,o=null;if(this.tokens.links){let l=Object.keys(this.tokens.links);if(l.length>0)for(;(o=this.tokenizer.rules.inline.reflinkSearch.exec(r))!==null;)l.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(o=this.tokenizer.rules.inline.anyPunctuation.exec(r))!==null;)r=r.slice(0,o.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let s;for(;(o=this.tokenizer.rules.inline.blockSkip.exec(r))!==null;)s=o[2]?o[2].length:0,r=r.slice(0,o.index+s)+"["+"a".repeat(o[0].length-s-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let i=!1,a="",u=1/0;for(;e;){if(e.length<u)u=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}i||(a=""),i=!1;let l;if(this.options.extensions?.inline?.some(m=>(l=m.call({lexer:this},e,n))?(e=e.substring(l.raw.length),n.push(l),!0):!1))continue;if(l=this.tokenizer.escape(e)){e=e.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.tag(e)){e=e.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.link(e)){e=e.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(l.raw.length);let m=n.at(-1);l.type==="text"&&m?.type==="text"?(m.raw+=l.raw,m.text+=l.text):n.push(l);continue}if(l=this.tokenizer.emStrong(e,r,a)){e=e.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.codespan(e)){e=e.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.br(e)){e=e.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.del(e,r,a)){e=e.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.autolink(e)){e=e.substring(l.raw.length),n.push(l);continue}if(!this.state.inLink&&(l=this.tokenizer.url(e))){e=e.substring(l.raw.length),n.push(l);continue}let p=e;if(this.options.extensions?.startInline){let m=1/0,x=e.slice(1),f;this.options.extensions.startInline.forEach(h=>{f=h.call({lexer:this},x),typeof f=="number"&&f>=0&&(m=Math.min(m,f))}),m<1/0&&m>=0&&(p=e.substring(0,m+1))}if(l=this.tokenizer.inlineText(p)){e=e.substring(l.raw.length),l.raw.slice(-1)!=="_"&&(a=l.raw.slice(-1)),i=!0;let m=n.at(-1);m?.type==="text"?(m.raw+=l.raw,m.text+=l.text):n.push(l);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return n}infiniteLoopError(e){let n="Infinite loop on byte: "+e;if(this.options.silent)console.error(n);else throw new Error(n)}},_r=class{options;parser;constructor(t){this.options=t||St}space(t){return""}code({text:t,lang:e,escaped:n}){let r=(e||"").match(Ee.notSpaceStart)?.[0],o=t.replace(Ee.endingNewline,"")+`
48
48
  `;return r?'<pre><code class="language-'+qe(r)+'">'+(n?o:qe(o,!0))+`</code></pre>
49
49
  `:"<pre><code>"+(n?o:qe(o,!0))+`</code></pre>
50
- `}blockquote({tokens:e}){return`<blockquote>
51
- ${this.parser.parse(e)}</blockquote>
52
- `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
53
- `}hr(e){return`<hr>
54
- `}list(e){let t=e.ordered,n=e.start,r="";for(let i=0;i<e.items.length;i++){let a=e.items[i];r+=this.listitem(a)}let o=t?"ol":"ul",s=t&&n!==1?' start="'+n+'"':"";return"<"+o+s+`>
50
+ `}blockquote({tokens:t}){return`<blockquote>
51
+ ${this.parser.parse(t)}</blockquote>
52
+ `}html({text:t}){return t}def(t){return""}heading({tokens:t,depth:e}){return`<h${e}>${this.parser.parseInline(t)}</h${e}>
53
+ `}hr(t){return`<hr>
54
+ `}list(t){let e=t.ordered,n=t.start,r="";for(let i=0;i<t.items.length;i++){let a=t.items[i];r+=this.listitem(a)}let o=e?"ol":"ul",s=e&&n!==1?' start="'+n+'"':"";return"<"+o+s+`>
55
55
  `+r+"</"+o+`>
56
- `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
57
- `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
58
- `}table(e){let t="",n="";for(let o=0;o<e.header.length;o++)n+=this.tablecell(e.header[o]);t+=this.tablerow({text:n});let r="";for(let o=0;o<e.rows.length;o++){let s=e.rows[o];n="";for(let i=0;i<s.length;i++)n+=this.tablecell(s[i]);r+=this.tablerow({text:n})}return r&&(r=`<tbody>${r}</tbody>`),`<table>
56
+ `}listitem(t){return`<li>${this.parser.parse(t.tokens)}</li>
57
+ `}checkbox({checked:t}){return"<input "+(t?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:t}){return`<p>${this.parser.parseInline(t)}</p>
58
+ `}table(t){let e="",n="";for(let o=0;o<t.header.length;o++)n+=this.tablecell(t.header[o]);e+=this.tablerow({text:n});let r="";for(let o=0;o<t.rows.length;o++){let s=t.rows[o];n="";for(let i=0;i<s.length;i++)n+=this.tablecell(s[i]);r+=this.tablerow({text:n})}return r&&(r=`<tbody>${r}</tbody>`),`<table>
59
59
  <thead>
60
- `+t+`</thead>
60
+ `+e+`</thead>
61
61
  `+r+`</table>
62
- `}tablerow({text:e}){return`<tr>
63
- ${e}</tr>
64
- `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
65
- `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${qe(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),o=Ha(e);if(o===null)return r;e=o;let s='<a href="'+e+'"';return t&&(s+=' title="'+qe(t)+'"'),s+=">"+r+"</a>",s}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let o=Ha(e);if(o===null)return qe(n);e=o;let s=`<img src="${e}" alt="${qe(n)}"`;return t&&(s+=` title="${qe(t)}"`),s+=">",s}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:qe(e.text)}},Xs=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Ge=class Gs{options;renderer;textRenderer;constructor(t){this.options=t||St,this.options.renderer=this.options.renderer||new Er,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Xs}static parse(t,n){return new Gs(n).parse(t)}static parseInline(t,n){return new Gs(n).parseInline(t)}parse(t){this.renderer.parser=this;let n="";for(let r=0;r<t.length;r++){let o=t[r];if(this.options.extensions?.renderers?.[o.type]){let i=o,a=this.options.extensions.renderers[i.type].call({parser:this},i);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(i.type)){n+=a||"";continue}}let s=o;switch(s.type){case"space":{n+=this.renderer.space(s);break}case"hr":{n+=this.renderer.hr(s);break}case"heading":{n+=this.renderer.heading(s);break}case"code":{n+=this.renderer.code(s);break}case"table":{n+=this.renderer.table(s);break}case"blockquote":{n+=this.renderer.blockquote(s);break}case"list":{n+=this.renderer.list(s);break}case"checkbox":{n+=this.renderer.checkbox(s);break}case"html":{n+=this.renderer.html(s);break}case"def":{n+=this.renderer.def(s);break}case"paragraph":{n+=this.renderer.paragraph(s);break}case"text":{n+=this.renderer.text(s);break}default:{let i='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(i),"";throw new Error(i)}}}return n}parseInline(t,n=this.renderer){this.renderer.parser=this;let r="";for(let o=0;o<t.length;o++){let s=t[o];if(this.options.extensions?.renderers?.[s.type]){let a=this.options.extensions.renderers[s.type].call({parser:this},s);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)){r+=a||"";continue}}let i=s;switch(i.type){case"escape":{r+=n.text(i);break}case"html":{r+=n.html(i);break}case"link":{r+=n.link(i);break}case"image":{r+=n.image(i);break}case"checkbox":{r+=n.checkbox(i);break}case"strong":{r+=n.strong(i);break}case"em":{r+=n.em(i);break}case"codespan":{r+=n.codespan(i);break}case"br":{r+=n.br(i);break}case"del":{r+=n.del(i);break}case"text":{r+=n.text(i);break}default:{let a='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return r}},Un=class{options;block;constructor(e){this.options=e||St}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Ue.lex:Ue.lexInline}provideParser(e=this.block){return e?Ge.parse:Ge.parseInline}},Zs=class{defaults=Fs();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Ge;Renderer=Er;TextRenderer=Xs;Lexer=Ue;Tokenizer=xr;Hooks=Un;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case"table":{let o=r;for(let s of o.header)n=n.concat(this.walkTokens(s.tokens,t));for(let s of o.rows)for(let i of s)n=n.concat(this.walkTokens(i.tokens,t));break}case"list":{let o=r;n=n.concat(this.walkTokens(o.items,t));break}default:{let o=r;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(s=>{let i=o[s].flat(1/0);n=n.concat(this.walkTokens(i,t))}):o.tokens&&(n=n.concat(this.walkTokens(o.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let s=t.renderers[o.name];s?t.renderers[o.name]=function(...i){let a=o.renderer.apply(this,i);return a===!1&&(a=s.apply(this,i)),a}:t.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let s=t[o.level];s?s.unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),r.extensions=t),n.renderer){let o=this.defaults.renderer||new Er(this.defaults);for(let s in n.renderer){if(!(s in o))throw new Error(`renderer '${s}' does not exist`);if(["options","parser"].includes(s))continue;let i=s,a=n.renderer[i],u=o[i];o[i]=(...c)=>{let p=a.apply(o,c);return p===!1&&(p=u.apply(o,c)),p||""}}r.renderer=o}if(n.tokenizer){let o=this.defaults.tokenizer||new xr(this.defaults);for(let s in n.tokenizer){if(!(s in o))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let i=s,a=n.tokenizer[i],u=o[i];o[i]=(...c)=>{let p=a.apply(o,c);return p===!1&&(p=u.apply(o,c)),p}}r.tokenizer=o}if(n.hooks){let o=this.defaults.hooks||new Un;for(let s in n.hooks){if(!(s in o))throw new Error(`hook '${s}' does not exist`);if(["options","block"].includes(s))continue;let i=s,a=n.hooks[i],u=o[i];Un.passThroughHooks.has(s)?o[i]=c=>{if(this.defaults.async&&Un.passThroughHooksRespectAsync.has(s))return(async()=>{let m=await a.call(o,c);return u.call(o,m)})();let p=a.call(o,c);return u.call(o,p)}:o[i]=(...c)=>{if(this.defaults.async)return(async()=>{let m=await a.apply(o,c);return m===!1&&(m=await u.apply(o,c)),m})();let p=a.apply(o,c);return p===!1&&(p=u.apply(o,c)),p}}r.hooks=o}if(n.walkTokens){let o=this.defaults.walkTokens,s=n.walkTokens;r.walkTokens=function(i){let a=[];return a.push(s.call(this,i)),o&&(a=a.concat(o.call(this,i))),a}}this.defaults={...this.defaults,...r}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Ue.lex(e,t??this.defaults)}parser(e,t){return Ge.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},o={...this.defaults,...r},s=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&r.async===!1)return s(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return s(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return s(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=e),o.async)return(async()=>{let i=o.hooks?await o.hooks.preprocess(t):t,a=await(o.hooks?await o.hooks.provideLexer(e):e?Ue.lex:Ue.lexInline)(i,o),u=o.hooks?await o.hooks.processAllTokens(a):a;o.walkTokens&&await Promise.all(this.walkTokens(u,o.walkTokens));let c=await(o.hooks?await o.hooks.provideParser(e):e?Ge.parse:Ge.parseInline)(u,o);return o.hooks?await o.hooks.postprocess(c):c})().catch(s);try{o.hooks&&(t=o.hooks.preprocess(t));let i=(o.hooks?o.hooks.provideLexer(e):e?Ue.lex:Ue.lexInline)(t,o);o.hooks&&(i=o.hooks.processAllTokens(i)),o.walkTokens&&this.walkTokens(i,o.walkTokens);let a=(o.hooks?o.hooks.provideParser(e):e?Ge.parse:Ge.parseInline)(i,o);return o.hooks&&(a=o.hooks.postprocess(a)),a}catch(i){return s(i)}}}onError(e,t){return n=>{if(n.message+=`
66
- Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error occurred:</p><pre>"+qe(n.message+"",!0)+"</pre>";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}},Tt=new Zs;function Z(e,t){return Tt.parse(e,t)}Z.options=Z.setOptions=function(e){return Tt.setOptions(e),Z.defaults=Tt.defaults,Va(Z.defaults),Z};Z.getDefaults=Fs;Z.defaults=St;Z.use=function(...e){return Tt.use(...e),Z.defaults=Tt.defaults,Va(Z.defaults),Z};Z.walkTokens=function(e,t){return Tt.walkTokens(e,t)};Z.parseInline=Tt.parseInline;Z.Parser=Ge;Z.parser=Ge.parse;Z.Renderer=Er;Z.TextRenderer=Xs;Z.Lexer=Ue;Z.lexer=Ue.lex;Z.Tokenizer=xr;Z.Hooks=Un;Z.parse=Z;var vg=Z.options,yg=Z.setOptions,bg=Z.use,xg=Z.walkTokens,Eg=Z.parseInline;var _g=Ge.parse,Tg=Ue.lex;var Pd=new Zs({gfm:!0,breaks:!0}),el=["a","p","br","strong","em","b","i","u","s","del","code","pre","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","hr","span","table","thead","tbody","tr","th","td"],tl=["href","title","class"],Dd=[...el,"img"],Ud=[...tl,"src","alt","width","height"];function Sr(e,t){let n=t?.allowImages===!0,r=Pd.parse(e,{async:!1}),o=Da.sanitize(r,{ALLOWED_TAGS:n?Dd:el,ALLOWED_ATTR:n?Ud:tl}),s=document.createElement("template");s.innerHTML=o;for(let i of s.content.querySelectorAll("a[href]"))i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer");return s.innerHTML.trim()}function nl(e,t){for(let n of Array.from(e.childNodes))n.nodeType===Node.TEXT_NODE?t.push({node:n,parent:e}):nl(n,t)}function rl(e){let t=[];nl(e,t);let n=0;for(let{node:r,parent:o}of t){let s=document.createDocumentFragment();for(let i of r.data.split(/(\s+)/)){if(i==="")continue;if(/\s/.test(i)){s.appendChild(document.createTextNode(i));continue}let a=document.createElement("span");a.className="word",a.style.setProperty("--ag-ui-word-index",String(n)),a.textContent=i,s.appendChild(a),n+=1}o.replaceChild(s,r)}}var wr=class{chips;palette;#e;#n=[];#i=!1;#u=!1;#a=[];#o=0;constructor(t){this.#e=t,this.chips=document.createElement("div"),this.chips.className="skill-chips",this.chips.hidden=!0,this.palette=document.createElement("div"),this.palette.className="skill-palette",this.palette.setAttribute("role","listbox"),this.palette.hidden=!0}setSkills(t){this.#n=t,this.#f()}enableChips(t){this.#i=t,this.#f()}enableSlash(t){this.#u=t}isOpen(){return!this.palette.hidden}onInput(t){this.#u&&t.startsWith("/")?this.#t(t.slice(1)):this.close()}onKeydown(t){return this.isOpen()?t.key==="ArrowDown"?(this.#r(1),!0):t.key==="ArrowUp"?(this.#r(-1),!0):t.key==="Escape"?(this.close(),!0):t.key==="Enter"?(this.#a.slice(this.#o,this.#o+1).forEach(n=>{this.#s(n)}),!0):!1:!1}close(){this.palette.hidden=!0,this.palette.replaceChildren()}#t(t){let n=t.trim().toLowerCase(),r=this.#n.filter(o=>o.name.toLowerCase().includes(n)||o.title.toLowerCase().includes(n));if(r.length===0){this.close();return}this.#a=r,this.#o=0,this.#l(),this.palette.hidden=!1}#r(t){let n=this.#a.length;this.#o=(this.#o+t+n)%n,this.#l()}#s(t){this.close(),this.#e(t)}#f(){this.chips.replaceChildren();let t=this.#i?this.#n.filter(n=>n.chip===!0):[];this.chips.hidden=t.length===0;for(let n of t){let r=document.createElement("button");r.type="button",r.className="skill-chip",r.textContent=n.title,r.addEventListener("click",()=>this.#s(n)),this.chips.appendChild(r)}}#l(){this.palette.replaceChildren(),this.#a.forEach((t,n)=>{let r=document.createElement("button");r.type="button",r.className="skill-item",r.setAttribute("role","option"),r.setAttribute("aria-selected",n===this.#o?"true":"false");let o=document.createElement("span");if(o.className="skill-item-title",o.textContent=t.title,r.appendChild(o),t.description!==void 0){let s=document.createElement("span");s.className="skill-item-desc",s.textContent=t.description,r.appendChild(s)}r.addEventListener("click",()=>this.#s(t)),this.palette.appendChild(r)})}};var ol=`
62
+ `}tablerow({text:t}){return`<tr>
63
+ ${t}</tr>
64
+ `}tablecell(t){let e=this.parser.parseInline(t.tokens),n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>
65
+ `}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${qe(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:n}){let r=this.parser.parseInline(n),o=Ba(t);if(o===null)return r;t=o;let s='<a href="'+t+'"';return e&&(s+=' title="'+qe(e)+'"'),s+=">"+r+"</a>",s}image({href:t,title:e,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let o=Ba(t);if(o===null)return qe(n);t=o;let s=`<img src="${t}" alt="${qe(n)}"`;return e&&(s+=` title="${qe(e)}"`),s+=">",s}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:qe(t.text)}},Ys=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},Ge=class $s{options;renderer;textRenderer;constructor(e){this.options=e||St,this.options.renderer=this.options.renderer||new _r,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ys}static parse(e,n){return new $s(n).parse(e)}static parseInline(e,n){return new $s(n).parseInline(e)}parse(e){this.renderer.parser=this;let n="";for(let r=0;r<e.length;r++){let o=e[r];if(this.options.extensions?.renderers?.[o.type]){let i=o,a=this.options.extensions.renderers[i.type].call({parser:this},i);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(i.type)){n+=a||"";continue}}let s=o;switch(s.type){case"space":{n+=this.renderer.space(s);break}case"hr":{n+=this.renderer.hr(s);break}case"heading":{n+=this.renderer.heading(s);break}case"code":{n+=this.renderer.code(s);break}case"table":{n+=this.renderer.table(s);break}case"blockquote":{n+=this.renderer.blockquote(s);break}case"list":{n+=this.renderer.list(s);break}case"checkbox":{n+=this.renderer.checkbox(s);break}case"html":{n+=this.renderer.html(s);break}case"def":{n+=this.renderer.def(s);break}case"paragraph":{n+=this.renderer.paragraph(s);break}case"text":{n+=this.renderer.text(s);break}default:{let i='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(i),"";throw new Error(i)}}}return n}parseInline(e,n=this.renderer){this.renderer.parser=this;let r="";for(let o=0;o<e.length;o++){let s=e[o];if(this.options.extensions?.renderers?.[s.type]){let a=this.options.extensions.renderers[s.type].call({parser:this},s);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)){r+=a||"";continue}}let i=s;switch(i.type){case"escape":{r+=n.text(i);break}case"html":{r+=n.html(i);break}case"link":{r+=n.link(i);break}case"image":{r+=n.image(i);break}case"checkbox":{r+=n.checkbox(i);break}case"strong":{r+=n.strong(i);break}case"em":{r+=n.em(i);break}case"codespan":{r+=n.codespan(i);break}case"br":{r+=n.br(i);break}case"del":{r+=n.del(i);break}case"text":{r+=n.text(i);break}default:{let a='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return r}},Gn=class{options;block;constructor(t){this.options=t||St}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(t=this.block){return t?Ue.lex:Ue.lexInline}provideParser(t=this.block){return t?Ge.parse:Ge.parseInline}},qs=class{defaults=zs();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Ge;Renderer=_r;TextRenderer=Ys;Lexer=Ue;Tokenizer=Tr;Hooks=Gn;constructor(...t){this.use(...t)}walkTokens(t,e){let n=[];for(let r of t)switch(n=n.concat(e.call(this,r)),r.type){case"table":{let o=r;for(let s of o.header)n=n.concat(this.walkTokens(s.tokens,e));for(let s of o.rows)for(let i of s)n=n.concat(this.walkTokens(i.tokens,e));break}case"list":{let o=r;n=n.concat(this.walkTokens(o.items,e));break}default:{let o=r;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(s=>{let i=o[s].flat(1/0);n=n.concat(this.walkTokens(i,e))}):o.tokens&&(n=n.concat(this.walkTokens(o.tokens,e)))}}return n}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let s=e.renderers[o.name];s?e.renderers[o.name]=function(...i){let a=o.renderer.apply(this,i);return a===!1&&(a=s.apply(this,i)),a}:e.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let s=e[o.level];s?s.unshift(o.tokenizer):e[o.level]=[o.tokenizer],o.start&&(o.level==="block"?e.startBlock?e.startBlock.push(o.start):e.startBlock=[o.start]:o.level==="inline"&&(e.startInline?e.startInline.push(o.start):e.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(e.childTokens[o.name]=o.childTokens)}),r.extensions=e),n.renderer){let o=this.defaults.renderer||new _r(this.defaults);for(let s in n.renderer){if(!(s in o))throw new Error(`renderer '${s}' does not exist`);if(["options","parser"].includes(s))continue;let i=s,a=n.renderer[i],u=o[i];o[i]=(...l)=>{let p=a.apply(o,l);return p===!1&&(p=u.apply(o,l)),p||""}}r.renderer=o}if(n.tokenizer){let o=this.defaults.tokenizer||new Tr(this.defaults);for(let s in n.tokenizer){if(!(s in o))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let i=s,a=n.tokenizer[i],u=o[i];o[i]=(...l)=>{let p=a.apply(o,l);return p===!1&&(p=u.apply(o,l)),p}}r.tokenizer=o}if(n.hooks){let o=this.defaults.hooks||new Gn;for(let s in n.hooks){if(!(s in o))throw new Error(`hook '${s}' does not exist`);if(["options","block"].includes(s))continue;let i=s,a=n.hooks[i],u=o[i];Gn.passThroughHooks.has(s)?o[i]=l=>{if(this.defaults.async&&Gn.passThroughHooksRespectAsync.has(s))return(async()=>{let m=await a.call(o,l);return u.call(o,m)})();let p=a.call(o,l);return u.call(o,p)}:o[i]=(...l)=>{if(this.defaults.async)return(async()=>{let m=await a.apply(o,l);return m===!1&&(m=await u.apply(o,l)),m})();let p=a.apply(o,l);return p===!1&&(p=u.apply(o,l)),p}}r.hooks=o}if(n.walkTokens){let o=this.defaults.walkTokens,s=n.walkTokens;r.walkTokens=function(i){let a=[];return a.push(s.call(this,i)),o&&(a=a.concat(o.call(this,i))),a}}this.defaults={...this.defaults,...r}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return Ue.lex(t,e??this.defaults)}parser(t,e){return Ge.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let r={...n},o={...this.defaults,...r},s=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&r.async===!1)return s(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return s(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return s(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=t),o.async)return(async()=>{let i=o.hooks?await o.hooks.preprocess(e):e,a=await(o.hooks?await o.hooks.provideLexer(t):t?Ue.lex:Ue.lexInline)(i,o),u=o.hooks?await o.hooks.processAllTokens(a):a;o.walkTokens&&await Promise.all(this.walkTokens(u,o.walkTokens));let l=await(o.hooks?await o.hooks.provideParser(t):t?Ge.parse:Ge.parseInline)(u,o);return o.hooks?await o.hooks.postprocess(l):l})().catch(s);try{o.hooks&&(e=o.hooks.preprocess(e));let i=(o.hooks?o.hooks.provideLexer(t):t?Ue.lex:Ue.lexInline)(e,o);o.hooks&&(i=o.hooks.processAllTokens(i)),o.walkTokens&&this.walkTokens(i,o.walkTokens);let a=(o.hooks?o.hooks.provideParser(t):t?Ge.parse:Ge.parseInline)(i,o);return o.hooks&&(a=o.hooks.postprocess(a)),a}catch(i){return s(i)}}}onError(t,e){return n=>{if(n.message+=`
66
+ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+qe(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},_t=new qs;function Z(t,e){return _t.parse(t,e)}Z.options=Z.setOptions=function(t){return _t.setOptions(t),Z.defaults=_t.defaults,Xa(Z.defaults),Z};Z.getDefaults=zs;Z.defaults=St;Z.use=function(...t){return _t.use(...t),Z.defaults=_t.defaults,Xa(Z.defaults),Z};Z.walkTokens=function(t,e){return _t.walkTokens(t,e)};Z.parseInline=_t.parseInline;Z.Parser=Ge;Z.parser=Ge.parse;Z.Renderer=_r;Z.TextRenderer=Ys;Z.Lexer=Ue;Z.lexer=Ue.lex;Z.Tokenizer=Tr;Z.Hooks=Gn;Z.parse=Z;var Cg=Z.options,Ng=Z.setOptions,Rg=Z.use,Og=Z.walkTokens,Mg=Z.parseInline;var Lg=Ge.parse,Pg=Ue.lex;var zd=new qs({gfm:!0,breaks:!0}),rl=["a","p","br","strong","em","b","i","u","s","del","code","pre","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","hr","span","table","thead","tbody","tr","th","td"],ol=["href","title","class"],Bd=[...rl,"img"],Vd=[...ol,"src","alt","width","height"];function kr(t,e){let n=e?.allowImages===!0,r=zd.parse(t,{async:!1}),o=Ha.sanitize(r,{ALLOWED_TAGS:n?Bd:rl,ALLOWED_ATTR:n?Vd:ol}),s=document.createElement("template");s.innerHTML=o;for(let i of s.content.querySelectorAll("a[href]"))i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer");return s.innerHTML.trim()}function sl(t,e){for(let n of Array.from(t.childNodes))n.nodeType===Node.TEXT_NODE?e.push({node:n,parent:t}):sl(n,e)}function il(t){let e=[];sl(t,e);let n=0;for(let{node:r,parent:o}of e){let s=document.createDocumentFragment();for(let i of r.data.split(/(\s+)/)){if(i==="")continue;if(/\s/.test(i)){s.appendChild(document.createTextNode(i));continue}let a=document.createElement("span");a.className="word",a.style.setProperty("--ag-ui-word-index",String(n)),a.textContent=i,s.appendChild(a),n+=1}o.replaceChild(s,r)}}var Ar=class{chips;palette;#e;#n=[];#r=!1;#a=!1;#l=[];#s=0;constructor(e){this.#e=e,this.chips=document.createElement("div"),this.chips.className="skill-chips",this.chips.hidden=!0,this.palette=document.createElement("div"),this.palette.className="skill-palette",this.palette.setAttribute("role","listbox"),this.palette.hidden=!0}setSkills(e){this.#n=e,this.#p()}enableChips(e){this.#r=e,this.#p()}enableSlash(e){this.#a=e}isOpen(){return!this.palette.hidden}onInput(e){this.#a&&e.startsWith("/")?this.#t(e.slice(1)):this.close()}onKeydown(e){return this.isOpen()?e.key==="ArrowDown"?(this.#o(1),!0):e.key==="ArrowUp"?(this.#o(-1),!0):e.key==="Escape"?(this.close(),!0):e.key==="Enter"?(this.#l.slice(this.#s,this.#s+1).forEach(n=>{this.#i(n)}),!0):!1:!1}close(){this.palette.hidden=!0,this.palette.replaceChildren()}#t(e){let n=e.trim().toLowerCase(),r=this.#n.filter(o=>o.name.toLowerCase().includes(n)||o.title.toLowerCase().includes(n));if(r.length===0){this.close();return}this.#l=r,this.#s=0,this.#u(),this.palette.hidden=!1}#o(e){let n=this.#l.length;this.#s=(this.#s+e+n)%n,this.#u()}#i(e){this.close(),this.#e(e)}#p(){this.chips.replaceChildren();let e=this.#r?this.#n.filter(n=>n.chip===!0):[];this.chips.hidden=e.length===0;for(let n of e){let r=document.createElement("button");r.type="button",r.className="skill-chip",r.textContent=n.title,r.addEventListener("click",()=>this.#i(n)),this.chips.appendChild(r)}}#u(){this.palette.replaceChildren(),this.#l.forEach((e,n)=>{let r=document.createElement("button");r.type="button",r.className="skill-item",r.setAttribute("role","option"),r.setAttribute("aria-selected",n===this.#s?"true":"false");let o=document.createElement("span");if(o.className="skill-item-title",o.textContent=e.title,r.appendChild(o),e.description!==void 0){let s=document.createElement("span");s.className="skill-item-desc",s.textContent=e.description,r.appendChild(s)}r.addEventListener("click",()=>this.#i(e)),this.palette.appendChild(r)})}};var al=`
67
67
  :host {
68
68
  /* Colors */
69
69
  --ag-ui-bg: #ffffff;
@@ -562,6 +562,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
562
562
  cursor: default;
563
563
  }
564
564
 
565
+ /* The composer button doubles as the Stop control while a run is in flight. */
566
+ .send[data-state="running"] {
567
+ background: var(--ag-ui-muted);
568
+ }
569
+
570
+ /* Muted "\u23F9 Stopped" line after a cancelled run \u2014 a note, not an error bubble. */
571
+ .stopped-note {
572
+ align-self: flex-start;
573
+ color: var(--ag-ui-muted);
574
+ font-size: 12px;
575
+ padding: 2px 4px;
576
+ }
577
+
565
578
  /* Inline confirmation card \u2014 lives in the transcript, no focus-stealing overlay. */
566
579
  .confirm {
567
580
  align-self: stretch;
@@ -692,19 +705,203 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
692
705
  font-size: 0.85em;
693
706
  color: var(--ag-ui-danger);
694
707
  }
695
- `;var sl={[de.PENDING]:"running\u2026",[de.DONE]:"\u2713 done",[de.ERROR]:"\u26A0 error",[de.DECLINED]:"\u2298 declined"},Gd={[de.DONE]:"Result",[de.ERROR]:"Error",[de.DECLINED]:"Declined"},Fn=class{element;#e;#n;#i;constructor(t,n,r=Ze.FULL,o){this.#n=r,this.#i=n,this.element=document.createElement("div"),this.element.className="tool-call",this.element.setAttribute("data-tool-name",t),this.element.setAttribute("data-status",de.PENDING),this.element.setAttribute("data-display",r);let s=document.createElement("div");s.className="tool-call-head";let i=document.createElement("span");if(i.className="tool-call-name",i.textContent=`\u{1F527} ${o??t}`,this.#e=document.createElement("span"),this.#e.className="tool-call-status",this.#e.textContent=sl[de.PENDING],s.append(i,this.#e),this.element.append(s),r===Ze.FULL){let a=document.createElement("pre");a.className="tool-call-args",a.textContent=JSON.stringify(n,null,2),this.element.append(a)}}settle(t,n){if(this.element.setAttribute("data-status",t),this.#e.textContent=sl[t],this.#n===Ze.MINIMAL)return;let r=document.createElement("button");r.type="button",r.className="tool-call-toggle",r.setAttribute("aria-expanded","false");let o=document.createElement("pre");o.className="tool-call-result",o.hidden=!0,this.#n===Ze.COMPACT?(r.textContent="Details",o.textContent=`args: ${JSON.stringify(this.#i)}
696
708
 
697
- ${n}`):(r.textContent=Gd[t],o.textContent=n),r.addEventListener("click",()=>{let s=o.hidden;o.hidden=!s,r.setAttribute("aria-expanded",String(s))}),this.element.append(r,o)}};var ve=[];for(let e=0;e<256;++e)ve.push((e+256).toString(16).slice(1));function il(e,t=0){return(ve[e[t+0]]+ve[e[t+1]]+ve[e[t+2]]+ve[e[t+3]]+"-"+ve[e[t+4]]+ve[e[t+5]]+"-"+ve[e[t+6]]+ve[e[t+7]]+"-"+ve[e[t+8]]+ve[e[t+9]]+"-"+ve[e[t+10]]+ve[e[t+11]]+ve[e[t+12]]+ve[e[t+13]]+ve[e[t+14]]+ve[e[t+15]]).toLowerCase()}var Ks,Fd=new Uint8Array(16);function Ys(){if(!Ks){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Ks=crypto.getRandomValues.bind(crypto)}return Ks(Fd)}var Hd=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),qs={randomUUID:Hd};function $d(e,t,n){if(qs.randomUUID&&!t&&!e)return qs.randomUUID();e=e||{};let r=e.random??e.rng?.()??Ys();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n=n||0,n<0||n+16>t.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)t[n+o]=r[o];return t}return il(r)}var ht=$d;var l={};ms(l,{BRAND:()=>fp,DIRTY:()=>wt,EMPTY_PATH:()=>jd,INVALID:()=>O,NEVER:()=>qp,OK:()=>_e,ParseStatus:()=>ye,Schema:()=>U,ZodAny:()=>vt,ZodArray:()=>lt,ZodBigInt:()=>At,ZodBoolean:()=>It,ZodBranded:()=>$n,ZodCatch:()=>Ft,ZodDate:()=>Ct,ZodDefault:()=>Gt,ZodDiscriminatedUnion:()=>Ir,ZodEffects:()=>Me,ZodEnum:()=>Dt,ZodError:()=>we,ZodFirstPartyTypeKind:()=>M,ZodFunction:()=>Nr,ZodIntersection:()=>Mt,ZodIssueCode:()=>E,ZodLazy:()=>Lt,ZodLiteral:()=>Pt,ZodMap:()=>fn,ZodNaN:()=>mn,ZodNativeEnum:()=>Ut,ZodNever:()=>Fe,ZodNull:()=>Rt,ZodNullable:()=>et,ZodNumber:()=>kt,ZodObject:()=>ke,ZodOptional:()=>Re,ZodParsedType:()=>A,ZodPipeline:()=>zn,ZodPromise:()=>yt,ZodReadonly:()=>Ht,ZodRecord:()=>Cr,ZodSchema:()=>U,ZodSet:()=>hn,ZodString:()=>gt,ZodSymbol:()=>dn,ZodTransformer:()=>Me,ZodTuple:()=>Qe,ZodType:()=>U,ZodUndefined:()=>Nt,ZodUnion:()=>Ot,ZodUnknown:()=>at,ZodVoid:()=>pn,addIssueToContext:()=>w,any:()=>_p,array:()=>kp,bigint:()=>vp,boolean:()=>vl,coerce:()=>Yp,custom:()=>hl,date:()=>yp,datetimeRegex:()=>pl,defaultErrorMap:()=>st,discriminatedUnion:()=>Np,effect:()=>zp,enum:()=>Fp,function:()=>Dp,getErrorMap:()=>ln,getParsedType:()=>Je,instanceof:()=>mp,intersection:()=>Rp,isAborted:()=>kr,isAsync:()=>cn,isDirty:()=>Ar,isValid:()=>mt,late:()=>hp,lazy:()=>Up,literal:()=>Gp,makeIssue:()=>Hn,map:()=>Lp,nan:()=>gp,nativeEnum:()=>Hp,never:()=>Sp,null:()=>Ep,nullable:()=>Vp,number:()=>gl,object:()=>Ap,objectUtil:()=>Js,oboolean:()=>Kp,onumber:()=>Zp,optional:()=>Bp,ostring:()=>Xp,pipeline:()=>Wp,preprocess:()=>jp,promise:()=>$p,quotelessJson:()=>zd,record:()=>Mp,set:()=>Pp,setErrorMap:()=>Vd,strictObject:()=>Ip,string:()=>ml,symbol:()=>bp,transformer:()=>zp,tuple:()=>Op,undefined:()=>xp,union:()=>Cp,unknown:()=>Tp,util:()=>H,void:()=>wp});var H;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},e.getValidEnumValues=o=>{let s=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return e.objectValues(i)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},e.find=(o,s)=>{for(let i of o)if(s(i))return i},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(H||(H={}));var Js;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Js||(Js={}));var A=H.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Je=e=>{switch(typeof e){case"undefined":return A.undefined;case"string":return A.string;case"number":return Number.isNaN(e)?A.nan:A.number;case"boolean":return A.boolean;case"function":return A.function;case"bigint":return A.bigint;case"symbol":return A.symbol;case"object":return Array.isArray(e)?A.array:e===null?A.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?A.promise:typeof Map<"u"&&e instanceof Map?A.map:typeof Set<"u"&&e instanceof Set?A.set:typeof Date<"u"&&e instanceof Date?A.date:A.object;default:return A.unknown}};var E=H.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),zd=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),we=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,u=0;for(;u<i.path.length;){let c=i.path[u];u===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(i))):a[c]=a[c]||{_errors:[]},a=a[c],u++}}};return o(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,H.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};we.create=e=>new we(e);var Bd=(e,t)=>{let n;switch(e.code){case E.invalid_type:e.received===A.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case E.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,H.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:n=`Unrecognized key(s) in object: ${H.joinValues(e.keys,", ")}`;break;case E.invalid_union:n="Invalid input";break;case E.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${H.joinValues(e.options)}`;break;case E.invalid_enum_value:n=`Invalid enum value. Expected ${H.joinValues(e.options)}, received '${e.received}'`;break;case E.invalid_arguments:n="Invalid function arguments";break;case E.invalid_return_type:n="Invalid function return type";break;case E.invalid_date:n="Invalid date";break;case E.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:H.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case E.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case E.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case E.custom:n="Invalid input";break;case E.invalid_intersection_types:n="Intersection results could not be merged";break;case E.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case E.not_finite:n="Number must be finite";break;default:n=t.defaultError,H.assertNever(e)}return{message:n}},st=Bd;var al=st;function Vd(e){al=e}function ln(){return al}var Hn=e=>{let{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",u=r.filter(c=>!!c).slice().reverse();for(let c of u)a=c(i,{data:t,defaultError:a}).message;return{...o,path:s,message:a}},jd=[];function w(e,t){let n=ln(),r=Hn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===st?void 0:st].filter(o=>!!o)});e.common.issues.push(r)}var ye=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let o of n){if(o.status==="aborted")return O;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return O;s.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:t.value,value:r}}},O=Object.freeze({status:"aborted"}),wt=e=>({status:"dirty",value:e}),_e=e=>({status:"valid",value:e}),kr=e=>e.status==="aborted",Ar=e=>e.status==="dirty",mt=e=>e.status==="valid",cn=e=>typeof Promise<"u"&&e instanceof Promise;var I;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(I||(I={}));var Oe=class{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ll=(e,t)=>{if(mt(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new we(e.common.issues);return this._error=n,this._error}}};function L(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(i,a)=>{let{message:u}=e;return i.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:u??n??a.defaultError}},description:o}}var U=class{get description(){return this._def.description}_getType(t){return Je(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Je(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ye,ctx:{common:t.parent.common,data:t.data,parsedType:Je(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(cn(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Je(t)},o=this._parseSync({data:t,path:r.path,parent:r});return ll(r,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Je(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return mt(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>mt(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){let r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Je(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(cn(o)?o:Promise.resolve(o));return ll(r,s)}refine(t,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=t(o),a=()=>s.addIssue({code:E.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(u=>u?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Me({schema:this,typeName:M.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Re.create(this,this._def)}nullable(){return et.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return lt.create(this)}promise(){return yt.create(this,this._def)}or(t){return Ot.create([this,t],this._def)}and(t){return Mt.create(this,t,this._def)}transform(t){return new Me({...L(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new Gt({...L(this._def),innerType:this,defaultValue:n,typeName:M.ZodDefault})}brand(){return new $n({typeName:M.ZodBranded,type:this,...L(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new Ft({...L(this._def),innerType:this,catchValue:n,typeName:M.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return zn.create(this,t)}readonly(){return Ht.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Wd=/^c[^\s-]{8,}$/i,Xd=/^[0-9a-z]+$/,Zd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Kd=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Yd=/^[a-z0-9_-]{21}$/i,qd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Jd=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Qd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ep="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Qs,tp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,np=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,rp=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,op=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,sp=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ip=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ul="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",ap=new RegExp(`^${ul}$`);function dl(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function lp(e){return new RegExp(`^${dl(e)}$`)}function pl(e){let t=`${ul}T${dl(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function cp(e,t){return!!((t==="v4"||!t)&&tp.test(e)||(t==="v6"||!t)&&rp.test(e))}function up(e,t){if(!qd.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function dp(e,t){return!!((t==="v4"||!t)&&np.test(e)||(t==="v6"||!t)&&op.test(e))}var gt=class e extends U{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==A.string){let s=this._getOrReturnCtx(t);return w(s,{code:E.invalid_type,expected:A.string,received:s.parsedType}),O}let r=new ye,o;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),w(o,{code:E.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),w(o,{code:E.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let i=t.data.length>s.value,a=t.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(t,o),i?w(o,{code:E.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&w(o,{code:E.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Qd.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"email",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Qs||(Qs=new RegExp(ep,"u")),Qs.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"emoji",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")Kd.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"uuid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")Yd.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"nanoid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Wd.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"cuid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")Xd.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"cuid2",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Zd.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"ulid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),w(o,{validation:"url",code:E.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"regex",code:E.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),w(o,{code:E.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),w(o,{code:E.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),w(o,{code:E.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?pl(s).test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{code:E.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?ap.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{code:E.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?lp(s).test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{code:E.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?Jd.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"duration",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?cp(t.data,s.version)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"ip",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?up(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"jwt",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?dp(t.data,s.version)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"cidr",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?sp.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"base64",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?ip.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"base64url",code:E.invalid_string,message:s.message}),r.dirty()):H.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:E.invalid_string,...I.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...I.errToObj(t)})}url(t){return this._addCheck({kind:"url",...I.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...I.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...I.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...I.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...I.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...I.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...I.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...I.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...I.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...I.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...I.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...I.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...I.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...I.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...I.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...I.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...I.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...I.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...I.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...I.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...I.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...I.errToObj(n)})}nonempty(t){return this.min(1,I.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};gt.create=e=>new gt({checks:[],typeName:M.ZodString,coerce:e?.coerce??!1,...L(e)});function pp(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}var kt=class e extends U{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==A.number){let s=this._getOrReturnCtx(t);return w(s,{code:E.invalid_type,expected:A.number,received:s.parsedType}),O}let r,o=new ye;for(let s of this._def.checks)s.kind==="int"?H.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),w(r,{code:E.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),w(r,{code:E.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),w(r,{code:E.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?pp(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),w(r,{code:E.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),w(r,{code:E.not_finite,message:s.message}),o.dirty()):H.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,I.toString(n))}gt(t,n){return this.setLimit("min",t,!1,I.toString(n))}lte(t,n){return this.setLimit("max",t,!0,I.toString(n))}lt(t,n){return this.setLimit("max",t,!1,I.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:I.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:I.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:I.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:I.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:I.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:I.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:I.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:I.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:I.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&H.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};kt.create=e=>new kt({checks:[],typeName:M.ZodNumber,coerce:e?.coerce||!1,...L(e)});var At=class e extends U{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==A.bigint)return this._getInvalidInput(t);let r,o=new ye;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),w(r,{code:E.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),w(r,{code:E.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),w(r,{code:E.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):H.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return w(n,{code:E.invalid_type,expected:A.bigint,received:n.parsedType}),O}gte(t,n){return this.setLimit("min",t,!0,I.toString(n))}gt(t,n){return this.setLimit("min",t,!1,I.toString(n))}lte(t,n){return this.setLimit("max",t,!0,I.toString(n))}lt(t,n){return this.setLimit("max",t,!1,I.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:I.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:I.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:I.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:I.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:I.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};At.create=e=>new At({checks:[],typeName:M.ZodBigInt,coerce:e?.coerce??!1,...L(e)});var It=class extends U{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==A.boolean){let r=this._getOrReturnCtx(t);return w(r,{code:E.invalid_type,expected:A.boolean,received:r.parsedType}),O}return _e(t.data)}};It.create=e=>new It({typeName:M.ZodBoolean,coerce:e?.coerce||!1,...L(e)});var Ct=class e extends U{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==A.date){let s=this._getOrReturnCtx(t);return w(s,{code:E.invalid_type,expected:A.date,received:s.parsedType}),O}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return w(s,{code:E.invalid_date}),O}let r=new ye,o;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),w(o,{code:E.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),w(o,{code:E.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):H.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:I.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:I.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};Ct.create=e=>new Ct({checks:[],coerce:e?.coerce||!1,typeName:M.ZodDate,...L(e)});var dn=class extends U{_parse(t){if(this._getType(t)!==A.symbol){let r=this._getOrReturnCtx(t);return w(r,{code:E.invalid_type,expected:A.symbol,received:r.parsedType}),O}return _e(t.data)}};dn.create=e=>new dn({typeName:M.ZodSymbol,...L(e)});var Nt=class extends U{_parse(t){if(this._getType(t)!==A.undefined){let r=this._getOrReturnCtx(t);return w(r,{code:E.invalid_type,expected:A.undefined,received:r.parsedType}),O}return _e(t.data)}};Nt.create=e=>new Nt({typeName:M.ZodUndefined,...L(e)});var Rt=class extends U{_parse(t){if(this._getType(t)!==A.null){let r=this._getOrReturnCtx(t);return w(r,{code:E.invalid_type,expected:A.null,received:r.parsedType}),O}return _e(t.data)}};Rt.create=e=>new Rt({typeName:M.ZodNull,...L(e)});var vt=class extends U{constructor(){super(...arguments),this._any=!0}_parse(t){return _e(t.data)}};vt.create=e=>new vt({typeName:M.ZodAny,...L(e)});var at=class extends U{constructor(){super(...arguments),this._unknown=!0}_parse(t){return _e(t.data)}};at.create=e=>new at({typeName:M.ZodUnknown,...L(e)});var Fe=class extends U{_parse(t){let n=this._getOrReturnCtx(t);return w(n,{code:E.invalid_type,expected:A.never,received:n.parsedType}),O}};Fe.create=e=>new Fe({typeName:M.ZodNever,...L(e)});var pn=class extends U{_parse(t){if(this._getType(t)!==A.undefined){let r=this._getOrReturnCtx(t);return w(r,{code:E.invalid_type,expected:A.void,received:r.parsedType}),O}return _e(t.data)}};pn.create=e=>new pn({typeName:M.ZodVoid,...L(e)});var lt=class e extends U{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==A.array)return w(n,{code:E.invalid_type,expected:A.array,received:n.parsedType}),O;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(w(n,{code:i?E.too_big:E.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(w(n,{code:E.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(w(n,{code:E.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new Oe(n,i,n.path,a)))).then(i=>ye.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new Oe(n,i,n.path,a)));return ye.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:I.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:I.toString(n)}})}nonempty(t){return this.min(1,t)}};lt.create=(e,t)=>new lt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...L(t)});function un(e){if(e instanceof ke){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Re.create(un(r))}return new ke({...e._def,shape:()=>t})}else return e instanceof lt?new lt({...e._def,type:un(e.element)}):e instanceof Re?Re.create(un(e.unwrap())):e instanceof et?et.create(un(e.unwrap())):e instanceof Qe?Qe.create(e.items.map(t=>un(t))):e}var ke=class e extends U{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=H.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==A.object){let c=this._getOrReturnCtx(t);return w(c,{code:E.invalid_type,expected:A.object,received:c.parsedType}),O}let{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Fe&&this._def.unknownKeys==="strip"))for(let c in o.data)i.includes(c)||a.push(c);let u=[];for(let c of i){let p=s[c],m=o.data[c];u.push({key:{status:"valid",value:c},value:p._parse(new Oe(o,m,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Fe){let c=this._def.unknownKeys;if(c==="passthrough")for(let p of a)u.push({key:{status:"valid",value:p},value:{status:"valid",value:o.data[p]}});else if(c==="strict")a.length>0&&(w(o,{code:E.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let p of a){let m=o.data[p];u.push({key:{status:"valid",value:p},value:c._parse(new Oe(o,m,o.path,p)),alwaysSet:p in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let c=[];for(let p of u){let m=await p.key,x=await p.value;c.push({key:m,value:x,alwaysSet:p.alwaysSet})}return c}).then(c=>ye.mergeObjectSync(r,c)):ye.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return I.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:I.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:M.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of H.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let r of H.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return un(this)}partial(t){let n={};for(let r of H.objectKeys(this.shape)){let o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of H.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Re;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:()=>n})}keyof(){return fl(H.objectKeys(this.shape))}};ke.create=(e,t)=>new ke({shape:()=>e,unknownKeys:"strip",catchall:Fe.create(),typeName:M.ZodObject,...L(t)});ke.strictCreate=(e,t)=>new ke({shape:()=>e,unknownKeys:"strict",catchall:Fe.create(),typeName:M.ZodObject,...L(t)});ke.lazycreate=(e,t)=>new ke({shape:e,unknownKeys:"strip",catchall:Fe.create(),typeName:M.ZodObject,...L(t)});var Ot=class extends U{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new we(a.ctx.common.issues));return w(n,{code:E.invalid_union,unionErrors:i}),O}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let u of r){let c={...n,common:{...n.common,issues:[]},parent:null},p=u._parseSync({data:n.data,path:n.path,parent:c});if(p.status==="valid")return p;p.status==="dirty"&&!s&&(s={result:p,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(u=>new we(u));return w(n,{code:E.invalid_union,unionErrors:a}),O}}get options(){return this._def.options}};Ot.create=(e,t)=>new Ot({options:e,typeName:M.ZodUnion,...L(t)});var it=e=>e instanceof Lt?it(e.schema):e instanceof Me?it(e.innerType()):e instanceof Pt?[e.value]:e instanceof Dt?e.options:e instanceof Ut?H.objectValues(e.enum):e instanceof Gt?it(e._def.innerType):e instanceof Nt?[void 0]:e instanceof Rt?[null]:e instanceof Re?[void 0,...it(e.unwrap())]:e instanceof et?[null,...it(e.unwrap())]:e instanceof $n||e instanceof Ht?it(e.unwrap()):e instanceof Ft?it(e._def.innerType):[],Ir=class e extends U{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.object)return w(n,{code:E.invalid_type,expected:A.object,received:n.parsedType}),O;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(w(n,{code:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),O)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let o=new Map;for(let s of n){let i=it(s.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);o.set(a,s)}}return new e({typeName:M.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...L(r)})}};function ei(e,t){let n=Je(e),r=Je(t);if(e===t)return{valid:!0,data:e};if(n===A.object&&r===A.object){let o=H.objectKeys(t),s=H.objectKeys(e).filter(a=>o.indexOf(a)!==-1),i={...e,...t};for(let a of s){let u=ei(e[a],t[a]);if(!u.valid)return{valid:!1};i[a]=u.data}return{valid:!0,data:i}}else if(n===A.array&&r===A.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let s=0;s<e.length;s++){let i=e[s],a=t[s],u=ei(i,a);if(!u.valid)return{valid:!1};o.push(u.data)}return{valid:!0,data:o}}else return n===A.date&&r===A.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Mt=class extends U{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=(s,i)=>{if(kr(s)||kr(i))return O;let a=ei(s.value,i.value);return a.valid?((Ar(s)||Ar(i))&&n.dirty(),{status:n.value,value:a.data}):(w(r,{code:E.invalid_intersection_types}),O)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Mt.create=(e,t,n)=>new Mt({left:e,right:t,typeName:M.ZodIntersection,...L(n)});var Qe=class e extends U{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.array)return w(r,{code:E.invalid_type,expected:A.array,received:r.parsedType}),O;if(r.data.length<this._def.items.length)return w(r,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),O;!this._def.rest&&r.data.length>this._def.items.length&&(w(r,{code:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new Oe(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>ye.mergeArray(n,i)):ye.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Qe.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Qe({items:e,typeName:M.ZodTuple,rest:null,...L(t)})};var Cr=class e extends U{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.object)return w(r,{code:E.invalid_type,expected:A.object,received:r.parsedType}),O;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new Oe(r,a,r.path,a)),value:i._parse(new Oe(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ye.mergeObjectAsync(n,o):ye.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof U?new e({keyType:t,valueType:n,typeName:M.ZodRecord,...L(r)}):new e({keyType:gt.create(),valueType:t,typeName:M.ZodRecord,...L(n)})}},fn=class extends U{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.map)return w(r,{code:E.invalid_type,expected:A.map,received:r.parsedType}),O;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,u],c)=>({key:o._parse(new Oe(r,a,r.path,[c,"key"])),value:s._parse(new Oe(r,u,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let u of i){let c=await u.key,p=await u.value;if(c.status==="aborted"||p.status==="aborted")return O;(c.status==="dirty"||p.status==="dirty")&&n.dirty(),a.set(c.value,p.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let u of i){let c=u.key,p=u.value;if(c.status==="aborted"||p.status==="aborted")return O;(c.status==="dirty"||p.status==="dirty")&&n.dirty(),a.set(c.value,p.value)}return{status:n.value,value:a}}}};fn.create=(e,t,n)=>new fn({valueType:t,keyType:e,typeName:M.ZodMap,...L(n)});var hn=class e extends U{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.set)return w(r,{code:E.invalid_type,expected:A.set,received:r.parsedType}),O;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(w(r,{code:E.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(w(r,{code:E.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(u){let c=new Set;for(let p of u){if(p.status==="aborted")return O;p.status==="dirty"&&n.dirty(),c.add(p.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((u,c)=>s._parse(new Oe(r,u,r.path,c)));return r.common.async?Promise.all(a).then(u=>i(u)):i(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:I.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};hn.create=(e,t)=>new hn({valueType:e,minSize:null,maxSize:null,typeName:M.ZodSet,...L(t)});var Nr=class e extends U{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.function)return w(n,{code:E.invalid_type,expected:A.function,received:n.parsedType}),O;function r(a,u){return Hn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ln(),st].filter(c=>!!c),issueData:{code:E.invalid_arguments,argumentsError:u}})}function o(a,u){return Hn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ln(),st].filter(c=>!!c),issueData:{code:E.invalid_return_type,returnTypeError:u}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof yt){let a=this;return _e(async function(...u){let c=new we([]),p=await a._def.args.parseAsync(u,s).catch(f=>{throw c.addIssue(r(u,f)),c}),m=await Reflect.apply(i,this,p);return await a._def.returns._def.type.parseAsync(m,s).catch(f=>{throw c.addIssue(o(m,f)),c})})}else{let a=this;return _e(function(...u){let c=a._def.args.safeParse(u,s);if(!c.success)throw new we([r(u,c.error)]);let p=Reflect.apply(i,this,c.data),m=a._def.returns.safeParse(p,s);if(!m.success)throw new we([o(p,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Qe.create(t).rest(at.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||Qe.create([]).rest(at.create()),returns:n||at.create(),typeName:M.ZodFunction,...L(r)})}},Lt=class extends U{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Lt.create=(e,t)=>new Lt({getter:e,typeName:M.ZodLazy,...L(t)});var Pt=class extends U{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return w(n,{received:n.data,code:E.invalid_literal,expected:this._def.value}),O}return{status:"valid",value:t.data}}get value(){return this._def.value}};Pt.create=(e,t)=>new Pt({value:e,typeName:M.ZodLiteral,...L(t)});function fl(e,t){return new Dt({values:e,typeName:M.ZodEnum,...L(t)})}var Dt=class e extends U{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return w(n,{expected:H.joinValues(r),received:n.parsedType,code:E.invalid_type}),O}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return w(n,{received:n.data,code:E.invalid_enum_value,options:r}),O}return _e(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};Dt.create=fl;var Ut=class extends U{_parse(t){let n=H.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==A.string&&r.parsedType!==A.number){let o=H.objectValues(n);return w(r,{expected:H.joinValues(o),received:r.parsedType,code:E.invalid_type}),O}if(this._cache||(this._cache=new Set(H.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=H.objectValues(n);return w(r,{received:r.data,code:E.invalid_enum_value,options:o}),O}return _e(t.data)}get enum(){return this._def.values}};Ut.create=(e,t)=>new Ut({values:e,typeName:M.ZodNativeEnum,...L(t)});var yt=class extends U{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.promise&&n.common.async===!1)return w(n,{code:E.invalid_type,expected:A.promise,received:n.parsedType}),O;let r=n.parsedType===A.promise?n.data:Promise.resolve(n.data);return _e(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};yt.create=(e,t)=>new yt({type:e,typeName:M.ZodPromise,...L(t)});var Me=class extends U{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:i=>{w(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return O;let u=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return u.status==="aborted"?O:u.status==="dirty"?wt(u.value):n.value==="dirty"?wt(u.value):u});{if(n.value==="aborted")return O;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?O:a.status==="dirty"?wt(a.value):n.value==="dirty"?wt(a.value):a}}if(o.type==="refinement"){let i=a=>{let u=o.refinement(a,s);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?O:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?O:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!mt(i))return O;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>mt(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):O);H.assertNever(o)}};Me.create=(e,t,n)=>new Me({schema:e,typeName:M.ZodEffects,effect:t,...L(n)});Me.createWithPreprocess=(e,t,n)=>new Me({schema:t,effect:{type:"preprocess",transform:e},typeName:M.ZodEffects,...L(n)});var Re=class extends U{_parse(t){return this._getType(t)===A.undefined?_e(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Re.create=(e,t)=>new Re({innerType:e,typeName:M.ZodOptional,...L(t)});var et=class extends U{_parse(t){return this._getType(t)===A.null?_e(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};et.create=(e,t)=>new et({innerType:e,typeName:M.ZodNullable,...L(t)});var Gt=class extends U{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===A.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Gt.create=(e,t)=>new Gt({innerType:e,typeName:M.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...L(t)});var Ft=class extends U{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return cn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new we(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new we(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Ft.create=(e,t)=>new Ft({innerType:e,typeName:M.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...L(t)});var mn=class extends U{_parse(t){if(this._getType(t)!==A.nan){let r=this._getOrReturnCtx(t);return w(r,{code:E.invalid_type,expected:A.nan,received:r.parsedType}),O}return{status:"valid",value:t.data}}};mn.create=e=>new mn({typeName:M.ZodNaN,...L(e)});var fp=Symbol("zod_brand"),$n=class extends U{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},zn=class e extends U{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?O:s.status==="dirty"?(n.dirty(),wt(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?O:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:M.ZodPipeline})}},Ht=class extends U{_parse(t){let n=this._def.innerType._parse(t),r=o=>(mt(o)&&(o.value=Object.freeze(o.value)),o);return cn(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Ht.create=(e,t)=>new Ht({innerType:e,typeName:M.ZodReadonly,...L(t)});function cl(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function hl(e,t={},n){return e?vt.create().superRefine((r,o)=>{let s=e(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=cl(t,r),u=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:u})}});if(!s){let i=cl(t,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):vt.create()}var hp={object:ke.lazycreate},M;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(M||(M={}));var mp=(e,t={message:`Input not instance of ${e.name}`})=>hl(n=>n instanceof e,t),ml=gt.create,gl=kt.create,gp=mn.create,vp=At.create,vl=It.create,yp=Ct.create,bp=dn.create,xp=Nt.create,Ep=Rt.create,_p=vt.create,Tp=at.create,Sp=Fe.create,wp=pn.create,kp=lt.create,Ap=ke.create,Ip=ke.strictCreate,Cp=Ot.create,Np=Ir.create,Rp=Mt.create,Op=Qe.create,Mp=Cr.create,Lp=fn.create,Pp=hn.create,Dp=Nr.create,Up=Lt.create,Gp=Pt.create,Fp=Dt.create,Hp=Ut.create,$p=yt.create,zp=Me.create,Bp=Re.create,Vp=et.create,jp=Me.createWithPreprocess,Wp=zn.create,Xp=()=>ml().optional(),Zp=()=>gl().optional(),Kp=()=>vl().optional(),Yp={string:(e=>gt.create({...e,coerce:!0})),number:(e=>kt.create({...e,coerce:!0})),boolean:(e=>It.create({...e,coerce:!0})),bigint:(e=>At.create({...e,coerce:!0})),date:(e=>Ct.create({...e,coerce:!0}))};var qp=O;var Jp=l.object({name:l.string(),arguments:l.string()}),Qp=l.object({id:l.string(),type:l.literal("function"),function:Jp,encryptedValue:l.string().optional()}),Rr=l.object({id:l.string(),role:l.string(),content:l.string().optional(),name:l.string().optional(),encryptedValue:l.string().optional()}),ef=l.object({type:l.literal("text"),text:l.string()}),tf=l.object({type:l.literal("data"),value:l.string(),mimeType:l.string()}),nf=l.object({type:l.literal("url"),value:l.string(),mimeType:l.string().optional()}),Or=l.discriminatedUnion("type",[tf,nf]),rf=l.object({type:l.literal("image"),source:Or,metadata:l.unknown().optional()}),of=l.object({type:l.literal("audio"),source:Or,metadata:l.unknown().optional()}),sf=l.object({type:l.literal("video"),source:Or,metadata:l.unknown().optional()}),af=l.object({type:l.literal("document"),source:Or,metadata:l.unknown().optional()});var yl=l.object({type:l.literal("binary"),mimeType:l.string(),id:l.string().optional(),url:l.string().optional(),data:l.string().optional(),filename:l.string().optional()}),bl=(e,t)=>{!e.id&&!e.url&&!e.data&&t.addIssue({code:l.ZodIssueCode.custom,message:"BinaryInputContent requires at least one of id, url, or data.",path:["id"]})},xv=yl.superRefine((e,t)=>{bl(e,t)}),lf=l.discriminatedUnion("type",[ef,rf,of,sf,af,yl]),cf=lf.superRefine((e,t)=>{e.type==="binary"&&bl(e,t)}),uf=Rr.extend({role:l.literal("developer"),content:l.string()}),df=Rr.extend({role:l.literal("system"),content:l.string()}),pf=Rr.extend({role:l.literal("assistant"),content:l.string().optional(),toolCalls:l.array(Qp).optional()}),ff=Rr.extend({role:l.literal("user"),content:l.union([l.string(),l.array(cf)])}),hf=l.object({id:l.string(),content:l.string(),role:l.literal("tool"),toolCallId:l.string(),error:l.string().optional(),encryptedValue:l.string().optional()}),mf=l.object({id:l.string(),role:l.literal("activity"),activityType:l.string(),content:l.record(l.any())}),gf=l.object({id:l.string(),role:l.literal("reasoning"),content:l.string(),encryptedValue:l.string().optional()}),xl=l.discriminatedUnion("role",[uf,df,pf,ff,hf,mf,gf]),Ev=l.union([l.literal("developer"),l.literal("system"),l.literal("assistant"),l.literal("user"),l.literal("tool"),l.literal("activity"),l.literal("reasoning")]),vf=l.object({description:l.string(),value:l.string()}),El=l.object({name:l.string(),description:l.string(),parameters:l.any(),metadata:l.record(l.any()).optional()}),yf=l.object({id:l.string(),reason:l.string(),message:l.string().optional(),toolCallId:l.string().optional(),responseSchema:l.record(l.any()).optional(),expiresAt:l.string().optional(),metadata:l.record(l.any()).optional()}),bf=l.object({interruptId:l.string(),status:l.enum(["resolved","cancelled"]),payload:l.any().optional()}),xf=l.object({threadId:l.string(),runId:l.string(),parentRunId:l.string().optional(),state:l.any(),messages:l.array(xl),tools:l.array(El),context:l.array(vf),forwardedProps:l.any(),resume:l.array(bf).optional()}),Ef=l.any(),q=class extends Error{constructor(e){super(e)}},ti=class extends q{constructor(){super("Connect not implemented. This method is not supported by the current agent.")}},_f=l.object({name:l.string(),description:l.string().optional()}),Tf=l.object({name:l.string().optional(),type:l.string().optional(),description:l.string().optional(),version:l.string().optional(),provider:l.string().optional(),documentationUrl:l.string().optional(),metadata:l.record(l.unknown()).optional()}),Sf=l.object({streaming:l.boolean().optional(),websocket:l.boolean().optional(),httpBinary:l.boolean().optional(),pushNotifications:l.boolean().optional(),resumable:l.boolean().optional()}),wf=l.object({supported:l.boolean().optional(),items:l.array(El).optional(),parallelCalls:l.boolean().optional(),clientProvided:l.boolean().optional()}),kf=l.object({structuredOutput:l.boolean().optional(),supportedMimeTypes:l.array(l.string()).optional()}),Af=l.object({snapshots:l.boolean().optional(),deltas:l.boolean().optional(),memory:l.boolean().optional(),persistentState:l.boolean().optional()}),If=l.object({supported:l.boolean().optional(),delegation:l.boolean().optional(),handoffs:l.boolean().optional(),subAgents:l.array(_f).optional()}),Cf=l.object({supported:l.boolean().optional(),streaming:l.boolean().optional(),encrypted:l.boolean().optional()}),Nf=l.object({image:l.boolean().optional(),audio:l.boolean().optional(),video:l.boolean().optional(),pdf:l.boolean().optional(),file:l.boolean().optional()}),Rf=l.object({image:l.boolean().optional(),audio:l.boolean().optional()}),Of=l.object({input:Nf.optional(),output:Rf.optional()}),Mf=l.object({codeExecution:l.boolean().optional(),sandboxed:l.boolean().optional(),maxIterations:l.number().optional(),maxExecutionTime:l.number().optional()}),Lf=l.object({supported:l.boolean().optional(),approvals:l.boolean().optional(),interventions:l.boolean().optional(),feedback:l.boolean().optional(),interrupts:l.boolean().optional(),approveWithEdits:l.boolean().optional()}),_v=l.object({identity:Tf.optional(),transport:Sf.optional(),tools:wf.optional(),output:kf.optional(),state:Af.optional(),multiAgent:If.optional(),reasoning:Cf.optional(),multimodal:Of.optional(),execution:Mf.optional(),humanInTheLoop:Lf.optional(),custom:l.record(l.unknown()).optional()}),_l=l.union([l.literal("developer"),l.literal("system"),l.literal("assistant"),l.literal("user")]),v=(function(e){return e.TEXT_MESSAGE_START="TEXT_MESSAGE_START",e.TEXT_MESSAGE_CONTENT="TEXT_MESSAGE_CONTENT",e.TEXT_MESSAGE_END="TEXT_MESSAGE_END",e.TEXT_MESSAGE_CHUNK="TEXT_MESSAGE_CHUNK",e.TOOL_CALL_START="TOOL_CALL_START",e.TOOL_CALL_ARGS="TOOL_CALL_ARGS",e.TOOL_CALL_END="TOOL_CALL_END",e.TOOL_CALL_CHUNK="TOOL_CALL_CHUNK",e.TOOL_CALL_RESULT="TOOL_CALL_RESULT",e.THINKING_START="THINKING_START",e.THINKING_END="THINKING_END",e.THINKING_TEXT_MESSAGE_START="THINKING_TEXT_MESSAGE_START",e.THINKING_TEXT_MESSAGE_CONTENT="THINKING_TEXT_MESSAGE_CONTENT",e.THINKING_TEXT_MESSAGE_END="THINKING_TEXT_MESSAGE_END",e.STATE_SNAPSHOT="STATE_SNAPSHOT",e.STATE_DELTA="STATE_DELTA",e.MESSAGES_SNAPSHOT="MESSAGES_SNAPSHOT",e.ACTIVITY_SNAPSHOT="ACTIVITY_SNAPSHOT",e.ACTIVITY_DELTA="ACTIVITY_DELTA",e.RAW="RAW",e.CUSTOM="CUSTOM",e.RUN_STARTED="RUN_STARTED",e.RUN_FINISHED="RUN_FINISHED",e.RUN_ERROR="RUN_ERROR",e.STEP_STARTED="STEP_STARTED",e.STEP_FINISHED="STEP_FINISHED",e.REASONING_START="REASONING_START",e.REASONING_MESSAGE_START="REASONING_MESSAGE_START",e.REASONING_MESSAGE_CONTENT="REASONING_MESSAGE_CONTENT",e.REASONING_MESSAGE_END="REASONING_MESSAGE_END",e.REASONING_MESSAGE_CHUNK="REASONING_MESSAGE_CHUNK",e.REASONING_END="REASONING_END",e.REASONING_ENCRYPTED_VALUE="REASONING_ENCRYPTED_VALUE",e})({}),V=l.object({type:l.nativeEnum(v),timestamp:l.number().optional(),rawEvent:l.any().optional()}).passthrough(),Pf=V.extend({type:l.literal(v.TEXT_MESSAGE_START),messageId:l.string(),role:_l.default("assistant"),name:l.string().optional()}),Tl=V.extend({type:l.literal(v.TEXT_MESSAGE_CONTENT),messageId:l.string(),delta:l.string()}),Df=V.extend({type:l.literal(v.TEXT_MESSAGE_END),messageId:l.string()}),Uf=V.extend({type:l.literal(v.TEXT_MESSAGE_CHUNK),messageId:l.string().optional(),role:_l.optional(),delta:l.string().optional(),name:l.string().optional()}),Gf=V.extend({type:l.literal(v.THINKING_TEXT_MESSAGE_START)}),Ff=Tl.omit({messageId:!0,type:!0}).extend({type:l.literal(v.THINKING_TEXT_MESSAGE_CONTENT)}),Hf=V.extend({type:l.literal(v.THINKING_TEXT_MESSAGE_END)}),$f=V.extend({type:l.literal(v.TOOL_CALL_START),toolCallId:l.string(),toolCallName:l.string(),parentMessageId:l.string().optional()}),zf=V.extend({type:l.literal(v.TOOL_CALL_ARGS),toolCallId:l.string(),delta:l.string()}),Bf=V.extend({type:l.literal(v.TOOL_CALL_END),toolCallId:l.string()}),Vf=V.extend({messageId:l.string(),type:l.literal(v.TOOL_CALL_RESULT),toolCallId:l.string(),content:l.string(),role:l.literal("tool").optional()}),jf=V.extend({type:l.literal(v.TOOL_CALL_CHUNK),toolCallId:l.string().optional(),toolCallName:l.string().optional(),parentMessageId:l.string().optional(),delta:l.string().optional()}),Wf=V.extend({type:l.literal(v.THINKING_START),title:l.string().optional()}),Xf=V.extend({type:l.literal(v.THINKING_END)}),Zf=V.extend({type:l.literal(v.STATE_SNAPSHOT),snapshot:Ef}),Kf=V.extend({type:l.literal(v.STATE_DELTA),delta:l.array(l.any())}),Yf=V.extend({type:l.literal(v.MESSAGES_SNAPSHOT),messages:l.array(xl)}),qf=V.extend({type:l.literal(v.ACTIVITY_SNAPSHOT),messageId:l.string(),activityType:l.string(),content:l.record(l.any()),replace:l.boolean().optional().default(!0)}),Jf=V.extend({type:l.literal(v.ACTIVITY_DELTA),messageId:l.string(),activityType:l.string(),patch:l.array(l.any())}),Qf=V.extend({type:l.literal(v.RAW),event:l.any(),source:l.string().optional()}),eh=V.extend({type:l.literal(v.CUSTOM),name:l.string(),value:l.any()}),th=V.extend({type:l.literal(v.RUN_STARTED),threadId:l.string(),runId:l.string(),parentRunId:l.string().optional(),input:xf.optional()}),nh=l.object({type:l.literal("success")}).strict(),rh=l.object({type:l.literal("interrupt"),interrupts:l.array(yf).min(1)}).strict(),oh=l.discriminatedUnion("type",[nh,rh]),sh=V.extend({type:l.literal(v.RUN_FINISHED),threadId:l.string(),runId:l.string(),result:l.any().optional(),outcome:oh.nullable().optional().transform(e=>e??void 0)}),ih=V.extend({type:l.literal(v.RUN_ERROR),message:l.string(),code:l.string().optional()}),ah=V.extend({type:l.literal(v.STEP_STARTED),stepName:l.string()}),lh=V.extend({type:l.literal(v.STEP_FINISHED),stepName:l.string()}),ch=l.union([l.literal("tool-call"),l.literal("message")]),uh=V.extend({type:l.literal(v.REASONING_START),messageId:l.string()}),dh=V.extend({type:l.literal(v.REASONING_MESSAGE_START),messageId:l.string(),role:l.literal("reasoning")}),ph=V.extend({type:l.literal(v.REASONING_MESSAGE_CONTENT),messageId:l.string(),delta:l.string()}),fh=V.extend({type:l.literal(v.REASONING_MESSAGE_END),messageId:l.string()}),hh=V.extend({type:l.literal(v.REASONING_MESSAGE_CHUNK),messageId:l.string().optional(),delta:l.string().optional()}),mh=V.extend({type:l.literal(v.REASONING_END),messageId:l.string()}),gh=V.extend({type:l.literal(v.REASONING_ENCRYPTED_VALUE),subtype:ch,entityId:l.string(),encryptedValue:l.string()}),Mr=l.discriminatedUnion("type",[Pf,Tl,Df,Uf,Wf,Xf,Gf,Ff,Hf,$f,zf,Bf,jf,Vf,Zf,Kf,Yf,qf,Jf,Qf,eh,th,sh,ih,ah,lh,uh,dh,ph,fh,hh,mh,gh]);var ni={};ms(ni,{JsonPatchError:()=>re,_areEquals:()=>jn,applyOperation:()=>$t,applyPatch:()=>Hr,applyReducer:()=>Eh,deepClone:()=>bh,getValueByPointer:()=>Gr,validate:()=>wl,validator:()=>Fr});var vh=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var s in o)o.hasOwnProperty(s)&&(r[s]=o[s])},e(t,n)};return function(t,n){e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),yh=Object.prototype.hasOwnProperty;function Pr(e,t){return yh.call(e,t)}function Dr(e){if(Array.isArray(e)){for(var t=new Array(e.length),n=0;n<t.length;n++)t[n]=""+n;return t}if(Object.keys)return Object.keys(e);var r=[];for(var o in e)Pr(e,o)&&r.push(o);return r}function be(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function Ur(e){for(var t=0,n=e.length,r;t<n;){if(r=e.charCodeAt(t),r>=48&&r<=57){t++;continue}return!1}return!0}function tt(e){return e.indexOf("/")===-1&&e.indexOf("~")===-1?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function Bn(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Lr(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(var t=0,n=e.length;t<n;t++)if(Lr(e[t]))return!0}else if(typeof e=="object"){for(var r=Dr(e),o=r.length,s=0;s<o;s++)if(Lr(e[r[s]]))return!0}}return!1}function Sl(e,t){var n=[e];for(var r in t){var o=typeof t[r]=="object"?JSON.stringify(t[r],null,2):t[r];typeof o<"u"&&n.push(r+": "+o)}return n.join(`
698
- `)}var Vn=(function(e){vh(t,e);function t(n,r,o,s,i){var a=this.constructor,u=e.call(this,Sl(n,{name:r,index:o,operation:s,tree:i}))||this;return u.name=r,u.index=o,u.operation=s,u.tree=i,Object.setPrototypeOf(u,a.prototype),u.message=Sl(n,{name:r,index:o,operation:s,tree:i}),u}return t})(Error);var re=Vn,bh=be,gn={add:function(e,t,n){return e[t]=this.value,{newDocument:n}},remove:function(e,t,n){var r=e[t];return delete e[t],{newDocument:n,removed:r}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:function(e,t,n){var r=Gr(n,this.path);r&&(r=be(r));var o=$t(n,{op:"remove",path:this.from}).removed;return $t(n,{op:"add",path:this.path,value:o}),{newDocument:n,removed:r}},copy:function(e,t,n){var r=Gr(n,this.from);return $t(n,{op:"add",path:this.path,value:be(r)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:jn(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}},xh={add:function(e,t,n){return Ur(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:n,index:t}},remove:function(e,t,n){var r=e.splice(t,1);return{newDocument:n,removed:r[0]}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:gn.move,copy:gn.copy,test:gn.test,_get:gn._get};function Gr(e,t){if(t=="")return e;var n={op:"_get",path:t};return $t(e,n),n.value}function $t(e,t,n,r,o,s){if(n===void 0&&(n=!1),r===void 0&&(r=!0),o===void 0&&(o=!0),s===void 0&&(s=0),n&&(typeof n=="function"?n(t,0,e,t.path):Fr(t,0)),t.path===""){var i={newDocument:e};if(t.op==="add")return i.newDocument=t.value,i;if(t.op==="replace")return i.newDocument=t.value,i.removed=e,i;if(t.op==="move"||t.op==="copy")return i.newDocument=Gr(e,t.from),t.op==="move"&&(i.removed=e),i;if(t.op==="test"){if(i.test=jn(e,t.value),i.test===!1)throw new re("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return i.newDocument=e,i}else{if(t.op==="remove")return i.removed=e,i.newDocument=null,i;if(t.op==="_get")return t.value=e,i;if(n)throw new re("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,t,e);return i}}else{r||(e=be(e));var a=t.path||"",u=a.split("/"),c=e,p=1,m=u.length,x=void 0,f=void 0,h=void 0;for(typeof n=="function"?h=n:h=Fr;;){if(f=u[p],f&&f.indexOf("~")!=-1&&(f=Bn(f)),o&&(f=="__proto__"||f=="prototype"&&p>0&&u[p-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&x===void 0&&(c[f]===void 0?x=u.slice(0,p).join("/"):p==m-1&&(x=t.path),x!==void 0&&h(t,0,e,x)),p++,Array.isArray(c)){if(f==="-")f=c.length;else{if(n&&!Ur(f))throw new re("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,t,e);Ur(f)&&(f=~~f)}if(p>=m){if(n&&t.op==="add"&&f>c.length)throw new re("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,t,e);var i=xh[t.op].call(t,c,f,e);if(i.test===!1)throw new re("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return i}}else if(p>=m){var i=gn[t.op].call(t,c,f,e);if(i.test===!1)throw new re("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return i}if(c=c[f],n&&p<m&&(!c||typeof c!="object"))throw new re("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,t,e)}}}function Hr(e,t,n,r,o){if(r===void 0&&(r=!0),o===void 0&&(o=!0),n&&!Array.isArray(t))throw new re("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(e=be(e));for(var s=new Array(t.length),i=0,a=t.length;i<a;i++)s[i]=$t(e,t[i],n,!0,o,i),e=s[i].newDocument;return s.newDocument=e,s}function Eh(e,t,n){var r=$t(e,t);if(r.test===!1)throw new re("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return r.newDocument}function Fr(e,t,n,r){if(typeof e!="object"||e===null||Array.isArray(e))throw new re("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,n);if(gn[e.op]){if(typeof e.path!="string")throw new re("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,n);if(e.path.indexOf("/")!==0&&e.path.length>0)throw new re('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,n);if((e.op==="move"||e.op==="copy")&&typeof e.from!="string")throw new re("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,n);if((e.op==="add"||e.op==="replace"||e.op==="test")&&e.value===void 0)throw new re("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,n);if((e.op==="add"||e.op==="replace"||e.op==="test")&&Lr(e.value))throw new re("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,n);if(n){if(e.op=="add"){var o=e.path.split("/").length,s=r.split("/").length;if(o!==s+1&&o!==s)throw new re("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,n)}else if(e.op==="replace"||e.op==="remove"||e.op==="_get"){if(e.path!==r)throw new re("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,n)}else if(e.op==="move"||e.op==="copy"){var i={op:"_get",path:e.from,value:void 0},a=wl([i],n);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new re("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,n)}}}else throw new re("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,n)}function wl(e,t,n){try{if(!Array.isArray(e))throw new re("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)Hr(be(t),be(e),n||!0);else{n=n||Fr;for(var r=0;r<e.length;r++)n(e[r],r,t,void 0)}}catch(o){if(o instanceof re)return o;throw o}}function jn(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){var n=Array.isArray(e),r=Array.isArray(t),o,s,i;if(n&&r){if(s=e.length,s!=t.length)return!1;for(o=s;o--!==0;)if(!jn(e[o],t[o]))return!1;return!0}if(n!=r)return!1;var a=Object.keys(e);if(s=a.length,s!==Object.keys(t).length)return!1;for(o=s;o--!==0;)if(!t.hasOwnProperty(a[o]))return!1;for(o=s;o--!==0;)if(i=a[o],!jn(e[i],t[i]))return!1;return!0}return e!==e&&t!==t}var ii={};ms(ii,{compare:()=>Ch,generate:()=>ri,observe:()=>Ih,unobserve:()=>Ah});var oi=new WeakMap,_h=(function(){function e(t){this.observers=new Map,this.obj=t}return e})(),Th=(function(){function e(t,n){this.callback=t,this.observer=n}return e})();function Sh(e){return oi.get(e)}function wh(e,t){return e.observers.get(t)}function kh(e,t){e.observers.delete(t.callback)}function Ah(e,t){t.unobserve()}function Ih(e,t){var n=[],r,o=Sh(e);if(!o)o=new _h(e),oi.set(e,o);else{var s=wh(o,t);r=s&&s.observer}if(r)return r;if(r={},o.value=be(e),t){r.callback=t,r.next=null;var i=function(){ri(r)},a=function(){clearTimeout(r.next),r.next=setTimeout(i)};typeof window<"u"&&(window.addEventListener("mouseup",a),window.addEventListener("keyup",a),window.addEventListener("mousedown",a),window.addEventListener("keydown",a),window.addEventListener("change",a))}return r.patches=n,r.object=e,r.unobserve=function(){ri(r),clearTimeout(r.next),kh(o,r),typeof window<"u"&&(window.removeEventListener("mouseup",a),window.removeEventListener("keyup",a),window.removeEventListener("mousedown",a),window.removeEventListener("keydown",a),window.removeEventListener("change",a))},o.observers.set(t,new Th(t,r)),r}function ri(e,t){t===void 0&&(t=!1);var n=oi.get(e.object);si(n.value,e.object,e.patches,"",t),e.patches.length&&Hr(n.value,e.patches);var r=e.patches;return r.length>0&&(e.patches=[],e.callback&&e.callback(r)),r}function si(e,t,n,r,o){if(t!==e){typeof t.toJSON=="function"&&(t=t.toJSON());for(var s=Dr(t),i=Dr(e),a=!1,u=!1,c=i.length-1;c>=0;c--){var p=i[c],m=e[p];if(Pr(t,p)&&!(t[p]===void 0&&m!==void 0&&Array.isArray(t)===!1)){var x=t[p];typeof m=="object"&&m!=null&&typeof x=="object"&&x!=null&&Array.isArray(m)===Array.isArray(x)?si(m,x,n,r+"/"+tt(p),o):m!==x&&(a=!0,o&&n.push({op:"test",path:r+"/"+tt(p),value:be(m)}),n.push({op:"replace",path:r+"/"+tt(p),value:be(x)}))}else Array.isArray(e)===Array.isArray(t)?(o&&n.push({op:"test",path:r+"/"+tt(p),value:be(m)}),n.push({op:"remove",path:r+"/"+tt(p)}),u=!0):(o&&n.push({op:"test",path:r,value:e}),n.push({op:"replace",path:r,value:t}),a=!0)}if(!(!u&&s.length==i.length))for(var c=0;c<s.length;c++){var p=s[c];!Pr(e,p)&&t[p]!==void 0&&n.push({op:"add",path:r+"/"+tt(p),value:be(t[p])})}}}function Ch(e,t,n){n===void 0&&(n=!1);var r=[];return si(e,t,r,"",n),r}var $r=Object.assign({},ni,ii,{JsonPatchError:Vn,deepClone:be,escapePathComponent:tt,unescapePathComponent:Bn});var ai=function(e,t){return ai=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[o]=r[o])},ai(e,t)};function nt(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");ai(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function kl(e,t,n,r){function o(s){return s instanceof n?s:new n(function(i){i(s)})}return new(n||(n=Promise))(function(s,i){function a(p){try{c(r.next(p))}catch(m){i(m)}}function u(p){try{c(r.throw(p))}catch(m){i(m)}}function c(p){p.done?s(p.value):o(p.value).then(a,u)}c((r=r.apply(e,t||[])).next())})}function zr(e,t){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,o,s,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(c){return function(p){return u([c,p])}}function u(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(n=0)),n;)try{if(r=1,o&&(s=c[0]&2?o.return:c[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,c[1])).done)return s;switch(o=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return n.label++,{value:c[1],done:!1};case 5:n.label++,o=c[1],c=[0];continue;case 7:c=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){n=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){n.label=c[1];break}if(c[0]===6&&n.label<s[1]){n.label=s[1],s=c;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(c);break}s[2]&&n.ops.pop(),n.trys.pop();continue}c=t.call(e,n)}catch(p){c=[6,p],o=0}finally{r=s=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function ct(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function vn(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],i;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}return s}function yn(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}function zt(e){return this instanceof zt?(this.v=e,this):new zt(e)}function Al(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(e,t||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",i),o[Symbol.asyncIterator]=function(){return this},o;function i(f){return function(h){return Promise.resolve(h).then(f,m)}}function a(f,h){r[f]&&(o[f]=function(g){return new Promise(function(_,S){s.push([f,g,_,S])>1||u(f,g)})},h&&(o[f]=h(o[f])))}function u(f,h){try{c(r[f](h))}catch(g){x(s[0][3],g)}}function c(f){f.value instanceof zt?Promise.resolve(f.value.v).then(p,m):x(s[0][2],f)}function p(f){u("next",f)}function m(f){u("throw",f)}function x(f,h){f(h),s.shift(),s.length&&u(s[0][0],s[0][1])}}function Il(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof ct=="function"?ct(e):e[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=e[s]&&function(i){return new Promise(function(a,u){i=e[s](i),o(a,u,i.done,i.value)})}}function o(s,i,a,u){Promise.resolve(u).then(function(c){s({value:c,done:a})},i)}}function G(e){return typeof e=="function"}function bn(e){var t=function(r){Error.call(r),r.stack=new Error().stack},n=e(t);return n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n}var Br=bn(function(e){return function(n){e(this),this.message=n?n.length+` errors occurred during unsubscription:
709
+ /* Chat-history drawer \u2014 a slide-over within the chat panel. */
710
+ .drawer {
711
+ position: absolute;
712
+ inset: 0;
713
+ z-index: 5;
714
+ display: flex;
715
+ }
716
+
717
+ .drawer[hidden] {
718
+ display: none;
719
+ }
720
+
721
+ .drawer-backdrop {
722
+ position: absolute;
723
+ inset: 0;
724
+ background: rgba(20, 20, 50, 0.32);
725
+ }
726
+
727
+ .drawer-panel {
728
+ position: relative;
729
+ display: flex;
730
+ flex-direction: column;
731
+ width: min(300px, 85%);
732
+ height: 100%;
733
+ background: var(--ag-ui-bg);
734
+ border-right: 1px solid var(--ag-ui-border);
735
+ box-shadow: var(--ag-ui-shadow);
736
+ overflow: hidden;
737
+ }
738
+
739
+ .drawer-header {
740
+ display: flex;
741
+ align-items: center;
742
+ justify-content: space-between;
743
+ gap: var(--ag-ui-space);
744
+ padding: var(--ag-ui-pad);
745
+ border-bottom: 1px solid var(--ag-ui-border);
746
+ }
747
+
748
+ .drawer-title {
749
+ font-weight: 600;
750
+ }
751
+
752
+ .drawer-new {
753
+ border: 1px solid var(--ag-ui-border);
754
+ border-radius: var(--ag-ui-radius);
755
+ background: var(--ag-ui-bg);
756
+ color: var(--ag-ui-accent);
757
+ padding: 4px 10px;
758
+ font: inherit;
759
+ font-size: 0.85em;
760
+ cursor: pointer;
761
+ }
762
+
763
+ .drawer-list {
764
+ flex: 1;
765
+ min-height: 0;
766
+ overflow-y: auto;
767
+ }
768
+
769
+ .drawer-empty {
770
+ padding: var(--ag-ui-pad);
771
+ font-size: 0.9em;
772
+ color: var(--ag-ui-muted);
773
+ }
774
+
775
+ .drawer-row {
776
+ display: flex;
777
+ align-items: stretch;
778
+ border-bottom: 1px solid var(--ag-ui-border);
779
+ }
780
+
781
+ .drawer-row--active {
782
+ background: var(--ag-ui-assistant-bg);
783
+ }
784
+
785
+ .drawer-row-select {
786
+ flex: 1;
787
+ min-width: 0;
788
+ display: flex;
789
+ flex-direction: column;
790
+ gap: 2px;
791
+ padding: 8px 12px;
792
+ border: none;
793
+ background: none;
794
+ color: inherit;
795
+ font: inherit;
796
+ text-align: left;
797
+ cursor: pointer;
798
+ }
799
+
800
+ .drawer-row-title {
801
+ font-weight: 600;
802
+ overflow: hidden;
803
+ white-space: nowrap;
804
+ text-overflow: ellipsis;
805
+ }
806
+
807
+ .drawer-row-time {
808
+ font-size: 0.72em;
809
+ color: var(--ag-ui-muted);
810
+ }
811
+
812
+ .drawer-row-preview {
813
+ font-size: 0.8em;
814
+ color: var(--ag-ui-muted);
815
+ overflow: hidden;
816
+ white-space: nowrap;
817
+ text-overflow: ellipsis;
818
+ }
819
+
820
+ .drawer-row-actions {
821
+ display: flex;
822
+ align-items: center;
823
+ gap: 2px;
824
+ padding: 0 6px;
825
+ }
826
+
827
+ .drawer-row-rename,
828
+ .drawer-row-delete {
829
+ border: none;
830
+ background: none;
831
+ color: var(--ag-ui-muted);
832
+ font-size: 0.9em;
833
+ padding: 4px;
834
+ cursor: pointer;
835
+ }
836
+
837
+ .drawer-rename-input {
838
+ flex: 1;
839
+ min-width: 0;
840
+ margin: 6px 10px;
841
+ padding: 4px 8px;
842
+ border: 1px solid var(--ag-ui-accent);
843
+ border-radius: 6px;
844
+ background: var(--ag-ui-input-bg);
845
+ color: var(--ag-ui-fg);
846
+ font: inherit;
847
+ }
848
+
849
+ .drawer-confirm {
850
+ display: flex;
851
+ align-items: center;
852
+ gap: 8px;
853
+ padding: 8px 12px;
854
+ font-size: 0.85em;
855
+ }
856
+
857
+ .drawer-confirm-label {
858
+ color: var(--ag-ui-danger);
859
+ }
860
+
861
+ .drawer-confirm-yes {
862
+ border: none;
863
+ border-radius: 6px;
864
+ background: var(--ag-ui-danger);
865
+ color: #ffffff;
866
+ padding: 3px 10px;
867
+ font: inherit;
868
+ cursor: pointer;
869
+ }
870
+
871
+ .drawer-confirm-no {
872
+ border: 1px solid var(--ag-ui-border);
873
+ border-radius: 6px;
874
+ background: none;
875
+ color: inherit;
876
+ padding: 3px 10px;
877
+ font: inherit;
878
+ cursor: pointer;
879
+ }
880
+
881
+ /* Embedded placement: an inline, flush side panel rather than a dimmed,
882
+ floating slide-over. */
883
+ :host([placement="embedded"]) .drawer-backdrop {
884
+ background: none;
885
+ }
886
+
887
+ :host([placement="embedded"]) .drawer-panel {
888
+ width: 100%;
889
+ border-right: none;
890
+ box-shadow: none;
891
+ }
892
+ `;function ll(t,e=Date.now()){let n=Math.round((e-t)/1e3);if(n<60)return"just now";let r=Math.round(n/60);if(r<60)return`${r}m ago`;let o=Math.round(r/60);if(o<24)return`${o}h ago`;let s=Math.round(o/24);return s<7?`${s}d ago`:`${Math.round(s/7)}w ago`}var Ir=class{element;#e;#n;#r=[];#a="";constructor(e){this.#e=e,this.element=document.createElement("div"),this.element.className="drawer",this.element.hidden=!0;let n=document.createElement("div");n.className="drawer-backdrop",n.addEventListener("click",()=>this.close());let r=document.createElement("div");r.className="drawer-panel",r.setAttribute("role","dialog"),r.setAttribute("aria-label","Chat history");let o=document.createElement("div");o.className="drawer-header";let s=document.createElement("span");s.className="drawer-title",s.textContent="Chats";let i=document.createElement("button");i.type="button",i.className="drawer-new",i.textContent="New chat",i.addEventListener("click",()=>{this.close(),this.#e.onNew()}),o.append(s,i),this.#n=document.createElement("div"),this.#n.className="drawer-list",r.append(o,this.#n),this.element.append(n,r)}isOpen(){return!this.element.hidden}open(){this.element.hidden=!1}close(){this.element.hidden=!0}toggle(){this.element.hidden=!this.element.hidden}setThreads(e,n){this.#r=e,this.#a=n,this.#l()}#l(){if(this.#n.replaceChildren(),this.#r.length===0){let e=document.createElement("div");e.className="drawer-empty",e.textContent="No conversations yet.",this.#n.appendChild(e);return}for(let e of this.#r)this.#n.appendChild(this.#s(e))}#s(e){let n=document.createElement("div");n.className="drawer-row",e.threadId===this.#a&&n.classList.add("drawer-row--active");let r=document.createElement("button");r.type="button",r.className="drawer-row-select";let o=document.createElement("span");o.className="drawer-row-title",o.textContent=e.title;let s=document.createElement("span");s.className="drawer-row-time",s.textContent=ll(e.updatedAt);let i=document.createElement("span");i.className="drawer-row-preview",i.textContent=e.preview,r.append(o,s,i),r.addEventListener("click",()=>{this.close(),this.#e.onSelect(e.threadId)});let a=document.createElement("button");a.type="button",a.className="drawer-row-rename",a.title="Rename",a.setAttribute("aria-label","Rename conversation"),a.textContent="\u270E",a.addEventListener("click",()=>this.#t(n,e));let u=document.createElement("button");u.type="button",u.className="drawer-row-delete",u.title="Delete",u.setAttribute("aria-label","Delete conversation"),u.textContent="\u{1F5D1}",u.addEventListener("click",()=>this.#o(n,e));let l=document.createElement("div");return l.className="drawer-row-actions",l.append(a,u),n.append(r,l),n}#t(e,n){let r=document.createElement("input");r.type="text",r.className="drawer-rename-input",r.value=n.title,r.addEventListener("keydown",o=>{if(o.key==="Enter"){let s=r.value.trim();s===""?this.#l():this.#e.onRename(n.threadId,s)}else o.key==="Escape"&&this.#l()}),e.replaceChildren(r),r.focus(),r.select()}#o(e,n){let r=document.createElement("div");r.className="drawer-confirm";let o=document.createElement("span");o.className="drawer-confirm-label",o.textContent="Delete?";let s=document.createElement("button");s.type="button",s.className="drawer-confirm-yes",s.textContent="Delete",s.addEventListener("click",()=>this.#e.onDelete(n.threadId));let i=document.createElement("button");i.type="button",i.className="drawer-confirm-no",i.textContent="Cancel",i.addEventListener("click",()=>this.#l()),r.append(o,s,i),e.replaceChildren(r)}};var cl={[de.PENDING]:"running\u2026",[de.DONE]:"\u2713 done",[de.ERROR]:"\u26A0 error",[de.DECLINED]:"\u2298 declined"},jd={[de.DONE]:"Result",[de.ERROR]:"Error",[de.DECLINED]:"Declined"},Fn=class{element;#e;#n;#r;constructor(e,n,r=Ze.FULL,o){this.#n=r,this.#r=n,this.element=document.createElement("div"),this.element.className="tool-call",this.element.setAttribute("data-tool-name",e),this.element.setAttribute("data-status",de.PENDING),this.element.setAttribute("data-display",r);let s=document.createElement("div");s.className="tool-call-head";let i=document.createElement("span");if(i.className="tool-call-name",i.textContent=`\u{1F527} ${o??e}`,this.#e=document.createElement("span"),this.#e.className="tool-call-status",this.#e.textContent=cl[de.PENDING],s.append(i,this.#e),this.element.append(s),r===Ze.FULL){let a=document.createElement("pre");a.className="tool-call-args",a.textContent=JSON.stringify(n,null,2),this.element.append(a)}}settle(e,n){if(this.element.setAttribute("data-status",e),this.#e.textContent=cl[e],this.#n===Ze.MINIMAL)return;let r=document.createElement("button");r.type="button",r.className="tool-call-toggle",r.setAttribute("aria-expanded","false");let o=document.createElement("pre");o.className="tool-call-result",o.hidden=!0,this.#n===Ze.COMPACT?(r.textContent="Details",o.textContent=`args: ${JSON.stringify(this.#r)}
893
+
894
+ ${n}`):(r.textContent=jd[e],o.textContent=n),r.addEventListener("click",()=>{let s=o.hidden;o.hidden=!s,r.setAttribute("aria-expanded",String(s))}),this.element.append(r,o)}};var ve=[];for(let t=0;t<256;++t)ve.push((t+256).toString(16).slice(1));function ul(t,e=0){return(ve[t[e+0]]+ve[t[e+1]]+ve[t[e+2]]+ve[t[e+3]]+"-"+ve[t[e+4]]+ve[t[e+5]]+"-"+ve[t[e+6]]+ve[t[e+7]]+"-"+ve[t[e+8]]+ve[t[e+9]]+"-"+ve[t[e+10]]+ve[t[e+11]]+ve[t[e+12]]+ve[t[e+13]]+ve[t[e+14]]+ve[t[e+15]]).toLowerCase()}var Js,Wd=new Uint8Array(16);function Qs(){if(!Js){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Js=crypto.getRandomValues.bind(crypto)}return Js(Wd)}var Xd=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ei={randomUUID:Xd};function Zd(t,e,n){if(ei.randomUUID&&!e&&!t)return ei.randomUUID();t=t||{};let r=t.random??t.rng?.()??Qs();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return ul(r)}var ht=Zd;var c={};ys(c,{BRAND:()=>xp,DIRTY:()=>wt,EMPTY_PATH:()=>Jd,INVALID:()=>O,NEVER:()=>of,OK:()=>Te,ParseStatus:()=>ye,Schema:()=>U,ZodAny:()=>vt,ZodArray:()=>lt,ZodBigInt:()=>At,ZodBoolean:()=>It,ZodBranded:()=>zn,ZodCatch:()=>Ht,ZodDate:()=>Ct,ZodDefault:()=>Gt,ZodDiscriminatedUnion:()=>Rr,ZodEffects:()=>Me,ZodEnum:()=>Dt,ZodError:()=>we,ZodFirstPartyTypeKind:()=>M,ZodFunction:()=>Mr,ZodIntersection:()=>Mt,ZodIssueCode:()=>E,ZodLazy:()=>Lt,ZodLiteral:()=>Pt,ZodMap:()=>hn,ZodNaN:()=>gn,ZodNativeEnum:()=>Ut,ZodNever:()=>He,ZodNull:()=>Rt,ZodNullable:()=>et,ZodNumber:()=>kt,ZodObject:()=>ke,ZodOptional:()=>Re,ZodParsedType:()=>A,ZodPipeline:()=>Bn,ZodPromise:()=>yt,ZodReadonly:()=>Ft,ZodRecord:()=>Or,ZodSchema:()=>U,ZodSet:()=>mn,ZodString:()=>gt,ZodSymbol:()=>pn,ZodTransformer:()=>Me,ZodTuple:()=>Qe,ZodType:()=>U,ZodUndefined:()=>Nt,ZodUnion:()=>Ot,ZodUnknown:()=>at,ZodVoid:()=>fn,addIssueToContext:()=>w,any:()=>Cp,array:()=>Mp,bigint:()=>Sp,boolean:()=>El,coerce:()=>rf,custom:()=>yl,date:()=>wp,datetimeRegex:()=>gl,defaultErrorMap:()=>st,discriminatedUnion:()=>Up,effect:()=>Kp,enum:()=>Wp,function:()=>Bp,getErrorMap:()=>cn,getParsedType:()=>Je,instanceof:()=>Tp,intersection:()=>Gp,isAborted:()=>Cr,isAsync:()=>un,isDirty:()=>Nr,isValid:()=>mt,late:()=>Ep,lazy:()=>Vp,literal:()=>jp,makeIssue:()=>$n,map:()=>$p,nan:()=>_p,nativeEnum:()=>Xp,never:()=>Rp,null:()=>Ip,nullable:()=>qp,number:()=>xl,object:()=>Lp,objectUtil:()=>ti,oboolean:()=>nf,onumber:()=>tf,optional:()=>Yp,ostring:()=>ef,pipeline:()=>Qp,preprocess:()=>Jp,promise:()=>Zp,quotelessJson:()=>Kd,record:()=>Fp,set:()=>zp,setErrorMap:()=>qd,strictObject:()=>Pp,string:()=>bl,symbol:()=>kp,transformer:()=>Kp,tuple:()=>Hp,undefined:()=>Ap,union:()=>Dp,unknown:()=>Np,util:()=>F,void:()=>Op});var F;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=r,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(F||(F={}));var ti;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(ti||(ti={}));var A=F.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Je=t=>{switch(typeof t){case"undefined":return A.undefined;case"string":return A.string;case"number":return Number.isNaN(t)?A.nan:A.number;case"boolean":return A.boolean;case"function":return A.function;case"bigint":return A.bigint;case"symbol":return A.symbol;case"object":return Array.isArray(t)?A.array:t===null?A.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?A.promise:typeof Map<"u"&&t instanceof Map?A.map:typeof Set<"u"&&t instanceof Set?A.set:typeof Date<"u"&&t instanceof Date?A.date:A.object;default:return A.unknown}};var E=F.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Kd=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),we=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,u=0;for(;u<i.path.length;){let l=i.path[u];u===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(n(i))):a[l]=a[l]||{_errors:[]},a=a[l],u++}}};return o(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,F.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};we.create=t=>new we(t);var Yd=(t,e)=>{let n;switch(t.code){case E.invalid_type:t.received===A.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case E.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,F.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:n=`Unrecognized key(s) in object: ${F.joinValues(t.keys,", ")}`;break;case E.invalid_union:n="Invalid input";break;case E.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${F.joinValues(t.options)}`;break;case E.invalid_enum_value:n=`Invalid enum value. Expected ${F.joinValues(t.options)}, received '${t.received}'`;break;case E.invalid_arguments:n="Invalid function arguments";break;case E.invalid_return_type:n="Invalid function return type";break;case E.invalid_date:n="Invalid date";break;case E.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:F.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case E.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case E.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case E.custom:n="Invalid input";break;case E.invalid_intersection_types:n="Intersection results could not be merged";break;case E.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case E.not_finite:n="Number must be finite";break;default:n=e.defaultError,F.assertNever(t)}return{message:n}},st=Yd;var dl=st;function qd(t){dl=t}function cn(){return dl}var $n=t=>{let{data:e,path:n,errorMaps:r,issueData:o}=t,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",u=r.filter(l=>!!l).slice().reverse();for(let l of u)a=l(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},Jd=[];function w(t,e){let n=cn(),r=$n({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===st?void 0:st].filter(o=>!!o)});t.common.issues.push(r)}var ye=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let o of n){if(o.status==="aborted")return O;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return O;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:e.value,value:r}}},O=Object.freeze({status:"aborted"}),wt=t=>({status:"dirty",value:t}),Te=t=>({status:"valid",value:t}),Cr=t=>t.status==="aborted",Nr=t=>t.status==="dirty",mt=t=>t.status==="valid",un=t=>typeof Promise<"u"&&t instanceof Promise;var I;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(I||(I={}));var Oe=class{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},pl=(t,e)=>{if(mt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new we(t.common.issues);return this._error=n,this._error}}};function L(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:u}=t;return i.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:u??n??a.defaultError}},description:o}}var U=class{get description(){return this._def.description}_getType(e){return Je(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Je(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ye,ctx:{common:e.parent.common,data:e.data,parsedType:Je(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(un(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Je(e)},o=this._parseSync({data:e,path:r.path,parent:r});return pl(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Je(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return mt(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>mt(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Je(e)},o=this._parse({data:e,path:r.path,parent:r}),s=await(un(o)?o:Promise.resolve(o));return pl(r,s)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:E.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(u=>u?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new Me({schema:this,typeName:M.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Re.create(this,this._def)}nullable(){return et.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return lt.create(this)}promise(){return yt.create(this,this._def)}or(e){return Ot.create([this,e],this._def)}and(e){return Mt.create(this,e,this._def)}transform(e){return new Me({...L(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Gt({...L(this._def),innerType:this,defaultValue:n,typeName:M.ZodDefault})}brand(){return new zn({typeName:M.ZodBranded,type:this,...L(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Ht({...L(this._def),innerType:this,catchValue:n,typeName:M.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Bn.create(this,e)}readonly(){return Ft.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Qd=/^c[^\s-]{8,}$/i,ep=/^[0-9a-z]+$/,tp=/^[0-9A-HJKMNP-TV-Z]{26}$/i,np=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,rp=/^[a-z0-9_-]{21}$/i,op=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,sp=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,ip=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ap="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ni,lp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,cp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,up=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,dp=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,pp=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,fp=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,hl="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",hp=new RegExp(`^${hl}$`);function ml(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function mp(t){return new RegExp(`^${ml(t)}$`)}function gl(t){let e=`${hl}T${ml(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function gp(t,e){return!!((e==="v4"||!e)&&lp.test(t)||(e==="v6"||!e)&&up.test(t))}function vp(t,e){if(!op.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function yp(t,e){return!!((e==="v4"||!e)&&cp.test(t)||(e==="v6"||!e)&&dp.test(t))}var gt=class t extends U{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==A.string){let s=this._getOrReturnCtx(e);return w(s,{code:E.invalid_type,expected:A.string,received:s.parsedType}),O}let r=new ye,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),w(o,{code:E.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),w(o,{code:E.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?w(o,{code:E.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&w(o,{code:E.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")ip.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"email",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")ni||(ni=new RegExp(ap,"u")),ni.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"emoji",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")np.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"uuid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")rp.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"nanoid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Qd.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"cuid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")ep.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"cuid2",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")tp.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"ulid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),w(o,{validation:"url",code:E.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"regex",code:E.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),w(o,{code:E.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),w(o,{code:E.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),w(o,{code:E.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?gl(s).test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{code:E.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?hp.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{code:E.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?mp(s).test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{code:E.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?sp.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"duration",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?gp(e.data,s.version)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"ip",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?vp(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"jwt",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?yp(e.data,s.version)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"cidr",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?pp.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"base64",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?fp.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"base64url",code:E.invalid_string,message:s.message}),r.dirty()):F.assertNever(s);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:E.invalid_string,...I.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...I.errToObj(e)})}url(e){return this._addCheck({kind:"url",...I.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...I.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...I.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...I.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...I.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...I.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...I.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...I.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...I.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...I.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...I.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...I.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...I.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...I.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...I.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...I.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...I.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...I.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...I.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...I.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...I.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...I.errToObj(n)})}nonempty(e){return this.min(1,I.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};gt.create=t=>new gt({checks:[],typeName:M.ZodString,coerce:t?.coerce??!1,...L(t)});function bp(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var kt=class t extends U{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==A.number){let s=this._getOrReturnCtx(e);return w(s,{code:E.invalid_type,expected:A.number,received:s.parsedType}),O}let r,o=new ye;for(let s of this._def.checks)s.kind==="int"?F.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{code:E.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?bp(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{code:E.not_finite,message:s.message}),o.dirty()):F.assertNever(s);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,I.toString(n))}gt(e,n){return this.setLimit("min",e,!1,I.toString(n))}lte(e,n){return this.setLimit("max",e,!0,I.toString(n))}lt(e,n){return this.setLimit("max",e,!1,I.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:I.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:I.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:I.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:I.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:I.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:I.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:I.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&F.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};kt.create=t=>new kt({checks:[],typeName:M.ZodNumber,coerce:t?.coerce||!1,...L(t)});var At=class t extends U{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==A.bigint)return this._getInvalidInput(e);let r,o=new ye;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):F.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return w(n,{code:E.invalid_type,expected:A.bigint,received:n.parsedType}),O}gte(e,n){return this.setLimit("min",e,!0,I.toString(n))}gt(e,n){return this.setLimit("min",e,!1,I.toString(n))}lte(e,n){return this.setLimit("max",e,!0,I.toString(n))}lt(e,n){return this.setLimit("max",e,!1,I.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:I.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:I.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:I.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};At.create=t=>new At({checks:[],typeName:M.ZodBigInt,coerce:t?.coerce??!1,...L(t)});var It=class extends U{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==A.boolean){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:A.boolean,received:r.parsedType}),O}return Te(e.data)}};It.create=t=>new It({typeName:M.ZodBoolean,coerce:t?.coerce||!1,...L(t)});var Ct=class t extends U{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==A.date){let s=this._getOrReturnCtx(e);return w(s,{code:E.invalid_type,expected:A.date,received:s.parsedType}),O}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return w(s,{code:E.invalid_date}),O}let r=new ye,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),w(o,{code:E.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),w(o,{code:E.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):F.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:I.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:I.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};Ct.create=t=>new Ct({checks:[],coerce:t?.coerce||!1,typeName:M.ZodDate,...L(t)});var pn=class extends U{_parse(e){if(this._getType(e)!==A.symbol){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:A.symbol,received:r.parsedType}),O}return Te(e.data)}};pn.create=t=>new pn({typeName:M.ZodSymbol,...L(t)});var Nt=class extends U{_parse(e){if(this._getType(e)!==A.undefined){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:A.undefined,received:r.parsedType}),O}return Te(e.data)}};Nt.create=t=>new Nt({typeName:M.ZodUndefined,...L(t)});var Rt=class extends U{_parse(e){if(this._getType(e)!==A.null){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:A.null,received:r.parsedType}),O}return Te(e.data)}};Rt.create=t=>new Rt({typeName:M.ZodNull,...L(t)});var vt=class extends U{constructor(){super(...arguments),this._any=!0}_parse(e){return Te(e.data)}};vt.create=t=>new vt({typeName:M.ZodAny,...L(t)});var at=class extends U{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Te(e.data)}};at.create=t=>new at({typeName:M.ZodUnknown,...L(t)});var He=class extends U{_parse(e){let n=this._getOrReturnCtx(e);return w(n,{code:E.invalid_type,expected:A.never,received:n.parsedType}),O}};He.create=t=>new He({typeName:M.ZodNever,...L(t)});var fn=class extends U{_parse(e){if(this._getType(e)!==A.undefined){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:A.void,received:r.parsedType}),O}return Te(e.data)}};fn.create=t=>new fn({typeName:M.ZodVoid,...L(t)});var lt=class t extends U{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==A.array)return w(n,{code:E.invalid_type,expected:A.array,received:n.parsedType}),O;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(w(n,{code:i?E.too_big:E.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(w(n,{code:E.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(w(n,{code:E.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new Oe(n,i,n.path,a)))).then(i=>ye.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new Oe(n,i,n.path,a)));return ye.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:I.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:I.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:I.toString(n)}})}nonempty(e){return this.min(1,e)}};lt.create=(t,e)=>new lt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...L(e)});function dn(t){if(t instanceof ke){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Re.create(dn(r))}return new ke({...t._def,shape:()=>e})}else return t instanceof lt?new lt({...t._def,type:dn(t.element)}):t instanceof Re?Re.create(dn(t.unwrap())):t instanceof et?et.create(dn(t.unwrap())):t instanceof Qe?Qe.create(t.items.map(e=>dn(e))):t}var ke=class t extends U{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=F.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==A.object){let l=this._getOrReturnCtx(e);return w(l,{code:E.invalid_type,expected:A.object,received:l.parsedType}),O}let{status:r,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof He&&this._def.unknownKeys==="strip"))for(let l in o.data)i.includes(l)||a.push(l);let u=[];for(let l of i){let p=s[l],m=o.data[l];u.push({key:{status:"valid",value:l},value:p._parse(new Oe(o,m,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof He){let l=this._def.unknownKeys;if(l==="passthrough")for(let p of a)u.push({key:{status:"valid",value:p},value:{status:"valid",value:o.data[p]}});else if(l==="strict")a.length>0&&(w(o,{code:E.unrecognized_keys,keys:a}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let p of a){let m=o.data[p];u.push({key:{status:"valid",value:p},value:l._parse(new Oe(o,m,o.path,p)),alwaysSet:p in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let p of u){let m=await p.key,x=await p.value;l.push({key:m,value:x,alwaysSet:p.alwaysSet})}return l}).then(l=>ye.mergeObjectSync(r,l)):ye.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return I.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:I.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:M.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of F.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of F.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return dn(this)}partial(e){let n={};for(let r of F.objectKeys(this.shape)){let o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of F.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Re;)s=s._def.innerType;n[r]=s}return new t({...this._def,shape:()=>n})}keyof(){return vl(F.objectKeys(this.shape))}};ke.create=(t,e)=>new ke({shape:()=>t,unknownKeys:"strip",catchall:He.create(),typeName:M.ZodObject,...L(e)});ke.strictCreate=(t,e)=>new ke({shape:()=>t,unknownKeys:"strict",catchall:He.create(),typeName:M.ZodObject,...L(e)});ke.lazycreate=(t,e)=>new ke({shape:t,unknownKeys:"strip",catchall:He.create(),typeName:M.ZodObject,...L(e)});var Ot=class extends U{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new we(a.ctx.common.issues));return w(n,{code:E.invalid_union,unionErrors:i}),O}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let u of r){let l={...n,common:{...n.common,issues:[]},parent:null},p=u._parseSync({data:n.data,path:n.path,parent:l});if(p.status==="valid")return p;p.status==="dirty"&&!s&&(s={result:p,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(u=>new we(u));return w(n,{code:E.invalid_union,unionErrors:a}),O}}get options(){return this._def.options}};Ot.create=(t,e)=>new Ot({options:t,typeName:M.ZodUnion,...L(e)});var it=t=>t instanceof Lt?it(t.schema):t instanceof Me?it(t.innerType()):t instanceof Pt?[t.value]:t instanceof Dt?t.options:t instanceof Ut?F.objectValues(t.enum):t instanceof Gt?it(t._def.innerType):t instanceof Nt?[void 0]:t instanceof Rt?[null]:t instanceof Re?[void 0,...it(t.unwrap())]:t instanceof et?[null,...it(t.unwrap())]:t instanceof zn||t instanceof Ft?it(t.unwrap()):t instanceof Ht?it(t._def.innerType):[],Rr=class t extends U{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==A.object)return w(n,{code:E.invalid_type,expected:A.object,received:n.parsedType}),O;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(w(n,{code:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),O)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let o=new Map;for(let s of n){let i=it(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:M.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...L(r)})}};function ri(t,e){let n=Je(t),r=Je(e);if(t===e)return{valid:!0,data:t};if(n===A.object&&r===A.object){let o=F.objectKeys(e),s=F.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let u=ri(t[a],e[a]);if(!u.valid)return{valid:!1};i[a]=u.data}return{valid:!0,data:i}}else if(n===A.array&&r===A.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],u=ri(i,a);if(!u.valid)return{valid:!1};o.push(u.data)}return{valid:!0,data:o}}else return n===A.date&&r===A.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Mt=class extends U{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(Cr(s)||Cr(i))return O;let a=ri(s.value,i.value);return a.valid?((Nr(s)||Nr(i))&&n.dirty(),{status:n.value,value:a.data}):(w(r,{code:E.invalid_intersection_types}),O)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Mt.create=(t,e,n)=>new Mt({left:t,right:e,typeName:M.ZodIntersection,...L(n)});var Qe=class t extends U{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==A.array)return w(r,{code:E.invalid_type,expected:A.array,received:r.parsedType}),O;if(r.data.length<this._def.items.length)return w(r,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),O;!this._def.rest&&r.data.length>this._def.items.length&&(w(r,{code:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new Oe(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>ye.mergeArray(n,i)):ye.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Qe.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Qe({items:t,typeName:M.ZodTuple,rest:null,...L(e)})};var Or=class t extends U{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==A.object)return w(r,{code:E.invalid_type,expected:A.object,received:r.parsedType}),O;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new Oe(r,a,r.path,a)),value:i._parse(new Oe(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ye.mergeObjectAsync(n,o):ye.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof U?new t({keyType:e,valueType:n,typeName:M.ZodRecord,...L(r)}):new t({keyType:gt.create(),valueType:e,typeName:M.ZodRecord,...L(n)})}},hn=class extends U{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==A.map)return w(r,{code:E.invalid_type,expected:A.map,received:r.parsedType}),O;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,u],l)=>({key:o._parse(new Oe(r,a,r.path,[l,"key"])),value:s._parse(new Oe(r,u,r.path,[l,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let u of i){let l=await u.key,p=await u.value;if(l.status==="aborted"||p.status==="aborted")return O;(l.status==="dirty"||p.status==="dirty")&&n.dirty(),a.set(l.value,p.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let u of i){let l=u.key,p=u.value;if(l.status==="aborted"||p.status==="aborted")return O;(l.status==="dirty"||p.status==="dirty")&&n.dirty(),a.set(l.value,p.value)}return{status:n.value,value:a}}}};hn.create=(t,e,n)=>new hn({valueType:e,keyType:t,typeName:M.ZodMap,...L(n)});var mn=class t extends U{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==A.set)return w(r,{code:E.invalid_type,expected:A.set,received:r.parsedType}),O;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(w(r,{code:E.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(w(r,{code:E.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(u){let l=new Set;for(let p of u){if(p.status==="aborted")return O;p.status==="dirty"&&n.dirty(),l.add(p.value)}return{status:n.value,value:l}}let a=[...r.data.values()].map((u,l)=>s._parse(new Oe(r,u,r.path,l)));return r.common.async?Promise.all(a).then(u=>i(u)):i(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:I.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:I.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};mn.create=(t,e)=>new mn({valueType:t,minSize:null,maxSize:null,typeName:M.ZodSet,...L(e)});var Mr=class t extends U{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==A.function)return w(n,{code:E.invalid_type,expected:A.function,received:n.parsedType}),O;function r(a,u){return $n({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,cn(),st].filter(l=>!!l),issueData:{code:E.invalid_arguments,argumentsError:u}})}function o(a,u){return $n({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,cn(),st].filter(l=>!!l),issueData:{code:E.invalid_return_type,returnTypeError:u}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof yt){let a=this;return Te(async function(...u){let l=new we([]),p=await a._def.args.parseAsync(u,s).catch(f=>{throw l.addIssue(r(u,f)),l}),m=await Reflect.apply(i,this,p);return await a._def.returns._def.type.parseAsync(m,s).catch(f=>{throw l.addIssue(o(m,f)),l})})}else{let a=this;return Te(function(...u){let l=a._def.args.safeParse(u,s);if(!l.success)throw new we([r(u,l.error)]);let p=Reflect.apply(i,this,l.data),m=a._def.returns.safeParse(p,s);if(!m.success)throw new we([o(p,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Qe.create(e).rest(at.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||Qe.create([]).rest(at.create()),returns:n||at.create(),typeName:M.ZodFunction,...L(r)})}},Lt=class extends U{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Lt.create=(t,e)=>new Lt({getter:t,typeName:M.ZodLazy,...L(e)});var Pt=class extends U{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return w(n,{received:n.data,code:E.invalid_literal,expected:this._def.value}),O}return{status:"valid",value:e.data}}get value(){return this._def.value}};Pt.create=(t,e)=>new Pt({value:t,typeName:M.ZodLiteral,...L(e)});function vl(t,e){return new Dt({values:t,typeName:M.ZodEnum,...L(e)})}var Dt=class t extends U{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return w(n,{expected:F.joinValues(r),received:n.parsedType,code:E.invalid_type}),O}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return w(n,{received:n.data,code:E.invalid_enum_value,options:r}),O}return Te(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Dt.create=vl;var Ut=class extends U{_parse(e){let n=F.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==A.string&&r.parsedType!==A.number){let o=F.objectValues(n);return w(r,{expected:F.joinValues(o),received:r.parsedType,code:E.invalid_type}),O}if(this._cache||(this._cache=new Set(F.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=F.objectValues(n);return w(r,{received:r.data,code:E.invalid_enum_value,options:o}),O}return Te(e.data)}get enum(){return this._def.values}};Ut.create=(t,e)=>new Ut({values:t,typeName:M.ZodNativeEnum,...L(e)});var yt=class extends U{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==A.promise&&n.common.async===!1)return w(n,{code:E.invalid_type,expected:A.promise,received:n.parsedType}),O;let r=n.parsedType===A.promise?n.data:Promise.resolve(n.data);return Te(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};yt.create=(t,e)=>new yt({type:t,typeName:M.ZodPromise,...L(e)});var Me=class extends U{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{w(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return O;let u=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return u.status==="aborted"?O:u.status==="dirty"?wt(u.value):n.value==="dirty"?wt(u.value):u});{if(n.value==="aborted")return O;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?O:a.status==="dirty"?wt(a.value):n.value==="dirty"?wt(a.value):a}}if(o.type==="refinement"){let i=a=>{let u=o.refinement(a,s);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?O:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?O:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!mt(i))return O;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>mt(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):O);F.assertNever(o)}};Me.create=(t,e,n)=>new Me({schema:t,typeName:M.ZodEffects,effect:e,...L(n)});Me.createWithPreprocess=(t,e,n)=>new Me({schema:e,effect:{type:"preprocess",transform:t},typeName:M.ZodEffects,...L(n)});var Re=class extends U{_parse(e){return this._getType(e)===A.undefined?Te(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Re.create=(t,e)=>new Re({innerType:t,typeName:M.ZodOptional,...L(e)});var et=class extends U{_parse(e){return this._getType(e)===A.null?Te(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};et.create=(t,e)=>new et({innerType:t,typeName:M.ZodNullable,...L(e)});var Gt=class extends U{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===A.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Gt.create=(t,e)=>new Gt({innerType:t,typeName:M.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...L(e)});var Ht=class extends U{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return un(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new we(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new we(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Ht.create=(t,e)=>new Ht({innerType:t,typeName:M.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...L(e)});var gn=class extends U{_parse(e){if(this._getType(e)!==A.nan){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:A.nan,received:r.parsedType}),O}return{status:"valid",value:e.data}}};gn.create=t=>new gn({typeName:M.ZodNaN,...L(t)});var xp=Symbol("zod_brand"),zn=class extends U{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Bn=class t extends U{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?O:s.status==="dirty"?(n.dirty(),wt(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?O:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:M.ZodPipeline})}},Ft=class extends U{_parse(e){let n=this._def.innerType._parse(e),r=o=>(mt(o)&&(o.value=Object.freeze(o.value)),o);return un(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Ft.create=(t,e)=>new Ft({innerType:t,typeName:M.ZodReadonly,...L(e)});function fl(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function yl(t,e={},n){return t?vt.create().superRefine((r,o)=>{let s=t(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=fl(e,r),u=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:u})}});if(!s){let i=fl(e,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):vt.create()}var Ep={object:ke.lazycreate},M;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(M||(M={}));var Tp=(t,e={message:`Input not instance of ${t.name}`})=>yl(n=>n instanceof t,e),bl=gt.create,xl=kt.create,_p=gn.create,Sp=At.create,El=It.create,wp=Ct.create,kp=pn.create,Ap=Nt.create,Ip=Rt.create,Cp=vt.create,Np=at.create,Rp=He.create,Op=fn.create,Mp=lt.create,Lp=ke.create,Pp=ke.strictCreate,Dp=Ot.create,Up=Rr.create,Gp=Mt.create,Hp=Qe.create,Fp=Or.create,$p=hn.create,zp=mn.create,Bp=Mr.create,Vp=Lt.create,jp=Pt.create,Wp=Dt.create,Xp=Ut.create,Zp=yt.create,Kp=Me.create,Yp=Re.create,qp=et.create,Jp=Me.createWithPreprocess,Qp=Bn.create,ef=()=>bl().optional(),tf=()=>xl().optional(),nf=()=>El().optional(),rf={string:(t=>gt.create({...t,coerce:!0})),number:(t=>kt.create({...t,coerce:!0})),boolean:(t=>It.create({...t,coerce:!0})),bigint:(t=>At.create({...t,coerce:!0})),date:(t=>Ct.create({...t,coerce:!0}))};var of=O;var sf=c.object({name:c.string(),arguments:c.string()}),af=c.object({id:c.string(),type:c.literal("function"),function:sf,encryptedValue:c.string().optional()}),Lr=c.object({id:c.string(),role:c.string(),content:c.string().optional(),name:c.string().optional(),encryptedValue:c.string().optional()}),lf=c.object({type:c.literal("text"),text:c.string()}),cf=c.object({type:c.literal("data"),value:c.string(),mimeType:c.string()}),uf=c.object({type:c.literal("url"),value:c.string(),mimeType:c.string().optional()}),Pr=c.discriminatedUnion("type",[cf,uf]),df=c.object({type:c.literal("image"),source:Pr,metadata:c.unknown().optional()}),pf=c.object({type:c.literal("audio"),source:Pr,metadata:c.unknown().optional()}),ff=c.object({type:c.literal("video"),source:Pr,metadata:c.unknown().optional()}),hf=c.object({type:c.literal("document"),source:Pr,metadata:c.unknown().optional()});var Tl=c.object({type:c.literal("binary"),mimeType:c.string(),id:c.string().optional(),url:c.string().optional(),data:c.string().optional(),filename:c.string().optional()}),_l=(t,e)=>{!t.id&&!t.url&&!t.data&&e.addIssue({code:c.ZodIssueCode.custom,message:"BinaryInputContent requires at least one of id, url, or data.",path:["id"]})},Pv=Tl.superRefine((t,e)=>{_l(t,e)}),mf=c.discriminatedUnion("type",[lf,df,pf,ff,hf,Tl]),gf=mf.superRefine((t,e)=>{t.type==="binary"&&_l(t,e)}),vf=Lr.extend({role:c.literal("developer"),content:c.string()}),yf=Lr.extend({role:c.literal("system"),content:c.string()}),bf=Lr.extend({role:c.literal("assistant"),content:c.string().optional(),toolCalls:c.array(af).optional()}),xf=Lr.extend({role:c.literal("user"),content:c.union([c.string(),c.array(gf)])}),Ef=c.object({id:c.string(),content:c.string(),role:c.literal("tool"),toolCallId:c.string(),error:c.string().optional(),encryptedValue:c.string().optional()}),Tf=c.object({id:c.string(),role:c.literal("activity"),activityType:c.string(),content:c.record(c.any())}),_f=c.object({id:c.string(),role:c.literal("reasoning"),content:c.string(),encryptedValue:c.string().optional()}),Sl=c.discriminatedUnion("role",[vf,yf,bf,xf,Ef,Tf,_f]),Dv=c.union([c.literal("developer"),c.literal("system"),c.literal("assistant"),c.literal("user"),c.literal("tool"),c.literal("activity"),c.literal("reasoning")]),Sf=c.object({description:c.string(),value:c.string()}),wl=c.object({name:c.string(),description:c.string(),parameters:c.any(),metadata:c.record(c.any()).optional()}),wf=c.object({id:c.string(),reason:c.string(),message:c.string().optional(),toolCallId:c.string().optional(),responseSchema:c.record(c.any()).optional(),expiresAt:c.string().optional(),metadata:c.record(c.any()).optional()}),kf=c.object({interruptId:c.string(),status:c.enum(["resolved","cancelled"]),payload:c.any().optional()}),Af=c.object({threadId:c.string(),runId:c.string(),parentRunId:c.string().optional(),state:c.any(),messages:c.array(Sl),tools:c.array(wl),context:c.array(Sf),forwardedProps:c.any(),resume:c.array(kf).optional()}),If=c.any(),q=class extends Error{constructor(t){super(t)}},oi=class extends q{constructor(){super("Connect not implemented. This method is not supported by the current agent.")}},Cf=c.object({name:c.string(),description:c.string().optional()}),Nf=c.object({name:c.string().optional(),type:c.string().optional(),description:c.string().optional(),version:c.string().optional(),provider:c.string().optional(),documentationUrl:c.string().optional(),metadata:c.record(c.unknown()).optional()}),Rf=c.object({streaming:c.boolean().optional(),websocket:c.boolean().optional(),httpBinary:c.boolean().optional(),pushNotifications:c.boolean().optional(),resumable:c.boolean().optional()}),Of=c.object({supported:c.boolean().optional(),items:c.array(wl).optional(),parallelCalls:c.boolean().optional(),clientProvided:c.boolean().optional()}),Mf=c.object({structuredOutput:c.boolean().optional(),supportedMimeTypes:c.array(c.string()).optional()}),Lf=c.object({snapshots:c.boolean().optional(),deltas:c.boolean().optional(),memory:c.boolean().optional(),persistentState:c.boolean().optional()}),Pf=c.object({supported:c.boolean().optional(),delegation:c.boolean().optional(),handoffs:c.boolean().optional(),subAgents:c.array(Cf).optional()}),Df=c.object({supported:c.boolean().optional(),streaming:c.boolean().optional(),encrypted:c.boolean().optional()}),Uf=c.object({image:c.boolean().optional(),audio:c.boolean().optional(),video:c.boolean().optional(),pdf:c.boolean().optional(),file:c.boolean().optional()}),Gf=c.object({image:c.boolean().optional(),audio:c.boolean().optional()}),Hf=c.object({input:Uf.optional(),output:Gf.optional()}),Ff=c.object({codeExecution:c.boolean().optional(),sandboxed:c.boolean().optional(),maxIterations:c.number().optional(),maxExecutionTime:c.number().optional()}),$f=c.object({supported:c.boolean().optional(),approvals:c.boolean().optional(),interventions:c.boolean().optional(),feedback:c.boolean().optional(),interrupts:c.boolean().optional(),approveWithEdits:c.boolean().optional()}),Uv=c.object({identity:Nf.optional(),transport:Rf.optional(),tools:Of.optional(),output:Mf.optional(),state:Lf.optional(),multiAgent:Pf.optional(),reasoning:Df.optional(),multimodal:Hf.optional(),execution:Ff.optional(),humanInTheLoop:$f.optional(),custom:c.record(c.unknown()).optional()}),kl=c.union([c.literal("developer"),c.literal("system"),c.literal("assistant"),c.literal("user")]),v=(function(t){return t.TEXT_MESSAGE_START="TEXT_MESSAGE_START",t.TEXT_MESSAGE_CONTENT="TEXT_MESSAGE_CONTENT",t.TEXT_MESSAGE_END="TEXT_MESSAGE_END",t.TEXT_MESSAGE_CHUNK="TEXT_MESSAGE_CHUNK",t.TOOL_CALL_START="TOOL_CALL_START",t.TOOL_CALL_ARGS="TOOL_CALL_ARGS",t.TOOL_CALL_END="TOOL_CALL_END",t.TOOL_CALL_CHUNK="TOOL_CALL_CHUNK",t.TOOL_CALL_RESULT="TOOL_CALL_RESULT",t.THINKING_START="THINKING_START",t.THINKING_END="THINKING_END",t.THINKING_TEXT_MESSAGE_START="THINKING_TEXT_MESSAGE_START",t.THINKING_TEXT_MESSAGE_CONTENT="THINKING_TEXT_MESSAGE_CONTENT",t.THINKING_TEXT_MESSAGE_END="THINKING_TEXT_MESSAGE_END",t.STATE_SNAPSHOT="STATE_SNAPSHOT",t.STATE_DELTA="STATE_DELTA",t.MESSAGES_SNAPSHOT="MESSAGES_SNAPSHOT",t.ACTIVITY_SNAPSHOT="ACTIVITY_SNAPSHOT",t.ACTIVITY_DELTA="ACTIVITY_DELTA",t.RAW="RAW",t.CUSTOM="CUSTOM",t.RUN_STARTED="RUN_STARTED",t.RUN_FINISHED="RUN_FINISHED",t.RUN_ERROR="RUN_ERROR",t.STEP_STARTED="STEP_STARTED",t.STEP_FINISHED="STEP_FINISHED",t.REASONING_START="REASONING_START",t.REASONING_MESSAGE_START="REASONING_MESSAGE_START",t.REASONING_MESSAGE_CONTENT="REASONING_MESSAGE_CONTENT",t.REASONING_MESSAGE_END="REASONING_MESSAGE_END",t.REASONING_MESSAGE_CHUNK="REASONING_MESSAGE_CHUNK",t.REASONING_END="REASONING_END",t.REASONING_ENCRYPTED_VALUE="REASONING_ENCRYPTED_VALUE",t})({}),V=c.object({type:c.nativeEnum(v),timestamp:c.number().optional(),rawEvent:c.any().optional()}).passthrough(),zf=V.extend({type:c.literal(v.TEXT_MESSAGE_START),messageId:c.string(),role:kl.default("assistant"),name:c.string().optional()}),Al=V.extend({type:c.literal(v.TEXT_MESSAGE_CONTENT),messageId:c.string(),delta:c.string()}),Bf=V.extend({type:c.literal(v.TEXT_MESSAGE_END),messageId:c.string()}),Vf=V.extend({type:c.literal(v.TEXT_MESSAGE_CHUNK),messageId:c.string().optional(),role:kl.optional(),delta:c.string().optional(),name:c.string().optional()}),jf=V.extend({type:c.literal(v.THINKING_TEXT_MESSAGE_START)}),Wf=Al.omit({messageId:!0,type:!0}).extend({type:c.literal(v.THINKING_TEXT_MESSAGE_CONTENT)}),Xf=V.extend({type:c.literal(v.THINKING_TEXT_MESSAGE_END)}),Zf=V.extend({type:c.literal(v.TOOL_CALL_START),toolCallId:c.string(),toolCallName:c.string(),parentMessageId:c.string().optional()}),Kf=V.extend({type:c.literal(v.TOOL_CALL_ARGS),toolCallId:c.string(),delta:c.string()}),Yf=V.extend({type:c.literal(v.TOOL_CALL_END),toolCallId:c.string()}),qf=V.extend({messageId:c.string(),type:c.literal(v.TOOL_CALL_RESULT),toolCallId:c.string(),content:c.string(),role:c.literal("tool").optional()}),Jf=V.extend({type:c.literal(v.TOOL_CALL_CHUNK),toolCallId:c.string().optional(),toolCallName:c.string().optional(),parentMessageId:c.string().optional(),delta:c.string().optional()}),Qf=V.extend({type:c.literal(v.THINKING_START),title:c.string().optional()}),eh=V.extend({type:c.literal(v.THINKING_END)}),th=V.extend({type:c.literal(v.STATE_SNAPSHOT),snapshot:If}),nh=V.extend({type:c.literal(v.STATE_DELTA),delta:c.array(c.any())}),rh=V.extend({type:c.literal(v.MESSAGES_SNAPSHOT),messages:c.array(Sl)}),oh=V.extend({type:c.literal(v.ACTIVITY_SNAPSHOT),messageId:c.string(),activityType:c.string(),content:c.record(c.any()),replace:c.boolean().optional().default(!0)}),sh=V.extend({type:c.literal(v.ACTIVITY_DELTA),messageId:c.string(),activityType:c.string(),patch:c.array(c.any())}),ih=V.extend({type:c.literal(v.RAW),event:c.any(),source:c.string().optional()}),ah=V.extend({type:c.literal(v.CUSTOM),name:c.string(),value:c.any()}),lh=V.extend({type:c.literal(v.RUN_STARTED),threadId:c.string(),runId:c.string(),parentRunId:c.string().optional(),input:Af.optional()}),ch=c.object({type:c.literal("success")}).strict(),uh=c.object({type:c.literal("interrupt"),interrupts:c.array(wf).min(1)}).strict(),dh=c.discriminatedUnion("type",[ch,uh]),ph=V.extend({type:c.literal(v.RUN_FINISHED),threadId:c.string(),runId:c.string(),result:c.any().optional(),outcome:dh.nullable().optional().transform(t=>t??void 0)}),fh=V.extend({type:c.literal(v.RUN_ERROR),message:c.string(),code:c.string().optional()}),hh=V.extend({type:c.literal(v.STEP_STARTED),stepName:c.string()}),mh=V.extend({type:c.literal(v.STEP_FINISHED),stepName:c.string()}),gh=c.union([c.literal("tool-call"),c.literal("message")]),vh=V.extend({type:c.literal(v.REASONING_START),messageId:c.string()}),yh=V.extend({type:c.literal(v.REASONING_MESSAGE_START),messageId:c.string(),role:c.literal("reasoning")}),bh=V.extend({type:c.literal(v.REASONING_MESSAGE_CONTENT),messageId:c.string(),delta:c.string()}),xh=V.extend({type:c.literal(v.REASONING_MESSAGE_END),messageId:c.string()}),Eh=V.extend({type:c.literal(v.REASONING_MESSAGE_CHUNK),messageId:c.string().optional(),delta:c.string().optional()}),Th=V.extend({type:c.literal(v.REASONING_END),messageId:c.string()}),_h=V.extend({type:c.literal(v.REASONING_ENCRYPTED_VALUE),subtype:gh,entityId:c.string(),encryptedValue:c.string()}),Dr=c.discriminatedUnion("type",[zf,Al,Bf,Vf,Qf,eh,jf,Wf,Xf,Zf,Kf,Yf,Jf,qf,th,nh,rh,oh,sh,ih,ah,lh,ph,fh,hh,mh,vh,yh,bh,xh,Eh,Th,_h]);var si={};ys(si,{JsonPatchError:()=>re,_areEquals:()=>Wn,applyOperation:()=>$t,applyPatch:()=>Br,applyReducer:()=>Ih,deepClone:()=>kh,getValueByPointer:()=>$r,validate:()=>Cl,validator:()=>zr});var Sh=(function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var s in o)o.hasOwnProperty(s)&&(r[s]=o[s])},t(e,n)};return function(e,n){t(e,n);function r(){this.constructor=e}e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),wh=Object.prototype.hasOwnProperty;function Gr(t,e){return wh.call(t,e)}function Hr(t){if(Array.isArray(t)){for(var e=new Array(t.length),n=0;n<e.length;n++)e[n]=""+n;return e}if(Object.keys)return Object.keys(t);var r=[];for(var o in t)Gr(t,o)&&r.push(o);return r}function be(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Fr(t){for(var e=0,n=t.length,r;e<n;){if(r=t.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}function tt(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function Vn(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Ur(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,n=t.length;e<n;e++)if(Ur(t[e]))return!0}else if(typeof t=="object"){for(var r=Hr(t),o=r.length,s=0;s<o;s++)if(Ur(t[r[s]]))return!0}}return!1}function Il(t,e){var n=[t];for(var r in e){var o=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof o<"u"&&n.push(r+": "+o)}return n.join(`
895
+ `)}var jn=(function(t){Sh(e,t);function e(n,r,o,s,i){var a=this.constructor,u=t.call(this,Il(n,{name:r,index:o,operation:s,tree:i}))||this;return u.name=r,u.index=o,u.operation=s,u.tree=i,Object.setPrototypeOf(u,a.prototype),u.message=Il(n,{name:r,index:o,operation:s,tree:i}),u}return e})(Error);var re=jn,kh=be,vn={add:function(t,e,n){return t[e]=this.value,{newDocument:n}},remove:function(t,e,n){var r=t[e];return delete t[e],{newDocument:n,removed:r}},replace:function(t,e,n){var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:function(t,e,n){var r=$r(n,this.path);r&&(r=be(r));var o=$t(n,{op:"remove",path:this.from}).removed;return $t(n,{op:"add",path:this.path,value:o}),{newDocument:n,removed:r}},copy:function(t,e,n){var r=$r(n,this.from);return $t(n,{op:"add",path:this.path,value:be(r)}),{newDocument:n}},test:function(t,e,n){return{newDocument:n,test:Wn(t[e],this.value)}},_get:function(t,e,n){return this.value=t[e],{newDocument:n}}},Ah={add:function(t,e,n){return Fr(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:n,index:e}},remove:function(t,e,n){var r=t.splice(e,1);return{newDocument:n,removed:r[0]}},replace:function(t,e,n){var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:vn.move,copy:vn.copy,test:vn.test,_get:vn._get};function $r(t,e){if(e=="")return t;var n={op:"_get",path:e};return $t(t,n),n.value}function $t(t,e,n,r,o,s){if(n===void 0&&(n=!1),r===void 0&&(r=!0),o===void 0&&(o=!0),s===void 0&&(s=0),n&&(typeof n=="function"?n(e,0,t,e.path):zr(e,0)),e.path===""){var i={newDocument:t};if(e.op==="add")return i.newDocument=e.value,i;if(e.op==="replace")return i.newDocument=e.value,i.removed=t,i;if(e.op==="move"||e.op==="copy")return i.newDocument=$r(t,e.from),e.op==="move"&&(i.removed=t),i;if(e.op==="test"){if(i.test=Wn(t,e.value),i.test===!1)throw new re("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i.newDocument=t,i}else{if(e.op==="remove")return i.removed=t,i.newDocument=null,i;if(e.op==="_get")return e.value=t,i;if(n)throw new re("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,t);return i}}else{r||(t=be(t));var a=e.path||"",u=a.split("/"),l=t,p=1,m=u.length,x=void 0,f=void 0,h=void 0;for(typeof n=="function"?h=n:h=zr;;){if(f=u[p],f&&f.indexOf("~")!=-1&&(f=Vn(f)),o&&(f=="__proto__"||f=="prototype"&&p>0&&u[p-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&x===void 0&&(l[f]===void 0?x=u.slice(0,p).join("/"):p==m-1&&(x=e.path),x!==void 0&&h(e,0,t,x)),p++,Array.isArray(l)){if(f==="-")f=l.length;else{if(n&&!Fr(f))throw new re("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,t);Fr(f)&&(f=~~f)}if(p>=m){if(n&&e.op==="add"&&f>l.length)throw new re("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,t);var i=Ah[e.op].call(e,l,f,t);if(i.test===!1)throw new re("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i}}else if(p>=m){var i=vn[e.op].call(e,l,f,t);if(i.test===!1)throw new re("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i}if(l=l[f],n&&p<m&&(!l||typeof l!="object"))throw new re("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,t)}}}function Br(t,e,n,r,o){if(r===void 0&&(r=!0),o===void 0&&(o=!0),n&&!Array.isArray(e))throw new re("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(t=be(t));for(var s=new Array(e.length),i=0,a=e.length;i<a;i++)s[i]=$t(t,e[i],n,!0,o,i),t=s[i].newDocument;return s.newDocument=t,s}function Ih(t,e,n){var r=$t(t,e);if(r.test===!1)throw new re("Test operation failed","TEST_OPERATION_FAILED",n,e,t);return r.newDocument}function zr(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t))throw new re("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,n);if(vn[t.op]){if(typeof t.path!="string")throw new re("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,n);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new re('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,n);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new re("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new re("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&Ur(t.value))throw new re("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,n);if(n){if(t.op=="add"){var o=t.path.split("/").length,s=r.split("/").length;if(o!==s+1&&o!==s)throw new re("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,n)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==r)throw new re("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,n)}else if(t.op==="move"||t.op==="copy"){var i={op:"_get",path:t.from,value:void 0},a=Cl([i],n);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new re("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,n)}}}else throw new re("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,n)}function Cl(t,e,n){try{if(!Array.isArray(t))throw new re("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Br(be(e),be(t),n||!0);else{n=n||zr;for(var r=0;r<t.length;r++)n(t[r],r,e,void 0)}}catch(o){if(o instanceof re)return o;throw o}}function Wn(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var n=Array.isArray(t),r=Array.isArray(e),o,s,i;if(n&&r){if(s=t.length,s!=e.length)return!1;for(o=s;o--!==0;)if(!Wn(t[o],e[o]))return!1;return!0}if(n!=r)return!1;var a=Object.keys(t);if(s=a.length,s!==Object.keys(e).length)return!1;for(o=s;o--!==0;)if(!e.hasOwnProperty(a[o]))return!1;for(o=s;o--!==0;)if(i=a[o],!Wn(t[i],e[i]))return!1;return!0}return t!==t&&e!==e}var ci={};ys(ci,{compare:()=>Dh,generate:()=>ii,observe:()=>Ph,unobserve:()=>Lh});var ai=new WeakMap,Ch=(function(){function t(e){this.observers=new Map,this.obj=e}return t})(),Nh=(function(){function t(e,n){this.callback=e,this.observer=n}return t})();function Rh(t){return ai.get(t)}function Oh(t,e){return t.observers.get(e)}function Mh(t,e){t.observers.delete(e.callback)}function Lh(t,e){e.unobserve()}function Ph(t,e){var n=[],r,o=Rh(t);if(!o)o=new Ch(t),ai.set(t,o);else{var s=Oh(o,e);r=s&&s.observer}if(r)return r;if(r={},o.value=be(t),e){r.callback=e,r.next=null;var i=function(){ii(r)},a=function(){clearTimeout(r.next),r.next=setTimeout(i)};typeof window<"u"&&(window.addEventListener("mouseup",a),window.addEventListener("keyup",a),window.addEventListener("mousedown",a),window.addEventListener("keydown",a),window.addEventListener("change",a))}return r.patches=n,r.object=t,r.unobserve=function(){ii(r),clearTimeout(r.next),Mh(o,r),typeof window<"u"&&(window.removeEventListener("mouseup",a),window.removeEventListener("keyup",a),window.removeEventListener("mousedown",a),window.removeEventListener("keydown",a),window.removeEventListener("change",a))},o.observers.set(e,new Nh(e,r)),r}function ii(t,e){e===void 0&&(e=!1);var n=ai.get(t.object);li(n.value,t.object,t.patches,"",e),t.patches.length&&Br(n.value,t.patches);var r=t.patches;return r.length>0&&(t.patches=[],t.callback&&t.callback(r)),r}function li(t,e,n,r,o){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=Hr(e),i=Hr(t),a=!1,u=!1,l=i.length-1;l>=0;l--){var p=i[l],m=t[p];if(Gr(e,p)&&!(e[p]===void 0&&m!==void 0&&Array.isArray(e)===!1)){var x=e[p];typeof m=="object"&&m!=null&&typeof x=="object"&&x!=null&&Array.isArray(m)===Array.isArray(x)?li(m,x,n,r+"/"+tt(p),o):m!==x&&(a=!0,o&&n.push({op:"test",path:r+"/"+tt(p),value:be(m)}),n.push({op:"replace",path:r+"/"+tt(p),value:be(x)}))}else Array.isArray(t)===Array.isArray(e)?(o&&n.push({op:"test",path:r+"/"+tt(p),value:be(m)}),n.push({op:"remove",path:r+"/"+tt(p)}),u=!0):(o&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:e}),a=!0)}if(!(!u&&s.length==i.length))for(var l=0;l<s.length;l++){var p=s[l];!Gr(t,p)&&e[p]!==void 0&&n.push({op:"add",path:r+"/"+tt(p),value:be(e[p])})}}}function Dh(t,e,n){n===void 0&&(n=!1);var r=[];return li(t,e,r,"",n),r}var Vr=Object.assign({},si,ci,{JsonPatchError:jn,deepClone:be,escapePathComponent:tt,unescapePathComponent:Vn});var ui=function(t,e){return ui=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[o]=r[o])},ui(t,e)};function nt(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");ui(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function Nl(t,e,n,r){function o(s){return s instanceof n?s:new n(function(i){i(s)})}return new(n||(n=Promise))(function(s,i){function a(p){try{l(r.next(p))}catch(m){i(m)}}function u(p){try{l(r.throw(p))}catch(m){i(m)}}function l(p){p.done?s(p.value):o(p.value).then(a,u)}l((r=r.apply(t,e||[])).next())})}function jr(t,e){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,o,s,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(l){return function(p){return u([l,p])}}function u(l){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,l[0]&&(n=0)),n;)try{if(r=1,o&&(s=l[0]&2?o.return:l[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,l[1])).done)return s;switch(o=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return n.label++,{value:l[1],done:!1};case 5:n.label++,o=l[1],l=[0];continue;case 7:l=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){n=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){n.label=l[1];break}if(l[0]===6&&n.label<s[1]){n.label=s[1],s=l;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(l);break}s[2]&&n.ops.pop(),n.trys.pop();continue}l=e.call(t,n)}catch(p){l=[6,p],o=0}finally{r=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function ct(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function yn(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}return s}function bn(t,e,n){if(n||arguments.length===2)for(var r=0,o=e.length,s;r<o;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return t.concat(s||Array.prototype.slice.call(e))}function zt(t){return this instanceof zt?(this.v=t,this):new zt(t)}function Rl(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",i),o[Symbol.asyncIterator]=function(){return this},o;function i(f){return function(h){return Promise.resolve(h).then(f,m)}}function a(f,h){r[f]&&(o[f]=function(g){return new Promise(function(T,S){s.push([f,g,T,S])>1||u(f,g)})},h&&(o[f]=h(o[f])))}function u(f,h){try{l(r[f](h))}catch(g){x(s[0][3],g)}}function l(f){f.value instanceof zt?Promise.resolve(f.value.v).then(p,m):x(s[0][2],f)}function p(f){u("next",f)}function m(f){u("throw",f)}function x(f,h){f(h),s.shift(),s.length&&u(s[0][0],s[0][1])}}function Ol(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof ct=="function"?ct(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=t[s]&&function(i){return new Promise(function(a,u){i=t[s](i),o(a,u,i.done,i.value)})}}function o(s,i,a,u){Promise.resolve(u).then(function(l){s({value:l,done:a})},i)}}function G(t){return typeof t=="function"}function xn(t){var e=function(r){Error.call(r),r.stack=new Error().stack},n=t(e);return n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n}var Wr=xn(function(t){return function(n){t(this),this.message=n?n.length+` errors occurred during unsubscription:
699
896
  `+n.map(function(r,o){return o+1+") "+r.toString()}).join(`
700
- `):"",this.name="UnsubscriptionError",this.errors=n}});function Wn(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var xn=(function(){function e(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var t,n,r,o,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var a=ct(i),u=a.next();!u.done;u=a.next()){var c=u.value;c.remove(this)}}catch(g){t={error:g}}finally{try{u&&!u.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}else i.remove(this);var p=this.initialTeardown;if(G(p))try{p()}catch(g){s=g instanceof Br?g.errors:[g]}var m=this._finalizers;if(m){this._finalizers=null;try{for(var x=ct(m),f=x.next();!f.done;f=x.next()){var h=f.value;try{Cl(h)}catch(g){s=s??[],g instanceof Br?s=yn(yn([],vn(s)),vn(g.errors)):s.push(g)}}}catch(g){r={error:g}}finally{try{f&&!f.done&&(o=x.return)&&o.call(x)}finally{if(r)throw r.error}}}if(s)throw new Br(s)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)Cl(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(t)}},e.prototype._hasParent=function(t){var n=this._parentage;return n===t||Array.isArray(n)&&n.includes(t)},e.prototype._addParent=function(t){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(t),n):n?[n,t]:t},e.prototype._removeParent=function(t){var n=this._parentage;n===t?this._parentage=null:Array.isArray(n)&&Wn(n,t)},e.prototype.remove=function(t){var n=this._finalizers;n&&Wn(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e})();var li=xn.EMPTY;function Vr(e){return e instanceof xn||e&&"closed"in e&&G(e.remove)&&G(e.add)&&G(e.unsubscribe)}function Cl(e){G(e)?e():e.unsubscribe()}var He={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var En={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var o=En.delegate;return o?.setTimeout?o.setTimeout.apply(o,yn([e,t],vn(n))):setTimeout.apply(void 0,yn([e,t],vn(n)))},clearTimeout:function(e){var t=En.delegate;return(t?.clearTimeout||clearTimeout)(e)},delegate:void 0};function jr(e){En.setTimeout(function(){var t=He.onUnhandledError;if(t)t(e);else throw e})}function Xn(){}var Nl=(function(){return ci("C",void 0,void 0)})();function Rl(e){return ci("E",void 0,e)}function Ol(e){return ci("N",e,void 0)}function ci(e,t,n){return{kind:e,value:t,error:n}}var Bt=null;function _n(e){if(He.useDeprecatedSynchronousErrorHandling){var t=!Bt;if(t&&(Bt={errorThrown:!1,error:null}),e(),t){var n=Bt,r=n.errorThrown,o=n.error;if(Bt=null,r)throw o}}else e()}function Ml(e){He.useDeprecatedSynchronousErrorHandling&&Bt&&(Bt.errorThrown=!0,Bt.error=e)}var Zn=(function(e){nt(t,e);function t(n){var r=e.call(this)||this;return r.isStopped=!1,n?(r.destination=n,Vr(n)&&n.add(r)):r.destination=Mh,r}return t.create=function(n,r,o){return new Xr(n,r,o)},t.prototype.next=function(n){this.isStopped?di(Ol(n),this):this._next(n)},t.prototype.error=function(n){this.isStopped?di(Rl(n),this):(this.isStopped=!0,this._error(n))},t.prototype.complete=function(){this.isStopped?di(Nl,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(n){this.destination.next(n)},t.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t})(xn);var Nh=Function.prototype.bind;function ui(e,t){return Nh.call(e,t)}var Rh=(function(){function e(t){this.partialObserver=t}return e.prototype.next=function(t){var n=this.partialObserver;if(n.next)try{n.next(t)}catch(r){Wr(r)}},e.prototype.error=function(t){var n=this.partialObserver;if(n.error)try{n.error(t)}catch(r){Wr(r)}else Wr(t)},e.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(n){Wr(n)}},e})(),Xr=(function(e){nt(t,e);function t(n,r,o){var s=e.call(this)||this,i;if(G(n)||!n)i={next:n??void 0,error:r??void 0,complete:o??void 0};else{var a;s&&He.useDeprecatedNextContext?(a=Object.create(n),a.unsubscribe=function(){return s.unsubscribe()},i={next:n.next&&ui(n.next,a),error:n.error&&ui(n.error,a),complete:n.complete&&ui(n.complete,a)}):i=n}return s.destination=new Rh(i),s}return t})(Zn);function Wr(e){He.useDeprecatedSynchronousErrorHandling?Ml(e):jr(e)}function Oh(e){throw e}function di(e,t){var n=He.onStoppedNotification;n&&En.setTimeout(function(){return n(e,t)})}var Mh={closed:!0,next:Xn,error:Oh,complete:Xn};var Tn=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Sn(e){return e}function Zr(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return pi(e)}function pi(e){return e.length===0?Sn:e.length===1?e[0]:function(n){return e.reduce(function(r,o){return o(r)},n)}}var J=(function(){function e(t){t&&(this._subscribe=t)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(t,n,r){var o=this,s=Ph(t)?t:new Xr(t,n,r);return _n(function(){var i=o,a=i.operator,u=i.source;s.add(a?a.call(s,u):u?o._subscribe(s):o._trySubscribe(s))}),s},e.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(n){t.error(n)}},e.prototype.forEach=function(t,n){var r=this;return n=Ll(n),new n(function(o,s){var i=new Xr({next:function(a){try{t(a)}catch(u){s(u),i.unsubscribe()}},error:s,complete:o});r.subscribe(i)})},e.prototype._subscribe=function(t){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(t)},e.prototype[Tn]=function(){return this},e.prototype.pipe=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return pi(t)(this)},e.prototype.toPromise=function(t){var n=this;return t=Ll(t),new t(function(r,o){var s;n.subscribe(function(i){return s=i},function(i){return o(i)},function(){return r(s)})})},e.create=function(t){return new e(t)},e})();function Ll(e){var t;return(t=e??He.Promise)!==null&&t!==void 0?t:Promise}function Lh(e){return e&&G(e.next)&&G(e.error)&&G(e.complete)}function Ph(e){return e&&e instanceof Zn||Lh(e)&&Vr(e)}function Dh(e){return G(e?.lift)}function ue(e){return function(t){if(Dh(t))return t.lift(function(n){try{return e(n,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function he(e,t,n,r,o){return new Uh(e,t,n,r,o)}var Uh=(function(e){nt(t,e);function t(n,r,o,s,i,a){var u=e.call(this,n)||this;return u.onFinalize=i,u.shouldUnsubscribe=a,u._next=r?function(c){try{r(c)}catch(p){n.error(p)}}:e.prototype._next,u._error=s?function(c){try{s(c)}catch(p){n.error(p)}finally{this.unsubscribe()}}:e.prototype._error,u._complete=o?function(){try{o()}catch(c){n.error(c)}finally{this.unsubscribe()}}:e.prototype._complete,u}return t.prototype.unsubscribe=function(){var n;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;e.prototype.unsubscribe.call(this),!r&&((n=this.onFinalize)===null||n===void 0||n.call(this))}},t})(Zn);var Pl=bn(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var rt=(function(e){nt(t,e);function t(){var n=e.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return t.prototype.lift=function(n){var r=new Dl(this,this);return r.operator=n,r},t.prototype._throwIfClosed=function(){if(this.closed)throw new Pl},t.prototype.next=function(n){var r=this;_n(function(){var o,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var i=ct(r.currentObservers),a=i.next();!a.done;a=i.next()){var u=a.value;u.next(n)}}catch(c){o={error:c}}finally{try{a&&!a.done&&(s=i.return)&&s.call(i)}finally{if(o)throw o.error}}}})},t.prototype.error=function(n){var r=this;_n(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var o=r.observers;o.length;)o.shift().error(n)}})},t.prototype.complete=function(){var n=this;_n(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var r=n.observers;r.length;)r.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(n){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,n)},t.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},t.prototype._innerSubscribe=function(n){var r=this,o=this,s=o.hasError,i=o.isStopped,a=o.observers;return s||i?li:(this.currentObservers=null,a.push(n),new xn(function(){r.currentObservers=null,Wn(a,n)}))},t.prototype._checkFinalizedStatuses=function(n){var r=this,o=r.hasError,s=r.thrownError,i=r.isStopped;o?n.error(s):i&&n.complete()},t.prototype.asObservable=function(){var n=new J;return n.source=this,n},t.create=function(n,r){return new Dl(n,r)},t})(J);var Dl=(function(e){nt(t,e);function t(n,r){var o=e.call(this)||this;return o.destination=n,o.source=r,o}return t.prototype.next=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.next)===null||o===void 0||o.call(r,n)},t.prototype.error=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.error)===null||o===void 0||o.call(r,n)},t.prototype.complete=function(){var n,r;(r=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||r===void 0||r.call(n)},t.prototype._subscribe=function(n){var r,o;return(o=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&o!==void 0?o:li},t})(rt);var fi={now:function(){return(fi.delegate||Date).now()},delegate:void 0};var Kr=(function(e){nt(t,e);function t(n,r,o){n===void 0&&(n=1/0),r===void 0&&(r=1/0),o===void 0&&(o=fi);var s=e.call(this)||this;return s._bufferSize=n,s._windowTime=r,s._timestampProvider=o,s._buffer=[],s._infiniteTimeWindow=!0,s._infiniteTimeWindow=r===1/0,s._bufferSize=Math.max(1,n),s._windowTime=Math.max(1,r),s}return t.prototype.next=function(n){var r=this,o=r.isStopped,s=r._buffer,i=r._infiniteTimeWindow,a=r._timestampProvider,u=r._windowTime;o||(s.push(n),!i&&s.push(a.now()+u)),this._trimBuffer(),e.prototype.next.call(this,n)},t.prototype._subscribe=function(n){this._throwIfClosed(),this._trimBuffer();for(var r=this._innerSubscribe(n),o=this,s=o._infiniteTimeWindow,i=o._buffer,a=i.slice(),u=0;u<a.length&&!n.closed;u+=s?1:2)n.next(a[u]);return this._checkFinalizedStatuses(n),r},t.prototype._trimBuffer=function(){var n=this,r=n._bufferSize,o=n._timestampProvider,s=n._buffer,i=n._infiniteTimeWindow,a=(i?1:2)*r;if(r<1/0&&a<s.length&&s.splice(0,s.length-a),!i){for(var u=o.now(),c=0,p=1;p<s.length&&s[p]<=u;p+=2)c=p;c&&s.splice(0,c+1)}},t})(rt);var Yr=new J(function(e){return e.complete()});function Ul(e){return e&&G(e.schedule)}function Gh(e){return e[e.length-1]}function Gl(e){return Ul(Gh(e))?e.pop():void 0}var qr=(function(e){return e&&typeof e.length=="number"&&typeof e!="function"});function Jr(e){return G(e?.then)}function Qr(e){return G(e[Tn])}function eo(e){return Symbol.asyncIterator&&G(e?.[Symbol.asyncIterator])}function to(e){return new TypeError("You provided "+(e!==null&&typeof e=="object"?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Fh(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var no=Fh();function ro(e){return G(e?.[no])}function oo(e){return Al(this,arguments,function(){var n,r,o,s;return zr(this,function(i){switch(i.label){case 0:n=e.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,zt(n.read())];case 3:return r=i.sent(),o=r.value,s=r.done,s?[4,zt(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,zt(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return n.releaseLock(),[7];case 10:return[2]}})})}function so(e){return G(e?.getReader)}function me(e){if(e instanceof J)return e;if(e!=null){if(Qr(e))return Hh(e);if(qr(e))return $h(e);if(Jr(e))return zh(e);if(eo(e))return Fl(e);if(ro(e))return Bh(e);if(so(e))return Vh(e)}throw to(e)}function Hh(e){return new J(function(t){var n=e[Tn]();if(G(n.subscribe))return n.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function $h(e){return new J(function(t){for(var n=0;n<e.length&&!t.closed;n++)t.next(e[n]);t.complete()})}function zh(e){return new J(function(t){e.then(function(n){t.closed||(t.next(n),t.complete())},function(n){return t.error(n)}).then(null,jr)})}function Bh(e){return new J(function(t){var n,r;try{for(var o=ct(e),s=o.next();!s.done;s=o.next()){var i=s.value;if(t.next(i),t.closed)return}}catch(a){n={error:a}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}t.complete()})}function Fl(e){return new J(function(t){jh(e,t).catch(function(n){return t.error(n)})})}function Vh(e){return Fl(oo(e))}function jh(e,t){var n,r,o,s;return kl(this,void 0,void 0,function(){var i,a;return zr(this,function(u){switch(u.label){case 0:u.trys.push([0,5,6,11]),n=Il(e),u.label=1;case 1:return[4,n.next()];case 2:if(r=u.sent(),!!r.done)return[3,4];if(i=r.value,t.next(i),t.closed)return[2];u.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=u.sent(),o={error:a},[3,11];case 6:return u.trys.push([6,,9,10]),r&&!r.done&&(s=n.return)?[4,s.call(n)]:[3,8];case 7:u.sent(),u.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})}function Le(e,t,n,r,o){r===void 0&&(r=0),o===void 0&&(o=!1);var s=t.schedule(function(){n(),o?e.add(this.schedule(null,r)):this.unsubscribe()},r);if(e.add(s),!o)return s}function io(e,t){return t===void 0&&(t=0),ue(function(n,r){n.subscribe(he(r,function(o){return Le(r,e,function(){return r.next(o)},t)},function(){return Le(r,e,function(){return r.complete()},t)},function(o){return Le(r,e,function(){return r.error(o)},t)}))})}function ao(e,t){return t===void 0&&(t=0),ue(function(n,r){r.add(e.schedule(function(){return n.subscribe(r)},t))})}function Hl(e,t){return me(e).pipe(ao(t),io(t))}function $l(e,t){return me(e).pipe(ao(t),io(t))}function zl(e,t){return new J(function(n){var r=0;return t.schedule(function(){r===e.length?n.complete():(n.next(e[r++]),n.closed||this.schedule())})})}function Bl(e,t){return new J(function(n){var r;return Le(n,t,function(){r=e[no](),Le(n,t,function(){var o,s,i;try{o=r.next(),s=o.value,i=o.done}catch(a){n.error(a);return}i?n.complete():n.next(s)},0,!0)}),function(){return G(r?.return)&&r.return()}})}function lo(e,t){if(!e)throw new Error("Iterable cannot be null");return new J(function(n){Le(n,t,function(){var r=e[Symbol.asyncIterator]();Le(n,t,function(){r.next().then(function(o){o.done?n.complete():n.next(o.value)})},0,!0)})})}function Vl(e,t){return lo(oo(e),t)}function jl(e,t){if(e!=null){if(Qr(e))return Hl(e,t);if(qr(e))return zl(e,t);if(Jr(e))return $l(e,t);if(eo(e))return lo(e,t);if(ro(e))return Bl(e,t);if(so(e))return Vl(e,t)}throw to(e)}function Vt(e,t){return t?jl(e,t):me(e)}function te(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=Gl(e);return Vt(e,n)}function Q(e,t){var n=G(e)?e:function(){return e},r=function(o){return o.error(n())};return new J(t?function(o){return t.schedule(r,0,o)}:r)}var Wl=bn(function(e){return function(){e(this),this.name="EmptyError",this.message="no elements in sequence"}});function co(e,t){var n=typeof t=="object";return new Promise(function(r,o){var s=!1,i;e.subscribe({next:function(a){i=a,s=!0},error:o,complete:function(){s?r(i):n?r(t.defaultValue):o(new Wl)}})})}function jt(e,t){return ue(function(n,r){var o=0;n.subscribe(he(r,function(s){r.next(e.call(t,s,o++))}))})}function Xl(e,t,n,r,o,s,i,a){var u=[],c=0,p=0,m=!1,x=function(){m&&!u.length&&!c&&t.complete()},f=function(g){return c<r?h(g):u.push(g)},h=function(g){s&&t.next(g),c++;var _=!1;me(n(g,p++)).subscribe(he(t,function(S){o?.(S),s?f(S):t.next(S)},function(){_=!0},void 0,function(){if(_)try{c--;for(var S=function(){var b=u.shift();i?Le(t,i,function(){return h(b)}):h(b)};u.length&&c<r;)S();x()}catch(b){t.error(b)}}))};return e.subscribe(he(t,f,function(){m=!0,x()})),function(){a?.()}}function Ae(e,t,n){return n===void 0&&(n=1/0),G(t)?Ae(function(r,o){return jt(function(s,i){return t(r,s,o,i)})(me(e(r,o)))},n):(typeof t=="number"&&(n=t),ue(function(r,o){return Xl(r,o,e,n)}))}function hi(e){return e===void 0&&(e=1/0),Ae(Sn,e)}function uo(e){return new J(function(t){me(e()).subscribe(t)})}function Kn(e){return ue(function(t,n){var r=null,o=!1,s;r=t.subscribe(he(n,void 0,void 0,function(i){s=me(e(i,Kn(e)(t))),r?(r.unsubscribe(),r=null,s.subscribe(n)):o=!0})),o&&(r.unsubscribe(),r=null,s.subscribe(n))})}function po(e,t){return G(t)?Ae(e,t,1):Ae(e,1)}function mi(e){return ue(function(t,n){var r=!1;t.subscribe(he(n,function(o){r=!0,n.next(o)},function(){r||n.next(e),n.complete()}))})}function Wt(e){return ue(function(t,n){try{t.subscribe(n)}finally{n.add(e)}})}function gi(e,t){return ue(function(n,r){var o=null,s=0,i=!1,a=function(){return i&&!o&&r.complete()};n.subscribe(he(r,function(u){o?.unsubscribe();var c=0,p=s++;me(e(u,p)).subscribe(o=he(r,function(m){return r.next(t?t(u,m,p,c++):m)},function(){o=null,a()}))},function(){i=!0,a()}))})}function fo(e){return ue(function(t,n){me(e).subscribe(he(n,function(){return n.complete()},Xn)),!n.closed&&t.subscribe(n)})}function vi(e,t,n){var r=G(e)||t||n?{next:e,error:t,complete:n}:e;return r?ue(function(o,s){var i;(i=r.subscribe)===null||i===void 0||i.call(r);var a=!0;o.subscribe(he(s,function(u){var c;(c=r.next)===null||c===void 0||c.call(r,u),s.next(u)},function(){var u;a=!1,(u=r.complete)===null||u===void 0||u.call(r),s.complete()},function(u){var c;a=!1,(c=r.error)===null||c===void 0||c.call(r,u),s.error(u)},function(){var u,c;a&&((u=r.unsubscribe)===null||u===void 0||u.call(r)),(c=r.finalize)===null||c===void 0||c.call(r)}))}):Sn}function Zl(e){return` \r
701
- `.indexOf(e)>=0}function ho(e){for(var t=["topLevel"],n=0,r,o,s,i=function(b){return t.push(b)},a=function(b){return t[t.length-1]=b},u=function(b){r==null&&(r=n,o=t.length,s=b)},c=function(b){b===s&&(r=void 0,o=void 0,s=void 0)},p=function(){return t.pop()},m=function(){return n--},x=function(b){if("0"<=b&&b<="9"){i("number");return}switch(b){case'"':i("string");return;case"-":i("numberNeedsDigit");return;case"t":i("true");return;case"f":i("false");return;case"n":i("null");return;case"[":i("arrayNeedsValue");return;case"{":i("objectNeedsKey");return}},f=e.length;n<f;n++){var h=e[n];switch(t[t.length-1]){case"topLevel":x(h);break;case"string":switch(h){case'"':p();break;case"\\":u("stringEscape"),i("stringEscaped");break}break;case"stringEscaped":h==="u"?i("stringUnicode"):(c("stringEscape"),p());break;case"stringUnicode":n-e.lastIndexOf("u",n)===4&&(c("stringEscape"),p());break;case"number":h==="."?a("numberNeedsDigit"):h==="e"||h==="E"?a("numberNeedsExponent"):(h<"0"||h>"9")&&(m(),p());break;case"numberNeedsDigit":a("number");break;case"numberNeedsExponent":a(h==="+"||h==="-"?"numberNeedsDigit":"number");break;case"true":case"false":case"null":(h<"a"||h>"z")&&(m(),p());break;case"arrayNeedsValue":h==="]"?p():Zl(h)||(c("collectionItem"),a("arrayNeedsComma"),x(h));break;case"arrayNeedsComma":h==="]"?p():h===","&&(u("collectionItem"),a("arrayNeedsValue"));break;case"objectNeedsKey":h==="}"?p():h==='"'&&(u("collectionItem"),a("objectNeedsColon"),i("string"));break;case"objectNeedsColon":h===":"&&a("objectNeedsValue");break;case"objectNeedsValue":Zl(h)||(c("collectionItem"),a("objectNeedsComma"),x(h));break;case"objectNeedsComma":h==="}"?p():h===","&&(u("collectionItem"),a("objectNeedsKey"));break}}o!=null&&(t.length=o);for(var g=[r!=null?e.slice(0,r):e],_=function(b){return g.push(b.slice(e.length-e.lastIndexOf(b[0])))},S=t.length-1;S>=0;S--)switch(t[S]){case"string":g.push('"');break;case"numberNeedsDigit":case"numberNeedsExponent":g.push("0");break;case"true":_("true");break;case"false":_("false");break;case"null":_("null");break;case"arrayNeedsValue":case"arrayNeedsComma":g.push("]");break;case"objectNeedsKey":case"objectNeedsColon":case"objectNeedsValue":case"objectNeedsComma":g.push("}");break}return g.join("")}function Yl(){let e=0,t=0;for(let r=0;r<28;r+=7){let o=this.buf[this.pos++];if(e|=(o&127)<<r,(o&128)==0)return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(n&15)<<28,t=(n&112)>>4,(n&128)==0)return this.assertBounds(),[e,t];for(let r=3;r<=31;r+=7){let o=this.buf[this.pos++];if(t|=(o&127)<<r,(o&128)==0)return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function go(e,t,n){for(let s=0;s<28;s=s+7){let i=e>>>s,a=!(!(i>>>7)&&t==0),u=(a?i|128:i)&255;if(n.push(u),!a)return}let r=e>>>28&15|(t&7)<<4,o=t>>3!=0;if(n.push((o?r|128:r)&255),!!o){for(let s=3;s<31;s=s+7){let i=t>>>s,a=!!(i>>>7),u=(a?i|128:i)&255;if(n.push(u),!a)return}n.push(t>>>31&1)}}var mo=4294967296;function yi(e){let t=e[0]==="-";t&&(e=e.slice(1));let n=1e6,r=0,o=0;function s(i,a){let u=Number(e.slice(i,a));o*=n,r=r*n+u,r>=mo&&(o=o+(r/mo|0),r=r%mo)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),t?Jl(r,o):xi(r,o)}function ql(e,t){let n=xi(e,t),r=n.hi&2147483648;r&&(n=Jl(n.lo,n.hi));let o=bi(n.lo,n.hi);return r?"-"+o:o}function bi(e,t){if({lo:e,hi:t}=Wh(e,t),t<=2097151)return String(mo*t+e);let n=e&16777215,r=(e>>>24|t<<8)&16777215,o=t>>16&65535,s=n+r*6777216+o*6710656,i=r+o*8147497,a=o*2,u=1e7;return s>=u&&(i+=Math.floor(s/u),s%=u),i>=u&&(a+=Math.floor(i/u),i%=u),a.toString()+Kl(i)+Kl(s)}function Wh(e,t){return{lo:e>>>0,hi:t>>>0}}function xi(e,t){return{lo:e|0,hi:t|0}}function Jl(e,t){return t=~t,e?e=~e+1:t+=1,xi(e,t)}var Kl=e=>{let t=String(e);return"0000000".slice(t.length)+t};function Ei(e,t){if(e>=0){for(;e>127;)t.push(e&127|128),e=e>>>7;t.push(e)}else{for(let n=0;n<9;n++)t.push(e&127|128),e=e>>7;t.push(1)}}function Ql(){let e=this.buf[this.pos++],t=e&127;if((e&128)==0)return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(e&127)<<7,(e&128)==0)return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(e&127)<<14,(e&128)==0)return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(e&127)<<21,(e&128)==0)return this.assertBounds(),t;e=this.buf[this.pos++],t|=(e&15)<<28;for(let n=5;(e&128)!==0&&n<10;n++)e=this.buf[this.pos++];if((e&128)!=0)throw new Error("invalid varint");return this.assertBounds(),t>>>0}var $e=Xh();function Xh(){let e=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof e.getBigInt64=="function"&&typeof e.getBigUint64=="function"&&typeof e.setBigInt64=="function"&&typeof e.setBigUint64=="function"&&(!!globalThis.Deno||typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){let n=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),o=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(i){let a=typeof i=="bigint"?i:BigInt(i);if(a>r||a<n)throw new Error(`invalid int64: ${i}`);return a},uParse(i){let a=typeof i=="bigint"?i:BigInt(i);if(a>s||a<o)throw new Error(`invalid uint64: ${i}`);return a},enc(i){return e.setBigInt64(0,this.parse(i),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(i){return e.setBigInt64(0,this.uParse(i),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec(i,a){return e.setInt32(0,i,!0),e.setInt32(4,a,!0),e.getBigInt64(0,!0)},uDec(i,a){return e.setInt32(0,i,!0),e.setInt32(4,a,!0),e.getBigUint64(0,!0)}}}return{zero:"0",supported:!1,parse(n){return typeof n!="string"&&(n=n.toString()),ec(n),n},uParse(n){return typeof n!="string"&&(n=n.toString()),tc(n),n},enc(n){return typeof n!="string"&&(n=n.toString()),ec(n),yi(n)},uEnc(n){return typeof n!="string"&&(n=n.toString()),tc(n),yi(n)},dec(n,r){return ql(n,r)},uDec(n,r){return bi(n,r)}}}function ec(e){if(!/^-?[0-9]+$/.test(e))throw new Error("invalid int64: "+e)}function tc(e){if(!/^[0-9]+$/.test(e))throw new Error("invalid uint64: "+e)}var _i=Symbol.for("@bufbuild/protobuf/text-encoding");function Ti(){if(globalThis[_i]==null){let e=new globalThis.TextEncoder,t=new globalThis.TextDecoder,n;globalThis[_i]={encodeUtf8(r){return e.encode(r)},decodeUtf8(r,o){return o?(n===void 0&&(n=new globalThis.TextDecoder("utf-8",{fatal:!0})),n.decode(r)):t.decode(r)},checkUtf8(r){try{return encodeURIComponent(r),!0}catch{return!1}}}}return globalThis[_i]}var bt;(function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"})(bt||(bt={}));var Zh=34028234663852886e22,Kh=-34028234663852886e22,Yh=4294967295,qh=2147483647,Jh=-2147483648,D=class{constructor(t=Ti().encodeUtf8){this.encodeUtf8=t,this.stack=[],this.chunks=[],this.buf=[]}finish(){this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]);let t=0;for(let o=0;o<this.chunks.length;o++)t+=this.chunks[o].length;let n=new Uint8Array(t),r=0;for(let o=0;o<this.chunks.length;o++)n.set(this.chunks[o],r),r+=this.chunks[o].length;return this.chunks=[],n}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let t=this.finish(),n=this.stack.pop();if(!n)throw new Error("invalid state, fork stack empty");return this.chunks=n.chunks,this.buf=n.buf,this.uint32(t.byteLength),this.raw(t)}tag(t,n){return this.uint32((t<<3|n)>>>0)}raw(t){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(t),this}uint32(t){for(nc(t);t>127;)this.buf.push(t&127|128),t=t>>>7;return this.buf.push(t),this}int32(t){return Si(t),Ei(t,this.buf),this}bool(t){return this.buf.push(t?1:0),this}bytes(t){return this.uint32(t.byteLength),this.raw(t)}string(t){let n=this.encodeUtf8(t);return this.uint32(n.byteLength),this.raw(n)}float(t){Qh(t);let n=new Uint8Array(4);return new DataView(n.buffer).setFloat32(0,t,!0),this.raw(n)}double(t){let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,t,!0),this.raw(n)}fixed32(t){nc(t);let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t,!0),this.raw(n)}sfixed32(t){Si(t);let n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,t,!0),this.raw(n)}sint32(t){return Si(t),t=(t<<1^t>>31)>>>0,Ei(t,this.buf),this}sfixed64(t){let n=new Uint8Array(8),r=new DataView(n.buffer),o=$e.enc(t);return r.setInt32(0,o.lo,!0),r.setInt32(4,o.hi,!0),this.raw(n)}fixed64(t){let n=new Uint8Array(8),r=new DataView(n.buffer),o=$e.uEnc(t);return r.setInt32(0,o.lo,!0),r.setInt32(4,o.hi,!0),this.raw(n)}int64(t){let n=$e.enc(t);return go(n.lo,n.hi,this.buf),this}sint64(t){let n=$e.enc(t),r=n.hi>>31,o=n.lo<<1^r,s=(n.hi<<1|n.lo>>>31)^r;return go(o,s,this.buf),this}uint64(t){let n=$e.uEnc(t);return go(n.lo,n.hi,this.buf),this}},T=class{constructor(t,n=Ti().decodeUtf8){this.decodeUtf8=n,this.varint64=Yl,this.uint32=Ql,this.buf=t,this.len=t.length,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}tag(){let t=this.pos,n=this.uint32(),r=this.pos-t;if(r>5||r==5&&this.buf[this.pos-1]>15)throw new Error("illegal tag: varint overflows uint32");let o=n>>>3,s=n&7;if(o<=0||s>5)throw new Error("illegal tag: field no "+o+" wire type "+s);return[o,s]}skip(t,n){let r=this.pos;switch(t){case bt.Varint:for(;this.buf[this.pos++]&128;);break;case bt.Bit64:this.pos+=4;case bt.Bit32:this.pos+=4;break;case bt.LengthDelimited:let o=this.uint32();this.pos+=o;break;case bt.StartGroup:for(;;){let[s,i]=this.tag();if(i===bt.EndGroup){if(n!==void 0&&s!==n)throw new Error("invalid end group tag");break}this.skip(i,s)}break;default:throw new Error("cant skip wire type "+t)}return this.assertBounds(),this.buf.subarray(r,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)}int64(){return $e.dec(...this.varint64())}uint64(){return $e.uDec(...this.varint64())}sint64(){let[t,n]=this.varint64(),r=-(t&1);return t=(t>>>1|(n&1)<<31)^r,n=n>>>1^r,$e.dec(t,n)}bool(){let[t,n]=this.varint64();return t!==0||n!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return $e.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return $e.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let t=this.uint32(),n=this.pos;return this.pos+=t,this.assertBounds(),this.buf.subarray(n,n+t)}string(t){return this.decodeUtf8(this.bytes(),t)}};function Si(e){if(typeof e=="string")e=Number(e);else if(typeof e!="number")throw new Error("invalid int32: "+typeof e);if(!Number.isInteger(e)||e>qh||e<Jh)throw new Error("invalid int32: "+e)}function nc(e){if(typeof e=="string")e=Number(e);else if(typeof e!="number")throw new Error("invalid uint32: "+typeof e);if(!Number.isInteger(e)||e>Yh||e<0)throw new Error("invalid uint32: "+e)}function Qh(e){if(typeof e=="string"){let t=e;if(e=Number(e),Number.isNaN(e)&&t!=="NaN")throw new Error("invalid float32: "+t)}else if(typeof e!="number")throw new Error("invalid float32: "+typeof e);if(Number.isFinite(e)&&(e>Zh||e<Kh))throw new Error("invalid float32: "+e)}var em=(function(e){return e[e.NULL_VALUE=0]="NULL_VALUE",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED",e})({});function wi(){return{fields:{}}}var Yn={encode(e,t=new D){return Object.entries(e.fields).forEach(([n,r])=>{r!==void 0&&Ii.encode({key:n,value:r},t.uint32(10).fork()).join()}),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=wi();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:{if(s!==10)break;let i=Ii.decode(n,n.uint32());i.value!==void 0&&(o.fields[i.key]=i.value);continue}}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Yn.fromPartial(e??{})},fromPartial(e){let t=wi();return t.fields=Object.entries(e.fields??{}).reduce((n,[r,o])=>(o!==void 0&&(n[r]=o),n),{}),t},wrap(e){let t=wi();if(e!==void 0)for(let n of Object.keys(e))t.fields[n]=e[n];return t},unwrap(e){let t={};if(e.fields)for(let n of Object.keys(e.fields))t[n]=e.fields[n];return t}};function rc(){return{key:"",value:void 0}}var Ii={encode(e,t=new D){return e.key!==""&&t.uint32(10).string(e.key),e.value!==void 0&&N.encode(N.wrap(e.value),t.uint32(18).fork()).join(),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=rc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.key=n.string();continue;case 2:if(s!==18)break;o.value=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Ii.fromPartial(e??{})},fromPartial(e){let t=rc();return t.key=e.key??"",t.value=e.value??void 0,t}};function ki(){return{nullValue:void 0,numberValue:void 0,stringValue:void 0,boolValue:void 0,structValue:void 0,listValue:void 0}}var N={encode(e,t=new D){return e.nullValue!==void 0&&t.uint32(8).int32(e.nullValue),e.numberValue!==void 0&&t.uint32(17).double(e.numberValue),e.stringValue!==void 0&&t.uint32(26).string(e.stringValue),e.boolValue!==void 0&&t.uint32(32).bool(e.boolValue),e.structValue!==void 0&&Yn.encode(Yn.wrap(e.structValue),t.uint32(42).fork()).join(),e.listValue!==void 0&&qn.encode(qn.wrap(e.listValue),t.uint32(50).fork()).join(),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=ki();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==8)break;o.nullValue=n.int32();continue;case 2:if(s!==17)break;o.numberValue=n.double();continue;case 3:if(s!==26)break;o.stringValue=n.string();continue;case 4:if(s!==32)break;o.boolValue=n.bool();continue;case 5:if(s!==42)break;o.structValue=Yn.unwrap(Yn.decode(n,n.uint32()));continue;case 6:if(s!==50)break;o.listValue=qn.unwrap(qn.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return N.fromPartial(e??{})},fromPartial(e){let t=ki();return t.nullValue=e.nullValue??void 0,t.numberValue=e.numberValue??void 0,t.stringValue=e.stringValue??void 0,t.boolValue=e.boolValue??void 0,t.structValue=e.structValue??void 0,t.listValue=e.listValue??void 0,t},wrap(e){let t=ki();if(e===null)t.nullValue=em.NULL_VALUE;else if(typeof e=="boolean")t.boolValue=e;else if(typeof e=="number")t.numberValue=e;else if(typeof e=="string")t.stringValue=e;else if(globalThis.Array.isArray(e))t.listValue=e;else if(typeof e=="object")t.structValue=e;else if(typeof e<"u")throw new globalThis.Error("Unsupported any value type: "+typeof e);return t},unwrap(e){if(e.stringValue!==void 0)return e.stringValue;if(e?.numberValue!==void 0)return e.numberValue;if(e?.boolValue!==void 0)return e.boolValue;if(e?.structValue!==void 0)return e.structValue;if(e?.listValue!==void 0)return e.listValue;if(e?.nullValue!==void 0)return null}};function Ai(){return{values:[]}}var qn={encode(e,t=new D){for(let n of e.values)N.encode(N.wrap(n),t.uint32(10).fork()).join();return t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=Ai();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.values.push(N.unwrap(N.decode(n,n.uint32())));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return qn.fromPartial(e??{})},fromPartial(e){let t=Ai();return t.values=e.values?.map(n=>n)||[],t},wrap(e){let t=Ai();return t.values=e??[],t},unwrap(e){return e?.hasOwnProperty("values")&&globalThis.Array.isArray(e.values)?e.values:e}},tm=(function(e){return e[e.ADD=0]="ADD",e[e.REMOVE=1]="REMOVE",e[e.REPLACE=2]="REPLACE",e[e.MOVE=3]="MOVE",e[e.COPY=4]="COPY",e[e.TEST=5]="TEST",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED",e})({});function oc(){return{op:0,path:"",from:void 0,value:void 0}}var yo={encode(e,t=new D){return e.op!==0&&t.uint32(8).int32(e.op),e.path!==""&&t.uint32(18).string(e.path),e.from!==void 0&&t.uint32(26).string(e.from),e.value!==void 0&&N.encode(N.wrap(e.value),t.uint32(34).fork()).join(),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=oc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==8)break;o.op=n.int32();continue;case 2:if(s!==18)break;o.path=n.string();continue;case 3:if(s!==26)break;o.from=n.string();continue;case 4:if(s!==34)break;o.value=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return yo.fromPartial(e??{})},fromPartial(e){let t=oc();return t.op=e.op??0,t.path=e.path??"",t.from=e.from??void 0,t.value=e.value??void 0,t}};function sc(){return{id:"",type:"",function:void 0}}var bo={encode(e,t=new D){return e.id!==""&&t.uint32(10).string(e.id),e.type!==""&&t.uint32(18).string(e.type),e.function!==void 0&&xo.encode(e.function,t.uint32(26).fork()).join(),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=sc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.id=n.string();continue;case 2:if(s!==18)break;o.type=n.string();continue;case 3:if(s!==26)break;o.function=xo.decode(n,n.uint32());continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return bo.fromPartial(e??{})},fromPartial(e){let t=sc();return t.id=e.id??"",t.type=e.type??"",t.function=e.function!==void 0&&e.function!==null?xo.fromPartial(e.function):void 0,t}};function ic(){return{name:"",arguments:""}}var xo={encode(e,t=new D){return e.name!==""&&t.uint32(10).string(e.name),e.arguments!==""&&t.uint32(18).string(e.arguments),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=ic();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.name=n.string();continue;case 2:if(s!==18)break;o.arguments=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return xo.fromPartial(e??{})},fromPartial(e){let t=ic();return t.name=e.name??"",t.arguments=e.arguments??"",t}};function ac(){return{value:"",mimeType:""}}var Eo={encode(e,t=new D){return e.value!==""&&t.uint32(10).string(e.value),e.mimeType!==""&&t.uint32(18).string(e.mimeType),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=ac();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.value=n.string();continue;case 2:if(s!==18)break;o.mimeType=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Eo.fromPartial(e??{})},fromPartial(e){let t=ac();return t.value=e.value??"",t.mimeType=e.mimeType??"",t}};function lc(){return{value:"",mimeType:void 0}}var _o={encode(e,t=new D){return e.value!==""&&t.uint32(10).string(e.value),e.mimeType!==void 0&&t.uint32(18).string(e.mimeType),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=lc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.value=n.string();continue;case 2:if(s!==18)break;o.mimeType=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return _o.fromPartial(e??{})},fromPartial(e){let t=lc();return t.value=e.value??"",t.mimeType=e.mimeType??void 0,t}};function cc(){return{data:void 0,url:void 0}}var Ie={encode(e,t=new D){return e.data!==void 0&&Eo.encode(e.data,t.uint32(10).fork()).join(),e.url!==void 0&&_o.encode(e.url,t.uint32(18).fork()).join(),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=cc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.data=Eo.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.url=_o.decode(n,n.uint32());continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Ie.fromPartial(e??{})},fromPartial(e){let t=cc();return t.data=e.data!==void 0&&e.data!==null?Eo.fromPartial(e.data):void 0,t.url=e.url!==void 0&&e.url!==null?_o.fromPartial(e.url):void 0,t}};function uc(){return{text:""}}var To={encode(e,t=new D){return e.text!==""&&t.uint32(10).string(e.text),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=uc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.text=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return To.fromPartial(e??{})},fromPartial(e){let t=uc();return t.text=e.text??"",t}};function dc(){return{source:void 0,metadata:void 0}}var So={encode(e,t=new D){return e.source!==void 0&&Ie.encode(e.source,t.uint32(10).fork()).join(),e.metadata!==void 0&&N.encode(N.wrap(e.metadata),t.uint32(18).fork()).join(),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=dc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.source=Ie.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return So.fromPartial(e??{})},fromPartial(e){let t=dc();return t.source=e.source!==void 0&&e.source!==null?Ie.fromPartial(e.source):void 0,t.metadata=e.metadata??void 0,t}};function pc(){return{source:void 0,metadata:void 0}}var wo={encode(e,t=new D){return e.source!==void 0&&Ie.encode(e.source,t.uint32(10).fork()).join(),e.metadata!==void 0&&N.encode(N.wrap(e.metadata),t.uint32(18).fork()).join(),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=pc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.source=Ie.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return wo.fromPartial(e??{})},fromPartial(e){let t=pc();return t.source=e.source!==void 0&&e.source!==null?Ie.fromPartial(e.source):void 0,t.metadata=e.metadata??void 0,t}};function fc(){return{source:void 0,metadata:void 0}}var ko={encode(e,t=new D){return e.source!==void 0&&Ie.encode(e.source,t.uint32(10).fork()).join(),e.metadata!==void 0&&N.encode(N.wrap(e.metadata),t.uint32(18).fork()).join(),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=fc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.source=Ie.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return ko.fromPartial(e??{})},fromPartial(e){let t=fc();return t.source=e.source!==void 0&&e.source!==null?Ie.fromPartial(e.source):void 0,t.metadata=e.metadata??void 0,t}};function hc(){return{source:void 0,metadata:void 0}}var Ao={encode(e,t=new D){return e.source!==void 0&&Ie.encode(e.source,t.uint32(10).fork()).join(),e.metadata!==void 0&&N.encode(N.wrap(e.metadata),t.uint32(18).fork()).join(),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=hc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.source=Ie.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Ao.fromPartial(e??{})},fromPartial(e){let t=hc();return t.source=e.source!==void 0&&e.source!==null?Ie.fromPartial(e.source):void 0,t.metadata=e.metadata??void 0,t}};function mc(){return{text:void 0,image:void 0,audio:void 0,video:void 0,document:void 0}}var Io={encode(e,t=new D){return e.text!==void 0&&To.encode(e.text,t.uint32(10).fork()).join(),e.image!==void 0&&So.encode(e.image,t.uint32(18).fork()).join(),e.audio!==void 0&&wo.encode(e.audio,t.uint32(26).fork()).join(),e.video!==void 0&&ko.encode(e.video,t.uint32(34).fork()).join(),e.document!==void 0&&Ao.encode(e.document,t.uint32(42).fork()).join(),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=mc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.text=To.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.image=So.decode(n,n.uint32());continue;case 3:if(s!==26)break;o.audio=wo.decode(n,n.uint32());continue;case 4:if(s!==34)break;o.video=ko.decode(n,n.uint32());continue;case 5:if(s!==42)break;o.document=Ao.decode(n,n.uint32());continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Io.fromPartial(e??{})},fromPartial(e){let t=mc();return t.text=e.text!==void 0&&e.text!==null?To.fromPartial(e.text):void 0,t.image=e.image!==void 0&&e.image!==null?So.fromPartial(e.image):void 0,t.audio=e.audio!==void 0&&e.audio!==null?wo.fromPartial(e.audio):void 0,t.video=e.video!==void 0&&e.video!==null?ko.fromPartial(e.video):void 0,t.document=e.document!==void 0&&e.document!==null?Ao.fromPartial(e.document):void 0,t}};function gc(){return{id:"",role:"",content:void 0,name:void 0,toolCalls:[],toolCallId:void 0,error:void 0,contentParts:[]}}var Co={encode(e,t=new D){e.id!==""&&t.uint32(10).string(e.id),e.role!==""&&t.uint32(18).string(e.role),e.content!==void 0&&t.uint32(26).string(e.content),e.name!==void 0&&t.uint32(34).string(e.name);for(let n of e.toolCalls)bo.encode(n,t.uint32(42).fork()).join();e.toolCallId!==void 0&&t.uint32(50).string(e.toolCallId),e.error!==void 0&&t.uint32(58).string(e.error);for(let n of e.contentParts)Io.encode(n,t.uint32(66).fork()).join();return t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=gc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.id=n.string();continue;case 2:if(s!==18)break;o.role=n.string();continue;case 3:if(s!==26)break;o.content=n.string();continue;case 4:if(s!==34)break;o.name=n.string();continue;case 5:if(s!==42)break;o.toolCalls.push(bo.decode(n,n.uint32()));continue;case 6:if(s!==50)break;o.toolCallId=n.string();continue;case 7:if(s!==58)break;o.error=n.string();continue;case 8:if(s!==66)break;o.contentParts.push(Io.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Co.fromPartial(e??{})},fromPartial(e){let t=gc();return t.id=e.id??"",t.role=e.role??"",t.content=e.content??void 0,t.name=e.name??void 0,t.toolCalls=e.toolCalls?.map(n=>bo.fromPartial(n))||[],t.toolCallId=e.toolCallId??void 0,t.error=e.error??void 0,t.contentParts=e.contentParts?.map(n=>Io.fromPartial(n))||[],t}};function vc(){return{id:"",reason:"",message:void 0,toolCallId:void 0,responseSchema:void 0,expiresAt:void 0,metadata:void 0}}var No={encode(e,t=new D){return e.id!==""&&t.uint32(10).string(e.id),e.reason!==""&&t.uint32(18).string(e.reason),e.message!==void 0&&t.uint32(26).string(e.message),e.toolCallId!==void 0&&t.uint32(34).string(e.toolCallId),e.responseSchema!==void 0&&N.encode(N.wrap(e.responseSchema),t.uint32(42).fork()).join(),e.expiresAt!==void 0&&t.uint32(50).string(e.expiresAt),e.metadata!==void 0&&N.encode(N.wrap(e.metadata),t.uint32(58).fork()).join(),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=vc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.id=n.string();continue;case 2:if(s!==18)break;o.reason=n.string();continue;case 3:if(s!==26)break;o.message=n.string();continue;case 4:if(s!==34)break;o.toolCallId=n.string();continue;case 5:if(s!==42)break;o.responseSchema=N.unwrap(N.decode(n,n.uint32()));continue;case 6:if(s!==50)break;o.expiresAt=n.string();continue;case 7:if(s!==58)break;o.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return No.fromPartial(e??{})},fromPartial(e){let t=vc();return t.id=e.id??"",t.reason=e.reason??"",t.message=e.message??void 0,t.toolCallId=e.toolCallId??void 0,t.responseSchema=e.responseSchema??void 0,t.expiresAt=e.expiresAt??void 0,t.metadata=e.metadata??void 0,t}},nm=(function(e){return e[e.TEXT_MESSAGE_START=0]="TEXT_MESSAGE_START",e[e.TEXT_MESSAGE_CONTENT=1]="TEXT_MESSAGE_CONTENT",e[e.TEXT_MESSAGE_END=2]="TEXT_MESSAGE_END",e[e.TOOL_CALL_START=3]="TOOL_CALL_START",e[e.TOOL_CALL_ARGS=4]="TOOL_CALL_ARGS",e[e.TOOL_CALL_END=5]="TOOL_CALL_END",e[e.STATE_SNAPSHOT=6]="STATE_SNAPSHOT",e[e.STATE_DELTA=7]="STATE_DELTA",e[e.MESSAGES_SNAPSHOT=8]="MESSAGES_SNAPSHOT",e[e.RAW=9]="RAW",e[e.CUSTOM=10]="CUSTOM",e[e.RUN_STARTED=11]="RUN_STARTED",e[e.RUN_FINISHED=12]="RUN_FINISHED",e[e.RUN_ERROR=13]="RUN_ERROR",e[e.STEP_STARTED=14]="STEP_STARTED",e[e.STEP_FINISHED=15]="STEP_FINISHED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED",e})({});function yc(){return{type:0,timestamp:void 0,rawEvent:void 0}}var R={encode(e,t=new D){return e.type!==0&&t.uint32(8).int32(e.type),e.timestamp!==void 0&&t.uint32(16).int64(e.timestamp),e.rawEvent!==void 0&&N.encode(N.wrap(e.rawEvent),t.uint32(26).fork()).join(),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=yc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==8)break;o.type=n.int32();continue;case 2:if(s!==16)break;o.timestamp=rm(n.int64());continue;case 3:if(s!==26)break;o.rawEvent=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return R.fromPartial(e??{})},fromPartial(e){let t=yc();return t.type=e.type??0,t.timestamp=e.timestamp??void 0,t.rawEvent=e.rawEvent??void 0,t}};function bc(){return{baseEvent:void 0,messageId:"",role:void 0,name:void 0}}var Ro={encode(e,t=new D){return e.baseEvent!==void 0&&R.encode(e.baseEvent,t.uint32(10).fork()).join(),e.messageId!==""&&t.uint32(18).string(e.messageId),e.role!==void 0&&t.uint32(26).string(e.role),e.name!==void 0&&t.uint32(34).string(e.name),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=bc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.messageId=n.string();continue;case 3:if(s!==26)break;o.role=n.string();continue;case 4:if(s!==34)break;o.name=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Ro.fromPartial(e??{})},fromPartial(e){let t=bc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?R.fromPartial(e.baseEvent):void 0,t.messageId=e.messageId??"",t.role=e.role??void 0,t.name=e.name??void 0,t}};function xc(){return{baseEvent:void 0,messageId:"",delta:""}}var Oo={encode(e,t=new D){return e.baseEvent!==void 0&&R.encode(e.baseEvent,t.uint32(10).fork()).join(),e.messageId!==""&&t.uint32(18).string(e.messageId),e.delta!==""&&t.uint32(26).string(e.delta),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=xc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.messageId=n.string();continue;case 3:if(s!==26)break;o.delta=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Oo.fromPartial(e??{})},fromPartial(e){let t=xc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?R.fromPartial(e.baseEvent):void 0,t.messageId=e.messageId??"",t.delta=e.delta??"",t}};function Ec(){return{baseEvent:void 0,messageId:""}}var Mo={encode(e,t=new D){return e.baseEvent!==void 0&&R.encode(e.baseEvent,t.uint32(10).fork()).join(),e.messageId!==""&&t.uint32(18).string(e.messageId),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=Ec();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.messageId=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Mo.fromPartial(e??{})},fromPartial(e){let t=Ec();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?R.fromPartial(e.baseEvent):void 0,t.messageId=e.messageId??"",t}};function _c(){return{baseEvent:void 0,toolCallId:"",toolCallName:"",parentMessageId:void 0}}var Lo={encode(e,t=new D){return e.baseEvent!==void 0&&R.encode(e.baseEvent,t.uint32(10).fork()).join(),e.toolCallId!==""&&t.uint32(18).string(e.toolCallId),e.toolCallName!==""&&t.uint32(26).string(e.toolCallName),e.parentMessageId!==void 0&&t.uint32(34).string(e.parentMessageId),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=_c();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.toolCallId=n.string();continue;case 3:if(s!==26)break;o.toolCallName=n.string();continue;case 4:if(s!==34)break;o.parentMessageId=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Lo.fromPartial(e??{})},fromPartial(e){let t=_c();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?R.fromPartial(e.baseEvent):void 0,t.toolCallId=e.toolCallId??"",t.toolCallName=e.toolCallName??"",t.parentMessageId=e.parentMessageId??void 0,t}};function Tc(){return{baseEvent:void 0,toolCallId:"",delta:""}}var Po={encode(e,t=new D){return e.baseEvent!==void 0&&R.encode(e.baseEvent,t.uint32(10).fork()).join(),e.toolCallId!==""&&t.uint32(18).string(e.toolCallId),e.delta!==""&&t.uint32(26).string(e.delta),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=Tc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.toolCallId=n.string();continue;case 3:if(s!==26)break;o.delta=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Po.fromPartial(e??{})},fromPartial(e){let t=Tc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?R.fromPartial(e.baseEvent):void 0,t.toolCallId=e.toolCallId??"",t.delta=e.delta??"",t}};function Sc(){return{baseEvent:void 0,toolCallId:""}}var Do={encode(e,t=new D){return e.baseEvent!==void 0&&R.encode(e.baseEvent,t.uint32(10).fork()).join(),e.toolCallId!==""&&t.uint32(18).string(e.toolCallId),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=Sc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.toolCallId=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Do.fromPartial(e??{})},fromPartial(e){let t=Sc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?R.fromPartial(e.baseEvent):void 0,t.toolCallId=e.toolCallId??"",t}};function wc(){return{baseEvent:void 0,snapshot:void 0}}var Uo={encode(e,t=new D){return e.baseEvent!==void 0&&R.encode(e.baseEvent,t.uint32(10).fork()).join(),e.snapshot!==void 0&&N.encode(N.wrap(e.snapshot),t.uint32(18).fork()).join(),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=wc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.snapshot=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Uo.fromPartial(e??{})},fromPartial(e){let t=wc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?R.fromPartial(e.baseEvent):void 0,t.snapshot=e.snapshot??void 0,t}};function kc(){return{baseEvent:void 0,delta:[]}}var Go={encode(e,t=new D){e.baseEvent!==void 0&&R.encode(e.baseEvent,t.uint32(10).fork()).join();for(let n of e.delta)yo.encode(n,t.uint32(18).fork()).join();return t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=kc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.delta.push(yo.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Go.fromPartial(e??{})},fromPartial(e){let t=kc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?R.fromPartial(e.baseEvent):void 0,t.delta=e.delta?.map(n=>yo.fromPartial(n))||[],t}};function Ac(){return{baseEvent:void 0,messages:[]}}var Fo={encode(e,t=new D){e.baseEvent!==void 0&&R.encode(e.baseEvent,t.uint32(10).fork()).join();for(let n of e.messages)Co.encode(n,t.uint32(18).fork()).join();return t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=Ac();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.messages.push(Co.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Fo.fromPartial(e??{})},fromPartial(e){let t=Ac();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?R.fromPartial(e.baseEvent):void 0,t.messages=e.messages?.map(n=>Co.fromPartial(n))||[],t}};function Ic(){return{baseEvent:void 0,event:void 0,source:void 0}}var Ho={encode(e,t=new D){return e.baseEvent!==void 0&&R.encode(e.baseEvent,t.uint32(10).fork()).join(),e.event!==void 0&&N.encode(N.wrap(e.event),t.uint32(18).fork()).join(),e.source!==void 0&&t.uint32(26).string(e.source),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=Ic();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.event=N.unwrap(N.decode(n,n.uint32()));continue;case 3:if(s!==26)break;o.source=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Ho.fromPartial(e??{})},fromPartial(e){let t=Ic();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?R.fromPartial(e.baseEvent):void 0,t.event=e.event??void 0,t.source=e.source??void 0,t}};function Cc(){return{baseEvent:void 0,name:"",value:void 0}}var $o={encode(e,t=new D){return e.baseEvent!==void 0&&R.encode(e.baseEvent,t.uint32(10).fork()).join(),e.name!==""&&t.uint32(18).string(e.name),e.value!==void 0&&N.encode(N.wrap(e.value),t.uint32(26).fork()).join(),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=Cc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.name=n.string();continue;case 3:if(s!==26)break;o.value=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return $o.fromPartial(e??{})},fromPartial(e){let t=Cc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?R.fromPartial(e.baseEvent):void 0,t.name=e.name??"",t.value=e.value??void 0,t}};function Nc(){return{baseEvent:void 0,threadId:"",runId:""}}var zo={encode(e,t=new D){return e.baseEvent!==void 0&&R.encode(e.baseEvent,t.uint32(10).fork()).join(),e.threadId!==""&&t.uint32(18).string(e.threadId),e.runId!==""&&t.uint32(26).string(e.runId),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=Nc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.threadId=n.string();continue;case 3:if(s!==26)break;o.runId=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return zo.fromPartial(e??{})},fromPartial(e){let t=Nc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?R.fromPartial(e.baseEvent):void 0,t.threadId=e.threadId??"",t.runId=e.runId??"",t}};function Rc(){return{baseEvent:void 0,threadId:"",runId:"",result:void 0,outcome:"",interrupts:[]}}var Bo={encode(e,t=new D){e.baseEvent!==void 0&&R.encode(e.baseEvent,t.uint32(10).fork()).join(),e.threadId!==""&&t.uint32(18).string(e.threadId),e.runId!==""&&t.uint32(26).string(e.runId),e.result!==void 0&&N.encode(N.wrap(e.result),t.uint32(34).fork()).join(),e.outcome!==""&&t.uint32(42).string(e.outcome);for(let n of e.interrupts)No.encode(n,t.uint32(50).fork()).join();return t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=Rc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.threadId=n.string();continue;case 3:if(s!==26)break;o.runId=n.string();continue;case 4:if(s!==34)break;o.result=N.unwrap(N.decode(n,n.uint32()));continue;case 5:if(s!==42)break;o.outcome=n.string();continue;case 6:if(s!==50)break;o.interrupts.push(No.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Bo.fromPartial(e??{})},fromPartial(e){let t=Rc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?R.fromPartial(e.baseEvent):void 0,t.threadId=e.threadId??"",t.runId=e.runId??"",t.result=e.result??void 0,t.outcome=e.outcome??"",t.interrupts=e.interrupts?.map(n=>No.fromPartial(n))||[],t}};function Oc(){return{baseEvent:void 0,code:void 0,message:""}}var Vo={encode(e,t=new D){return e.baseEvent!==void 0&&R.encode(e.baseEvent,t.uint32(10).fork()).join(),e.code!==void 0&&t.uint32(18).string(e.code),e.message!==""&&t.uint32(26).string(e.message),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=Oc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.code=n.string();continue;case 3:if(s!==26)break;o.message=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Vo.fromPartial(e??{})},fromPartial(e){let t=Oc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?R.fromPartial(e.baseEvent):void 0,t.code=e.code??void 0,t.message=e.message??"",t}};function Mc(){return{baseEvent:void 0,stepName:""}}var jo={encode(e,t=new D){return e.baseEvent!==void 0&&R.encode(e.baseEvent,t.uint32(10).fork()).join(),e.stepName!==""&&t.uint32(18).string(e.stepName),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=Mc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.stepName=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return jo.fromPartial(e??{})},fromPartial(e){let t=Mc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?R.fromPartial(e.baseEvent):void 0,t.stepName=e.stepName??"",t}};function Lc(){return{baseEvent:void 0,stepName:""}}var Wo={encode(e,t=new D){return e.baseEvent!==void 0&&R.encode(e.baseEvent,t.uint32(10).fork()).join(),e.stepName!==""&&t.uint32(18).string(e.stepName),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=Lc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.stepName=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Wo.fromPartial(e??{})},fromPartial(e){let t=Lc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?R.fromPartial(e.baseEvent):void 0,t.stepName=e.stepName??"",t}};function Pc(){return{baseEvent:void 0,messageId:void 0,role:void 0,delta:void 0,name:void 0}}var Xo={encode(e,t=new D){return e.baseEvent!==void 0&&R.encode(e.baseEvent,t.uint32(10).fork()).join(),e.messageId!==void 0&&t.uint32(18).string(e.messageId),e.role!==void 0&&t.uint32(26).string(e.role),e.delta!==void 0&&t.uint32(34).string(e.delta),e.name!==void 0&&t.uint32(42).string(e.name),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=Pc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.messageId=n.string();continue;case 3:if(s!==26)break;o.role=n.string();continue;case 4:if(s!==34)break;o.delta=n.string();continue;case 5:if(s!==42)break;o.name=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Xo.fromPartial(e??{})},fromPartial(e){let t=Pc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?R.fromPartial(e.baseEvent):void 0,t.messageId=e.messageId??void 0,t.role=e.role??void 0,t.delta=e.delta??void 0,t.name=e.name??void 0,t}};function Dc(){return{baseEvent:void 0,toolCallId:void 0,toolCallName:void 0,parentMessageId:void 0,delta:void 0}}var Zo={encode(e,t=new D){return e.baseEvent!==void 0&&R.encode(e.baseEvent,t.uint32(10).fork()).join(),e.toolCallId!==void 0&&t.uint32(18).string(e.toolCallId),e.toolCallName!==void 0&&t.uint32(26).string(e.toolCallName),e.parentMessageId!==void 0&&t.uint32(34).string(e.parentMessageId),e.delta!==void 0&&t.uint32(42).string(e.delta),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=Dc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.toolCallId=n.string();continue;case 3:if(s!==26)break;o.toolCallName=n.string();continue;case 4:if(s!==34)break;o.parentMessageId=n.string();continue;case 5:if(s!==42)break;o.delta=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Zo.fromPartial(e??{})},fromPartial(e){let t=Dc();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?R.fromPartial(e.baseEvent):void 0,t.toolCallId=e.toolCallId??void 0,t.toolCallName=e.toolCallName??void 0,t.parentMessageId=e.parentMessageId??void 0,t.delta=e.delta??void 0,t}};function Uc(){return{textMessageStart:void 0,textMessageContent:void 0,textMessageEnd:void 0,toolCallStart:void 0,toolCallArgs:void 0,toolCallEnd:void 0,stateSnapshot:void 0,stateDelta:void 0,messagesSnapshot:void 0,raw:void 0,custom:void 0,runStarted:void 0,runFinished:void 0,runError:void 0,stepStarted:void 0,stepFinished:void 0,textMessageChunk:void 0,toolCallChunk:void 0}}var Gc={encode(e,t=new D){return e.textMessageStart!==void 0&&Ro.encode(e.textMessageStart,t.uint32(10).fork()).join(),e.textMessageContent!==void 0&&Oo.encode(e.textMessageContent,t.uint32(18).fork()).join(),e.textMessageEnd!==void 0&&Mo.encode(e.textMessageEnd,t.uint32(26).fork()).join(),e.toolCallStart!==void 0&&Lo.encode(e.toolCallStart,t.uint32(34).fork()).join(),e.toolCallArgs!==void 0&&Po.encode(e.toolCallArgs,t.uint32(42).fork()).join(),e.toolCallEnd!==void 0&&Do.encode(e.toolCallEnd,t.uint32(50).fork()).join(),e.stateSnapshot!==void 0&&Uo.encode(e.stateSnapshot,t.uint32(58).fork()).join(),e.stateDelta!==void 0&&Go.encode(e.stateDelta,t.uint32(66).fork()).join(),e.messagesSnapshot!==void 0&&Fo.encode(e.messagesSnapshot,t.uint32(74).fork()).join(),e.raw!==void 0&&Ho.encode(e.raw,t.uint32(82).fork()).join(),e.custom!==void 0&&$o.encode(e.custom,t.uint32(90).fork()).join(),e.runStarted!==void 0&&zo.encode(e.runStarted,t.uint32(98).fork()).join(),e.runFinished!==void 0&&Bo.encode(e.runFinished,t.uint32(106).fork()).join(),e.runError!==void 0&&Vo.encode(e.runError,t.uint32(114).fork()).join(),e.stepStarted!==void 0&&jo.encode(e.stepStarted,t.uint32(122).fork()).join(),e.stepFinished!==void 0&&Wo.encode(e.stepFinished,t.uint32(130).fork()).join(),e.textMessageChunk!==void 0&&Xo.encode(e.textMessageChunk,t.uint32(138).fork()).join(),e.toolCallChunk!==void 0&&Zo.encode(e.toolCallChunk,t.uint32(146).fork()).join(),t},decode(e,t){let n=e instanceof T?e:new T(e),r=t===void 0?n.len:n.pos+t,o=Uc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.textMessageStart=Ro.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.textMessageContent=Oo.decode(n,n.uint32());continue;case 3:if(s!==26)break;o.textMessageEnd=Mo.decode(n,n.uint32());continue;case 4:if(s!==34)break;o.toolCallStart=Lo.decode(n,n.uint32());continue;case 5:if(s!==42)break;o.toolCallArgs=Po.decode(n,n.uint32());continue;case 6:if(s!==50)break;o.toolCallEnd=Do.decode(n,n.uint32());continue;case 7:if(s!==58)break;o.stateSnapshot=Uo.decode(n,n.uint32());continue;case 8:if(s!==66)break;o.stateDelta=Go.decode(n,n.uint32());continue;case 9:if(s!==74)break;o.messagesSnapshot=Fo.decode(n,n.uint32());continue;case 10:if(s!==82)break;o.raw=Ho.decode(n,n.uint32());continue;case 11:if(s!==90)break;o.custom=$o.decode(n,n.uint32());continue;case 12:if(s!==98)break;o.runStarted=zo.decode(n,n.uint32());continue;case 13:if(s!==106)break;o.runFinished=Bo.decode(n,n.uint32());continue;case 14:if(s!==114)break;o.runError=Vo.decode(n,n.uint32());continue;case 15:if(s!==122)break;o.stepStarted=jo.decode(n,n.uint32());continue;case 16:if(s!==130)break;o.stepFinished=Wo.decode(n,n.uint32());continue;case 17:if(s!==138)break;o.textMessageChunk=Xo.decode(n,n.uint32());continue;case 18:if(s!==146)break;o.toolCallChunk=Zo.decode(n,n.uint32());continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(e){return Gc.fromPartial(e??{})},fromPartial(e){let t=Uc();return t.textMessageStart=e.textMessageStart!==void 0&&e.textMessageStart!==null?Ro.fromPartial(e.textMessageStart):void 0,t.textMessageContent=e.textMessageContent!==void 0&&e.textMessageContent!==null?Oo.fromPartial(e.textMessageContent):void 0,t.textMessageEnd=e.textMessageEnd!==void 0&&e.textMessageEnd!==null?Mo.fromPartial(e.textMessageEnd):void 0,t.toolCallStart=e.toolCallStart!==void 0&&e.toolCallStart!==null?Lo.fromPartial(e.toolCallStart):void 0,t.toolCallArgs=e.toolCallArgs!==void 0&&e.toolCallArgs!==null?Po.fromPartial(e.toolCallArgs):void 0,t.toolCallEnd=e.toolCallEnd!==void 0&&e.toolCallEnd!==null?Do.fromPartial(e.toolCallEnd):void 0,t.stateSnapshot=e.stateSnapshot!==void 0&&e.stateSnapshot!==null?Uo.fromPartial(e.stateSnapshot):void 0,t.stateDelta=e.stateDelta!==void 0&&e.stateDelta!==null?Go.fromPartial(e.stateDelta):void 0,t.messagesSnapshot=e.messagesSnapshot!==void 0&&e.messagesSnapshot!==null?Fo.fromPartial(e.messagesSnapshot):void 0,t.raw=e.raw!==void 0&&e.raw!==null?Ho.fromPartial(e.raw):void 0,t.custom=e.custom!==void 0&&e.custom!==null?$o.fromPartial(e.custom):void 0,t.runStarted=e.runStarted!==void 0&&e.runStarted!==null?zo.fromPartial(e.runStarted):void 0,t.runFinished=e.runFinished!==void 0&&e.runFinished!==null?Bo.fromPartial(e.runFinished):void 0,t.runError=e.runError!==void 0&&e.runError!==null?Vo.fromPartial(e.runError):void 0,t.stepStarted=e.stepStarted!==void 0&&e.stepStarted!==null?jo.fromPartial(e.stepStarted):void 0,t.stepFinished=e.stepFinished!==void 0&&e.stepFinished!==null?Wo.fromPartial(e.stepFinished):void 0,t.textMessageChunk=e.textMessageChunk!==void 0&&e.textMessageChunk!==null?Xo.fromPartial(e.textMessageChunk):void 0,t.toolCallChunk=e.toolCallChunk!==void 0&&e.toolCallChunk!==null?Zo.fromPartial(e.toolCallChunk):void 0,t}};function rm(e){let t=globalThis.Number(e.toString());if(t>globalThis.Number.MAX_SAFE_INTEGER)throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");if(t<globalThis.Number.MIN_SAFE_INTEGER)throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");return t}var vo=e=>{if(!(!e||typeof e!="object")){if(e.data)return{type:"data",value:e.data.value,mimeType:e.data.mimeType};if(e.url)return{type:"url",value:e.url.value,mimeType:e.url.mimeType}}},om=e=>{if(!(!e||typeof e!="object")){if(e.text)return{type:"text",text:e.text.text};if(e.image)return{type:"image",source:vo(e.image.source),metadata:e.image.metadata};if(e.audio)return{type:"audio",source:vo(e.audio.source),metadata:e.audio.metadata};if(e.video)return{type:"video",source:vo(e.video.source),metadata:e.video.metadata};if(e.document)return{type:"document",source:vo(e.document.source),metadata:e.document.metadata}}};function Fc(e){let t=Gc.decode(e),n=Object.values(t).find(r=>r!==void 0);if(!n)throw new Error("Invalid event");if(n.type=nm[n.baseEvent.type],n.timestamp=n.baseEvent.timestamp,n.rawEvent=n.baseEvent.rawEvent,delete n.baseEvent,n.type===v.MESSAGES_SNAPSHOT)for(let r of n.messages){let o=r;if(o.role==="user"&&Array.isArray(o.contentParts)){let s=o.contentParts.map(i=>om(i)).filter(i=>i!==void 0);s.length>0&&(o.content=s)}Array.isArray(o.contentParts)&&o.contentParts.length===0&&(o.contentParts=void 0),o.toolCalls?.length===0&&(o.toolCalls=void 0)}if(n.type===v.RUN_FINISHED){let r=n,o=typeof r.outcome=="string"&&r.outcome!==""?r.outcome:void 0,s=Array.isArray(r.interrupts)?r.interrupts:[];delete r.interrupts,o==="interrupt"?r.outcome={type:"interrupt",interrupts:s}:o==="success"?r.outcome={type:"success"}:delete r.outcome}if(n.type===v.STATE_DELTA)for(let r of n.delta)r.op=tm[r.op].toLowerCase(),Object.keys(r).forEach(o=>{r[o]===void 0&&delete r[o]});return Object.keys(n).forEach(r=>{n[r]===void 0&&delete n[r]}),Mr.parse(n)}var Ci="application/vnd.ag-ui.event+proto";var im=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,Ni=e=>{if(typeof e!="string")throw new TypeError("Invalid argument expected string");let t=e.match(im);if(!t)throw new Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},Hc=e=>e==="*"||e==="x"||e==="X",$c=e=>{let t=parseInt(e,10);return isNaN(t)?e:t},am=(e,t)=>typeof e!=typeof t?[String(e),String(t)]:[e,t],lm=(e,t)=>{if(Hc(e)||Hc(t))return 0;let[n,r]=am($c(e),$c(t));return n>r?1:n<r?-1:0},Ri=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n++){let r=lm(e[n]||"0",t[n]||"0");if(r!==0)return r}return 0};var Jn=(e,t)=>{let n=Ni(e),r=Ni(t),o=n.pop(),s=r.pop(),i=Ri(n,r);return i!==0?i:o&&s?Ri(o.split("."),s.split(".")):o||s?o?-1:1:0};var B=e=>{if(typeof structuredClone=="function")return structuredClone(e);try{return JSON.parse(JSON.stringify(e))}catch{return Array.isArray(e)?[...e]:{...e}}};function ze(){return ht()}function Li(e){if(Object.freeze(e),typeof e=="object"&&e)for(let t of Object.values(e))typeof t=="object"&&t&&!Object.isFrozen(t)&&Li(t);return e}async function W(e,t,n,r){let o=typeof process<"u"&&process.env!==void 0,s=o&&!!process.env.VITEST_WORKER_ID,i=o&&!!process.env.VITEST_WORKER_ID,a=B(t),u=B(n),c=a,p=u,m;for(let x of e)try{i&&(Li(c),Li(p));let f=await r(x,c,p);if(f===void 0)continue;if(f.messages!==void 0&&f.messages!==c&&(c=B(f.messages)),f.state!==void 0&&f.state!==p&&(p=B(f.state)),m=f.stopPropagation,m===!0)break}catch(f){if(i&&f instanceof TypeError){if(s)throw f;console.error("AG-UI: Subscriber attempted to mutate frozen inputs in-place. Return mutations via AgentStateMutation instead of mutating directly.",f)}else s||console.error("Subscriber error:",f);continue}return{...c===a?{}:{messages:i&&Object.isFrozen(c)?B(c):c},...p===u?{}:{state:i&&Object.isFrozen(p)?B(p):p},...m===void 0?{}:{stopPropagation:m}}}function Ko(e){if(!e)return{enabled:!1,events:!1,lifecycle:!1,verbose:!1};if(e===!0)return{enabled:!0,events:!0,lifecycle:!0,verbose:!0};let t=e.events??!0,n=e.lifecycle??!0,r=e.verbose??!1;return{enabled:t||n,events:t,lifecycle:n,verbose:r}}function Qn(e){if(e instanceof Pi)return e;if(e===!0)return new Pi(Ko(!0))}var Pi=class{constructor(e){this.config=e}event(e,t,n,r){this.config.events&&(this.config.verbose?console.debug(`[${e}] ${t}`,typeof n=="string"?n:JSON.stringify(n)):console.debug(`[${e}] ${t}`,r??n))}lifecycle(e,t,n){this.config.lifecycle&&(n?console.debug(`[${e}] ${t}`,n):console.debug(`[${e}] ${t}`))}get eventsEnabled(){return this.config.events}get lifecycleEnabled(){return this.config.lifecycle}get enabled(){return this.config.enabled}};function Oi(e){return e.enabled?new Pi(e):void 0}function cm(e,t,n){if(t){let o=e.find(i=>i.id===t);if(o?.role==="assistant")return o;o&&console.warn(`TOOL_CALL_START: parentMessageId '${t}' matches a '${o.role}' message, not assistant \u2014 falling back to toolCallId`);let s={id:o?n:t,role:"assistant",toolCalls:[]};return e.push(s),s}let r={id:n,role:"assistant",toolCalls:[]};return e.push(r),r}var Xc=(e,t,n,r,o)=>{let s=Qn(o),i=B(n.messages),a=B(e.state),u={},c=m=>{m.messages!==void 0&&(i=m.messages,u.messages=m.messages),m.state!==void 0&&(a=m.state,u.state=m.state)},p=()=>{let m=B(u);return u={},m.messages!==void 0||m.state!==void 0?te(m):Yr};return t.pipe(po(async m=>{let x=await W(r,i,a,(f,h,g)=>f.onEvent?.({event:m,agent:n,input:e,messages:h,state:g}));if(c(x),x.stopPropagation===!0?s?.event("APPLY","Event dropped:",m,{type:m.type,reason:"stopPropagation by subscriber"}):s?.event("APPLY","Event applied:",m,{type:m.type,subscribers:r.length}),x.stopPropagation===!0)return p();switch(m.type){case v.TEXT_MESSAGE_START:{let f=await W(r,i,a,(h,g,_)=>h.onTextMessageStartEvent?.({event:m,messages:g,state:_,agent:n,input:e}));if(c(f),f.stopPropagation!==!0){let{messageId:h,role:g="assistant",name:_}=m;if(!i.find(S=>S.id===h)){let S={id:h,role:g,content:"",..._!==void 0&&{name:_}};i.push(S),c({messages:i})}}return p()}case v.TEXT_MESSAGE_CONTENT:{let{messageId:f,delta:h}=m,g=i.find(S=>S.id===f);if(!g)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${f}'`),p();let _=await W(r,i,a,(S,b,F)=>S.onTextMessageContentEvent?.({event:m,messages:b,state:F,agent:n,input:e,textMessageBuffer:typeof g.content=="string"?g.content:""}));return c(_),_.stopPropagation!==!0&&(g.content=`${typeof g.content=="string"?g.content:""}${h}`,c({messages:i})),p()}case v.TEXT_MESSAGE_END:{let{messageId:f}=m,h=i.find(g=>g.id===f);return h?(c(await W(r,i,a,(g,_,S)=>g.onTextMessageEndEvent?.({event:m,messages:_,state:S,agent:n,input:e,textMessageBuffer:typeof h.content=="string"?h.content:""}))),await Promise.all(r.map(g=>{g.onNewMessage?.({message:h,messages:i,state:a,agent:n,input:e})})),p()):(console.warn(`TEXT_MESSAGE_END: No message found with ID '${f}'`),p())}case v.TOOL_CALL_START:{let f=await W(r,i,a,(h,g,_)=>h.onToolCallStartEvent?.({event:m,messages:g,state:_,agent:n,input:e}));if(c(f),f.stopPropagation!==!0){let{toolCallId:h,toolCallName:g,parentMessageId:_}=m,S=cm(i,_,h);S.toolCalls??=[],S.toolCalls.push({id:h,type:"function",function:{name:g,arguments:""}}),c({messages:i})}return p()}case v.TOOL_CALL_ARGS:{let{toolCallId:f,delta:h}=m,g=i.find(b=>b.toolCalls?.some(F=>F.id===f));if(!g)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${f}'`),p();let _=g.toolCalls?.find(b=>b.id===f);if(!_)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${f}'`),p();let S=await W(r,i,a,(b,F,X)=>{let ae=_.function.arguments,ee=_.function.name,ut={};try{ut=ho(ae)}catch{}return b.onToolCallArgsEvent?.({event:m,messages:F,state:X,agent:n,input:e,toolCallBuffer:ae,toolCallName:ee,partialToolCallArgs:ut})});return c(S),S.stopPropagation!==!0&&(_.function.arguments+=h,c({messages:i})),p()}case v.TOOL_CALL_END:{let{toolCallId:f}=m,h=i.find(_=>_.toolCalls?.some(S=>S.id===f));if(!h)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${f}'`),p();let g=h.toolCalls?.find(_=>_.id===f);return g?(c(await W(r,i,a,(_,S,b)=>{let F=g.function.arguments,X=g.function.name,ae={};try{ae=JSON.parse(F)}catch{}return _.onToolCallEndEvent?.({event:m,messages:S,state:b,agent:n,input:e,toolCallName:X,toolCallArgs:ae})})),await Promise.all(r.map(_=>{_.onNewToolCall?.({toolCall:g,messages:i,state:a,agent:n,input:e})})),p()):(console.warn(`TOOL_CALL_END: No tool call found with ID '${f}'`),p())}case v.TOOL_CALL_RESULT:{let f=await W(r,i,a,(h,g,_)=>h.onToolCallResultEvent?.({event:m,messages:g,state:_,agent:n,input:e}));if(c(f),f.stopPropagation!==!0){let{messageId:h,toolCallId:g,content:_,role:S}=m,b={id:h,toolCallId:g,role:S||"tool",content:_};i.push(b),await Promise.all(r.map(F=>{F.onNewMessage?.({message:b,messages:i,state:a,agent:n,input:e})})),c({messages:i})}return p()}case v.STATE_SNAPSHOT:{let f=await W(r,i,a,(h,g,_)=>h.onStateSnapshotEvent?.({event:m,messages:g,state:_,agent:n,input:e}));if(c(f),f.stopPropagation!==!0){let{snapshot:h}=m;a=h,c({state:a})}return p()}case v.STATE_DELTA:{let f=await W(r,i,a,(h,g,_)=>h.onStateDeltaEvent?.({event:m,messages:g,state:_,agent:n,input:e}));if(c(f),f.stopPropagation!==!0){let{delta:h}=m;try{a=$r.applyPatch(a,h,!0,!1).newDocument,c({state:a})}catch(g){let _=g instanceof Error?g.message:String(g);console.warn(`Failed to apply state patch:
897
+ `):"",this.name="UnsubscriptionError",this.errors=n}});function Xn(t,e){if(t){var n=t.indexOf(e);0<=n&&t.splice(n,1)}}var En=(function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,n,r,o,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var a=ct(i),u=a.next();!u.done;u=a.next()){var l=u.value;l.remove(this)}}catch(g){e={error:g}}finally{try{u&&!u.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}else i.remove(this);var p=this.initialTeardown;if(G(p))try{p()}catch(g){s=g instanceof Wr?g.errors:[g]}var m=this._finalizers;if(m){this._finalizers=null;try{for(var x=ct(m),f=x.next();!f.done;f=x.next()){var h=f.value;try{Ml(h)}catch(g){s=s??[],g instanceof Wr?s=bn(bn([],yn(s)),yn(g.errors)):s.push(g)}}}catch(g){r={error:g}}finally{try{f&&!f.done&&(o=x.return)&&o.call(x)}finally{if(r)throw r.error}}}if(s)throw new Wr(s)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)Ml(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(e)}},t.prototype._hasParent=function(e){var n=this._parentage;return n===e||Array.isArray(n)&&n.includes(e)},t.prototype._addParent=function(e){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(e),n):n?[n,e]:e},t.prototype._removeParent=function(e){var n=this._parentage;n===e?this._parentage=null:Array.isArray(n)&&Xn(n,e)},t.prototype.remove=function(e){var n=this._finalizers;n&&Xn(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})();var di=En.EMPTY;function Xr(t){return t instanceof En||t&&"closed"in t&&G(t.remove)&&G(t.add)&&G(t.unsubscribe)}function Ml(t){G(t)?t():t.unsubscribe()}var Fe={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var Tn={setTimeout:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var o=Tn.delegate;return o?.setTimeout?o.setTimeout.apply(o,bn([t,e],yn(n))):setTimeout.apply(void 0,bn([t,e],yn(n)))},clearTimeout:function(t){var e=Tn.delegate;return(e?.clearTimeout||clearTimeout)(t)},delegate:void 0};function Zr(t){Tn.setTimeout(function(){var e=Fe.onUnhandledError;if(e)e(t);else throw t})}function Zn(){}var Ll=(function(){return pi("C",void 0,void 0)})();function Pl(t){return pi("E",void 0,t)}function Dl(t){return pi("N",t,void 0)}function pi(t,e,n){return{kind:t,value:e,error:n}}var Bt=null;function _n(t){if(Fe.useDeprecatedSynchronousErrorHandling){var e=!Bt;if(e&&(Bt={errorThrown:!1,error:null}),t(),e){var n=Bt,r=n.errorThrown,o=n.error;if(Bt=null,r)throw o}}else t()}function Ul(t){Fe.useDeprecatedSynchronousErrorHandling&&Bt&&(Bt.errorThrown=!0,Bt.error=t)}var Kn=(function(t){nt(e,t);function e(n){var r=t.call(this)||this;return r.isStopped=!1,n?(r.destination=n,Xr(n)&&n.add(r)):r.destination=Fh,r}return e.create=function(n,r,o){return new Yr(n,r,o)},e.prototype.next=function(n){this.isStopped?hi(Dl(n),this):this._next(n)},e.prototype.error=function(n){this.isStopped?hi(Pl(n),this):(this.isStopped=!0,this._error(n))},e.prototype.complete=function(){this.isStopped?hi(Ll,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(n){this.destination.next(n)},e.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(En);var Uh=Function.prototype.bind;function fi(t,e){return Uh.call(t,e)}var Gh=(function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var n=this.partialObserver;if(n.next)try{n.next(e)}catch(r){Kr(r)}},t.prototype.error=function(e){var n=this.partialObserver;if(n.error)try{n.error(e)}catch(r){Kr(r)}else Kr(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(n){Kr(n)}},t})(),Yr=(function(t){nt(e,t);function e(n,r,o){var s=t.call(this)||this,i;if(G(n)||!n)i={next:n??void 0,error:r??void 0,complete:o??void 0};else{var a;s&&Fe.useDeprecatedNextContext?(a=Object.create(n),a.unsubscribe=function(){return s.unsubscribe()},i={next:n.next&&fi(n.next,a),error:n.error&&fi(n.error,a),complete:n.complete&&fi(n.complete,a)}):i=n}return s.destination=new Gh(i),s}return e})(Kn);function Kr(t){Fe.useDeprecatedSynchronousErrorHandling?Ul(t):Zr(t)}function Hh(t){throw t}function hi(t,e){var n=Fe.onStoppedNotification;n&&Tn.setTimeout(function(){return n(t,e)})}var Fh={closed:!0,next:Zn,error:Hh,complete:Zn};var Sn=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function wn(t){return t}function qr(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return mi(t)}function mi(t){return t.length===0?wn:t.length===1?t[0]:function(n){return t.reduce(function(r,o){return o(r)},n)}}var J=(function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(e,n,r){var o=this,s=zh(e)?e:new Yr(e,n,r);return _n(function(){var i=o,a=i.operator,u=i.source;s.add(a?a.call(s,u):u?o._subscribe(s):o._trySubscribe(s))}),s},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(n){e.error(n)}},t.prototype.forEach=function(e,n){var r=this;return n=Gl(n),new n(function(o,s){var i=new Yr({next:function(a){try{e(a)}catch(u){s(u),i.unsubscribe()}},error:s,complete:o});r.subscribe(i)})},t.prototype._subscribe=function(e){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(e)},t.prototype[Sn]=function(){return this},t.prototype.pipe=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return mi(e)(this)},t.prototype.toPromise=function(e){var n=this;return e=Gl(e),new e(function(r,o){var s;n.subscribe(function(i){return s=i},function(i){return o(i)},function(){return r(s)})})},t.create=function(e){return new t(e)},t})();function Gl(t){var e;return(e=t??Fe.Promise)!==null&&e!==void 0?e:Promise}function $h(t){return t&&G(t.next)&&G(t.error)&&G(t.complete)}function zh(t){return t&&t instanceof Kn||$h(t)&&Xr(t)}function Bh(t){return G(t?.lift)}function ue(t){return function(e){if(Bh(e))return e.lift(function(n){try{return t(n,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function he(t,e,n,r,o){return new Vh(t,e,n,r,o)}var Vh=(function(t){nt(e,t);function e(n,r,o,s,i,a){var u=t.call(this,n)||this;return u.onFinalize=i,u.shouldUnsubscribe=a,u._next=r?function(l){try{r(l)}catch(p){n.error(p)}}:t.prototype._next,u._error=s?function(l){try{s(l)}catch(p){n.error(p)}finally{this.unsubscribe()}}:t.prototype._error,u._complete=o?function(){try{o()}catch(l){n.error(l)}finally{this.unsubscribe()}}:t.prototype._complete,u}return e.prototype.unsubscribe=function(){var n;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;t.prototype.unsubscribe.call(this),!r&&((n=this.onFinalize)===null||n===void 0||n.call(this))}},e})(Kn);var Hl=xn(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var rt=(function(t){nt(e,t);function e(){var n=t.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return e.prototype.lift=function(n){var r=new Fl(this,this);return r.operator=n,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new Hl},e.prototype.next=function(n){var r=this;_n(function(){var o,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var i=ct(r.currentObservers),a=i.next();!a.done;a=i.next()){var u=a.value;u.next(n)}}catch(l){o={error:l}}finally{try{a&&!a.done&&(s=i.return)&&s.call(i)}finally{if(o)throw o.error}}}})},e.prototype.error=function(n){var r=this;_n(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var o=r.observers;o.length;)o.shift().error(n)}})},e.prototype.complete=function(){var n=this;_n(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var r=n.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(n){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,n)},e.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},e.prototype._innerSubscribe=function(n){var r=this,o=this,s=o.hasError,i=o.isStopped,a=o.observers;return s||i?di:(this.currentObservers=null,a.push(n),new En(function(){r.currentObservers=null,Xn(a,n)}))},e.prototype._checkFinalizedStatuses=function(n){var r=this,o=r.hasError,s=r.thrownError,i=r.isStopped;o?n.error(s):i&&n.complete()},e.prototype.asObservable=function(){var n=new J;return n.source=this,n},e.create=function(n,r){return new Fl(n,r)},e})(J);var Fl=(function(t){nt(e,t);function e(n,r){var o=t.call(this)||this;return o.destination=n,o.source=r,o}return e.prototype.next=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.next)===null||o===void 0||o.call(r,n)},e.prototype.error=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.error)===null||o===void 0||o.call(r,n)},e.prototype.complete=function(){var n,r;(r=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||r===void 0||r.call(n)},e.prototype._subscribe=function(n){var r,o;return(o=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&o!==void 0?o:di},e})(rt);var gi={now:function(){return(gi.delegate||Date).now()},delegate:void 0};var Jr=(function(t){nt(e,t);function e(n,r,o){n===void 0&&(n=1/0),r===void 0&&(r=1/0),o===void 0&&(o=gi);var s=t.call(this)||this;return s._bufferSize=n,s._windowTime=r,s._timestampProvider=o,s._buffer=[],s._infiniteTimeWindow=!0,s._infiniteTimeWindow=r===1/0,s._bufferSize=Math.max(1,n),s._windowTime=Math.max(1,r),s}return e.prototype.next=function(n){var r=this,o=r.isStopped,s=r._buffer,i=r._infiniteTimeWindow,a=r._timestampProvider,u=r._windowTime;o||(s.push(n),!i&&s.push(a.now()+u)),this._trimBuffer(),t.prototype.next.call(this,n)},e.prototype._subscribe=function(n){this._throwIfClosed(),this._trimBuffer();for(var r=this._innerSubscribe(n),o=this,s=o._infiniteTimeWindow,i=o._buffer,a=i.slice(),u=0;u<a.length&&!n.closed;u+=s?1:2)n.next(a[u]);return this._checkFinalizedStatuses(n),r},e.prototype._trimBuffer=function(){var n=this,r=n._bufferSize,o=n._timestampProvider,s=n._buffer,i=n._infiniteTimeWindow,a=(i?1:2)*r;if(r<1/0&&a<s.length&&s.splice(0,s.length-a),!i){for(var u=o.now(),l=0,p=1;p<s.length&&s[p]<=u;p+=2)l=p;l&&s.splice(0,l+1)}},e})(rt);var Qr=new J(function(t){return t.complete()});function $l(t){return t&&G(t.schedule)}function jh(t){return t[t.length-1]}function zl(t){return $l(jh(t))?t.pop():void 0}var eo=(function(t){return t&&typeof t.length=="number"&&typeof t!="function"});function to(t){return G(t?.then)}function no(t){return G(t[Sn])}function ro(t){return Symbol.asyncIterator&&G(t?.[Symbol.asyncIterator])}function oo(t){return new TypeError("You provided "+(t!==null&&typeof t=="object"?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Wh(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var so=Wh();function io(t){return G(t?.[so])}function ao(t){return Rl(this,arguments,function(){var n,r,o,s;return jr(this,function(i){switch(i.label){case 0:n=t.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,zt(n.read())];case 3:return r=i.sent(),o=r.value,s=r.done,s?[4,zt(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,zt(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return n.releaseLock(),[7];case 10:return[2]}})})}function lo(t){return G(t?.getReader)}function me(t){if(t instanceof J)return t;if(t!=null){if(no(t))return Xh(t);if(eo(t))return Zh(t);if(to(t))return Kh(t);if(ro(t))return Bl(t);if(io(t))return Yh(t);if(lo(t))return qh(t)}throw oo(t)}function Xh(t){return new J(function(e){var n=t[Sn]();if(G(n.subscribe))return n.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Zh(t){return new J(function(e){for(var n=0;n<t.length&&!e.closed;n++)e.next(t[n]);e.complete()})}function Kh(t){return new J(function(e){t.then(function(n){e.closed||(e.next(n),e.complete())},function(n){return e.error(n)}).then(null,Zr)})}function Yh(t){return new J(function(e){var n,r;try{for(var o=ct(t),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(a){n={error:a}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}e.complete()})}function Bl(t){return new J(function(e){Jh(t,e).catch(function(n){return e.error(n)})})}function qh(t){return Bl(ao(t))}function Jh(t,e){var n,r,o,s;return Nl(this,void 0,void 0,function(){var i,a;return jr(this,function(u){switch(u.label){case 0:u.trys.push([0,5,6,11]),n=Ol(t),u.label=1;case 1:return[4,n.next()];case 2:if(r=u.sent(),!!r.done)return[3,4];if(i=r.value,e.next(i),e.closed)return[2];u.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=u.sent(),o={error:a},[3,11];case 6:return u.trys.push([6,,9,10]),r&&!r.done&&(s=n.return)?[4,s.call(n)]:[3,8];case 7:u.sent(),u.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Le(t,e,n,r,o){r===void 0&&(r=0),o===void 0&&(o=!1);var s=e.schedule(function(){n(),o?t.add(this.schedule(null,r)):this.unsubscribe()},r);if(t.add(s),!o)return s}function co(t,e){return e===void 0&&(e=0),ue(function(n,r){n.subscribe(he(r,function(o){return Le(r,t,function(){return r.next(o)},e)},function(){return Le(r,t,function(){return r.complete()},e)},function(o){return Le(r,t,function(){return r.error(o)},e)}))})}function uo(t,e){return e===void 0&&(e=0),ue(function(n,r){r.add(t.schedule(function(){return n.subscribe(r)},e))})}function Vl(t,e){return me(t).pipe(uo(e),co(e))}function jl(t,e){return me(t).pipe(uo(e),co(e))}function Wl(t,e){return new J(function(n){var r=0;return e.schedule(function(){r===t.length?n.complete():(n.next(t[r++]),n.closed||this.schedule())})})}function Xl(t,e){return new J(function(n){var r;return Le(n,e,function(){r=t[so](),Le(n,e,function(){var o,s,i;try{o=r.next(),s=o.value,i=o.done}catch(a){n.error(a);return}i?n.complete():n.next(s)},0,!0)}),function(){return G(r?.return)&&r.return()}})}function po(t,e){if(!t)throw new Error("Iterable cannot be null");return new J(function(n){Le(n,e,function(){var r=t[Symbol.asyncIterator]();Le(n,e,function(){r.next().then(function(o){o.done?n.complete():n.next(o.value)})},0,!0)})})}function Zl(t,e){return po(ao(t),e)}function Kl(t,e){if(t!=null){if(no(t))return Vl(t,e);if(eo(t))return Wl(t,e);if(to(t))return jl(t,e);if(ro(t))return po(t,e);if(io(t))return Xl(t,e);if(lo(t))return Zl(t,e)}throw oo(t)}function Vt(t,e){return e?Kl(t,e):me(t)}function te(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=zl(t);return Vt(t,n)}function Q(t,e){var n=G(t)?t:function(){return t},r=function(o){return o.error(n())};return new J(e?function(o){return e.schedule(r,0,o)}:r)}var Yl=xn(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function fo(t,e){var n=typeof e=="object";return new Promise(function(r,o){var s=!1,i;t.subscribe({next:function(a){i=a,s=!0},error:o,complete:function(){s?r(i):n?r(e.defaultValue):o(new Yl)}})})}function jt(t,e){return ue(function(n,r){var o=0;n.subscribe(he(r,function(s){r.next(t.call(e,s,o++))}))})}function ql(t,e,n,r,o,s,i,a){var u=[],l=0,p=0,m=!1,x=function(){m&&!u.length&&!l&&e.complete()},f=function(g){return l<r?h(g):u.push(g)},h=function(g){s&&e.next(g),l++;var T=!1;me(n(g,p++)).subscribe(he(e,function(S){o?.(S),s?f(S):e.next(S)},function(){T=!0},void 0,function(){if(T)try{l--;for(var S=function(){var b=u.shift();i?Le(e,i,function(){return h(b)}):h(b)};u.length&&l<r;)S();x()}catch(b){e.error(b)}}))};return t.subscribe(he(e,f,function(){m=!0,x()})),function(){a?.()}}function Ae(t,e,n){return n===void 0&&(n=1/0),G(e)?Ae(function(r,o){return jt(function(s,i){return e(r,s,o,i)})(me(t(r,o)))},n):(typeof e=="number"&&(n=e),ue(function(r,o){return ql(r,o,t,n)}))}function vi(t){return t===void 0&&(t=1/0),Ae(wn,t)}function ho(t){return new J(function(e){me(t()).subscribe(e)})}function Yn(t){return ue(function(e,n){var r=null,o=!1,s;r=e.subscribe(he(n,void 0,void 0,function(i){s=me(t(i,Yn(t)(e))),r?(r.unsubscribe(),r=null,s.subscribe(n)):o=!0})),o&&(r.unsubscribe(),r=null,s.subscribe(n))})}function mo(t,e){return G(e)?Ae(t,e,1):Ae(t,1)}function yi(t){return ue(function(e,n){var r=!1;e.subscribe(he(n,function(o){r=!0,n.next(o)},function(){r||n.next(t),n.complete()}))})}function Wt(t){return ue(function(e,n){try{e.subscribe(n)}finally{n.add(t)}})}function bi(t,e){return ue(function(n,r){var o=null,s=0,i=!1,a=function(){return i&&!o&&r.complete()};n.subscribe(he(r,function(u){o?.unsubscribe();var l=0,p=s++;me(t(u,p)).subscribe(o=he(r,function(m){return r.next(e?e(u,m,p,l++):m)},function(){o=null,a()}))},function(){i=!0,a()}))})}function go(t){return ue(function(e,n){me(t).subscribe(he(n,function(){return n.complete()},Zn)),!n.closed&&e.subscribe(n)})}function xi(t,e,n){var r=G(t)||e||n?{next:t,error:e,complete:n}:t;return r?ue(function(o,s){var i;(i=r.subscribe)===null||i===void 0||i.call(r);var a=!0;o.subscribe(he(s,function(u){var l;(l=r.next)===null||l===void 0||l.call(r,u),s.next(u)},function(){var u;a=!1,(u=r.complete)===null||u===void 0||u.call(r),s.complete()},function(u){var l;a=!1,(l=r.error)===null||l===void 0||l.call(r,u),s.error(u)},function(){var u,l;a&&((u=r.unsubscribe)===null||u===void 0||u.call(r)),(l=r.finalize)===null||l===void 0||l.call(r)}))}):wn}function Jl(t){return` \r
898
+ `.indexOf(t)>=0}function vo(t){for(var e=["topLevel"],n=0,r,o,s,i=function(b){return e.push(b)},a=function(b){return e[e.length-1]=b},u=function(b){r==null&&(r=n,o=e.length,s=b)},l=function(b){b===s&&(r=void 0,o=void 0,s=void 0)},p=function(){return e.pop()},m=function(){return n--},x=function(b){if("0"<=b&&b<="9"){i("number");return}switch(b){case'"':i("string");return;case"-":i("numberNeedsDigit");return;case"t":i("true");return;case"f":i("false");return;case"n":i("null");return;case"[":i("arrayNeedsValue");return;case"{":i("objectNeedsKey");return}},f=t.length;n<f;n++){var h=t[n];switch(e[e.length-1]){case"topLevel":x(h);break;case"string":switch(h){case'"':p();break;case"\\":u("stringEscape"),i("stringEscaped");break}break;case"stringEscaped":h==="u"?i("stringUnicode"):(l("stringEscape"),p());break;case"stringUnicode":n-t.lastIndexOf("u",n)===4&&(l("stringEscape"),p());break;case"number":h==="."?a("numberNeedsDigit"):h==="e"||h==="E"?a("numberNeedsExponent"):(h<"0"||h>"9")&&(m(),p());break;case"numberNeedsDigit":a("number");break;case"numberNeedsExponent":a(h==="+"||h==="-"?"numberNeedsDigit":"number");break;case"true":case"false":case"null":(h<"a"||h>"z")&&(m(),p());break;case"arrayNeedsValue":h==="]"?p():Jl(h)||(l("collectionItem"),a("arrayNeedsComma"),x(h));break;case"arrayNeedsComma":h==="]"?p():h===","&&(u("collectionItem"),a("arrayNeedsValue"));break;case"objectNeedsKey":h==="}"?p():h==='"'&&(u("collectionItem"),a("objectNeedsColon"),i("string"));break;case"objectNeedsColon":h===":"&&a("objectNeedsValue");break;case"objectNeedsValue":Jl(h)||(l("collectionItem"),a("objectNeedsComma"),x(h));break;case"objectNeedsComma":h==="}"?p():h===","&&(u("collectionItem"),a("objectNeedsKey"));break}}o!=null&&(e.length=o);for(var g=[r!=null?t.slice(0,r):t],T=function(b){return g.push(b.slice(t.length-t.lastIndexOf(b[0])))},S=e.length-1;S>=0;S--)switch(e[S]){case"string":g.push('"');break;case"numberNeedsDigit":case"numberNeedsExponent":g.push("0");break;case"true":T("true");break;case"false":T("false");break;case"null":T("null");break;case"arrayNeedsValue":case"arrayNeedsComma":g.push("]");break;case"objectNeedsKey":case"objectNeedsColon":case"objectNeedsValue":case"objectNeedsComma":g.push("}");break}return g.join("")}function ec(){let t=0,e=0;for(let r=0;r<28;r+=7){let o=this.buf[this.pos++];if(t|=(o&127)<<r,(o&128)==0)return this.assertBounds(),[t,e]}let n=this.buf[this.pos++];if(t|=(n&15)<<28,e=(n&112)>>4,(n&128)==0)return this.assertBounds(),[t,e];for(let r=3;r<=31;r+=7){let o=this.buf[this.pos++];if(e|=(o&127)<<r,(o&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function bo(t,e,n){for(let s=0;s<28;s=s+7){let i=t>>>s,a=!(!(i>>>7)&&e==0),u=(a?i|128:i)&255;if(n.push(u),!a)return}let r=t>>>28&15|(e&7)<<4,o=e>>3!=0;if(n.push((o?r|128:r)&255),!!o){for(let s=3;s<31;s=s+7){let i=e>>>s,a=!!(i>>>7),u=(a?i|128:i)&255;if(n.push(u),!a)return}n.push(e>>>31&1)}}var yo=4294967296;function Ei(t){let e=t[0]==="-";e&&(t=t.slice(1));let n=1e6,r=0,o=0;function s(i,a){let u=Number(t.slice(i,a));o*=n,r=r*n+u,r>=yo&&(o=o+(r/yo|0),r=r%yo)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?nc(r,o):_i(r,o)}function tc(t,e){let n=_i(t,e),r=n.hi&2147483648;r&&(n=nc(n.lo,n.hi));let o=Ti(n.lo,n.hi);return r?"-"+o:o}function Ti(t,e){if({lo:t,hi:e}=Qh(t,e),e<=2097151)return String(yo*e+t);let n=t&16777215,r=(t>>>24|e<<8)&16777215,o=e>>16&65535,s=n+r*6777216+o*6710656,i=r+o*8147497,a=o*2,u=1e7;return s>=u&&(i+=Math.floor(s/u),s%=u),i>=u&&(a+=Math.floor(i/u),i%=u),a.toString()+Ql(i)+Ql(s)}function Qh(t,e){return{lo:t>>>0,hi:e>>>0}}function _i(t,e){return{lo:t|0,hi:e|0}}function nc(t,e){return e=~e,t?t=~t+1:e+=1,_i(t,e)}var Ql=t=>{let e=String(t);return"0000000".slice(e.length)+e};function Si(t,e){if(t>=0){for(;t>127;)e.push(t&127|128),t=t>>>7;e.push(t)}else{for(let n=0;n<9;n++)e.push(t&127|128),t=t>>7;e.push(1)}}function rc(){let t=this.buf[this.pos++],e=t&127;if((t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<7,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<14,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<21,(t&128)==0)return this.assertBounds(),e;t=this.buf[this.pos++],e|=(t&15)<<28;for(let n=5;(t&128)!==0&&n<10;n++)t=this.buf[this.pos++];if((t&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}var $e=em();function em(){let t=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof t.getBigInt64=="function"&&typeof t.getBigUint64=="function"&&typeof t.setBigInt64=="function"&&typeof t.setBigUint64=="function"&&(!!globalThis.Deno||typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){let n=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),o=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(i){let a=typeof i=="bigint"?i:BigInt(i);if(a>r||a<n)throw new Error(`invalid int64: ${i}`);return a},uParse(i){let a=typeof i=="bigint"?i:BigInt(i);if(a>s||a<o)throw new Error(`invalid uint64: ${i}`);return a},enc(i){return t.setBigInt64(0,this.parse(i),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},uEnc(i){return t.setBigInt64(0,this.uParse(i),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},dec(i,a){return t.setInt32(0,i,!0),t.setInt32(4,a,!0),t.getBigInt64(0,!0)},uDec(i,a){return t.setInt32(0,i,!0),t.setInt32(4,a,!0),t.getBigUint64(0,!0)}}}return{zero:"0",supported:!1,parse(n){return typeof n!="string"&&(n=n.toString()),oc(n),n},uParse(n){return typeof n!="string"&&(n=n.toString()),sc(n),n},enc(n){return typeof n!="string"&&(n=n.toString()),oc(n),Ei(n)},uEnc(n){return typeof n!="string"&&(n=n.toString()),sc(n),Ei(n)},dec(n,r){return tc(n,r)},uDec(n,r){return Ti(n,r)}}}function oc(t){if(!/^-?[0-9]+$/.test(t))throw new Error("invalid int64: "+t)}function sc(t){if(!/^[0-9]+$/.test(t))throw new Error("invalid uint64: "+t)}var wi=Symbol.for("@bufbuild/protobuf/text-encoding");function ki(){if(globalThis[wi]==null){let t=new globalThis.TextEncoder,e=new globalThis.TextDecoder,n;globalThis[wi]={encodeUtf8(r){return t.encode(r)},decodeUtf8(r,o){return o?(n===void 0&&(n=new globalThis.TextDecoder("utf-8",{fatal:!0})),n.decode(r)):e.decode(r)},checkUtf8(r){try{return encodeURIComponent(r),!0}catch{return!1}}}}return globalThis[wi]}var bt;(function(t){t[t.Varint=0]="Varint",t[t.Bit64=1]="Bit64",t[t.LengthDelimited=2]="LengthDelimited",t[t.StartGroup=3]="StartGroup",t[t.EndGroup=4]="EndGroup",t[t.Bit32=5]="Bit32"})(bt||(bt={}));var tm=34028234663852886e22,nm=-34028234663852886e22,rm=4294967295,om=2147483647,sm=-2147483648,D=class{constructor(e=ki().encodeUtf8){this.encodeUtf8=e,this.stack=[],this.chunks=[],this.buf=[]}finish(){this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]);let e=0;for(let o=0;o<this.chunks.length;o++)e+=this.chunks[o].length;let n=new Uint8Array(e),r=0;for(let o=0;o<this.chunks.length;o++)n.set(this.chunks[o],r),r+=this.chunks[o].length;return this.chunks=[],n}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),n=this.stack.pop();if(!n)throw new Error("invalid state, fork stack empty");return this.chunks=n.chunks,this.buf=n.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,n){return this.uint32((e<<3|n)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(ic(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Ai(e),Si(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let n=this.encodeUtf8(e);return this.uint32(n.byteLength),this.raw(n)}float(e){im(e);let n=new Uint8Array(4);return new DataView(n.buffer).setFloat32(0,e,!0),this.raw(n)}double(e){let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,e,!0),this.raw(n)}fixed32(e){ic(e);let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e,!0),this.raw(n)}sfixed32(e){Ai(e);let n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,e,!0),this.raw(n)}sint32(e){return Ai(e),e=(e<<1^e>>31)>>>0,Si(e,this.buf),this}sfixed64(e){let n=new Uint8Array(8),r=new DataView(n.buffer),o=$e.enc(e);return r.setInt32(0,o.lo,!0),r.setInt32(4,o.hi,!0),this.raw(n)}fixed64(e){let n=new Uint8Array(8),r=new DataView(n.buffer),o=$e.uEnc(e);return r.setInt32(0,o.lo,!0),r.setInt32(4,o.hi,!0),this.raw(n)}int64(e){let n=$e.enc(e);return bo(n.lo,n.hi,this.buf),this}sint64(e){let n=$e.enc(e),r=n.hi>>31,o=n.lo<<1^r,s=(n.hi<<1|n.lo>>>31)^r;return bo(o,s,this.buf),this}uint64(e){let n=$e.uEnc(e);return bo(n.lo,n.hi,this.buf),this}},_=class{constructor(e,n=ki().decodeUtf8){this.decodeUtf8=n,this.varint64=ec,this.uint32=rc,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}tag(){let e=this.pos,n=this.uint32(),r=this.pos-e;if(r>5||r==5&&this.buf[this.pos-1]>15)throw new Error("illegal tag: varint overflows uint32");let o=n>>>3,s=n&7;if(o<=0||s>5)throw new Error("illegal tag: field no "+o+" wire type "+s);return[o,s]}skip(e,n){let r=this.pos;switch(e){case bt.Varint:for(;this.buf[this.pos++]&128;);break;case bt.Bit64:this.pos+=4;case bt.Bit32:this.pos+=4;break;case bt.LengthDelimited:let o=this.uint32();this.pos+=o;break;case bt.StartGroup:for(;;){let[s,i]=this.tag();if(i===bt.EndGroup){if(n!==void 0&&s!==n)throw new Error("invalid end group tag");break}this.skip(i,s)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(r,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return $e.dec(...this.varint64())}uint64(){return $e.uDec(...this.varint64())}sint64(){let[e,n]=this.varint64(),r=-(e&1);return e=(e>>>1|(n&1)<<31)^r,n=n>>>1^r,$e.dec(e,n)}bool(){let[e,n]=this.varint64();return e!==0||n!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return $e.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return $e.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),n=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(n,n+e)}string(e){return this.decodeUtf8(this.bytes(),e)}};function Ai(t){if(typeof t=="string")t=Number(t);else if(typeof t!="number")throw new Error("invalid int32: "+typeof t);if(!Number.isInteger(t)||t>om||t<sm)throw new Error("invalid int32: "+t)}function ic(t){if(typeof t=="string")t=Number(t);else if(typeof t!="number")throw new Error("invalid uint32: "+typeof t);if(!Number.isInteger(t)||t>rm||t<0)throw new Error("invalid uint32: "+t)}function im(t){if(typeof t=="string"){let e=t;if(t=Number(t),Number.isNaN(t)&&e!=="NaN")throw new Error("invalid float32: "+e)}else if(typeof t!="number")throw new Error("invalid float32: "+typeof t);if(Number.isFinite(t)&&(t>tm||t<nm))throw new Error("invalid float32: "+t)}var am=(function(t){return t[t.NULL_VALUE=0]="NULL_VALUE",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function Ii(){return{fields:{}}}var qn={encode(t,e=new D){return Object.entries(t.fields).forEach(([n,r])=>{r!==void 0&&Ri.encode({key:n,value:r},e.uint32(10).fork()).join()}),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Ii();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:{if(s!==10)break;let i=Ri.decode(n,n.uint32());i.value!==void 0&&(o.fields[i.key]=i.value);continue}}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return qn.fromPartial(t??{})},fromPartial(t){let e=Ii();return e.fields=Object.entries(t.fields??{}).reduce((n,[r,o])=>(o!==void 0&&(n[r]=o),n),{}),e},wrap(t){let e=Ii();if(t!==void 0)for(let n of Object.keys(t))e.fields[n]=t[n];return e},unwrap(t){let e={};if(t.fields)for(let n of Object.keys(t.fields))e[n]=t.fields[n];return e}};function ac(){return{key:"",value:void 0}}var Ri={encode(t,e=new D){return t.key!==""&&e.uint32(10).string(t.key),t.value!==void 0&&N.encode(N.wrap(t.value),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=ac();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.key=n.string();continue;case 2:if(s!==18)break;o.value=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Ri.fromPartial(t??{})},fromPartial(t){let e=ac();return e.key=t.key??"",e.value=t.value??void 0,e}};function Ci(){return{nullValue:void 0,numberValue:void 0,stringValue:void 0,boolValue:void 0,structValue:void 0,listValue:void 0}}var N={encode(t,e=new D){return t.nullValue!==void 0&&e.uint32(8).int32(t.nullValue),t.numberValue!==void 0&&e.uint32(17).double(t.numberValue),t.stringValue!==void 0&&e.uint32(26).string(t.stringValue),t.boolValue!==void 0&&e.uint32(32).bool(t.boolValue),t.structValue!==void 0&&qn.encode(qn.wrap(t.structValue),e.uint32(42).fork()).join(),t.listValue!==void 0&&Jn.encode(Jn.wrap(t.listValue),e.uint32(50).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Ci();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==8)break;o.nullValue=n.int32();continue;case 2:if(s!==17)break;o.numberValue=n.double();continue;case 3:if(s!==26)break;o.stringValue=n.string();continue;case 4:if(s!==32)break;o.boolValue=n.bool();continue;case 5:if(s!==42)break;o.structValue=qn.unwrap(qn.decode(n,n.uint32()));continue;case 6:if(s!==50)break;o.listValue=Jn.unwrap(Jn.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return N.fromPartial(t??{})},fromPartial(t){let e=Ci();return e.nullValue=t.nullValue??void 0,e.numberValue=t.numberValue??void 0,e.stringValue=t.stringValue??void 0,e.boolValue=t.boolValue??void 0,e.structValue=t.structValue??void 0,e.listValue=t.listValue??void 0,e},wrap(t){let e=Ci();if(t===null)e.nullValue=am.NULL_VALUE;else if(typeof t=="boolean")e.boolValue=t;else if(typeof t=="number")e.numberValue=t;else if(typeof t=="string")e.stringValue=t;else if(globalThis.Array.isArray(t))e.listValue=t;else if(typeof t=="object")e.structValue=t;else if(typeof t<"u")throw new globalThis.Error("Unsupported any value type: "+typeof t);return e},unwrap(t){if(t.stringValue!==void 0)return t.stringValue;if(t?.numberValue!==void 0)return t.numberValue;if(t?.boolValue!==void 0)return t.boolValue;if(t?.structValue!==void 0)return t.structValue;if(t?.listValue!==void 0)return t.listValue;if(t?.nullValue!==void 0)return null}};function Ni(){return{values:[]}}var Jn={encode(t,e=new D){for(let n of t.values)N.encode(N.wrap(n),e.uint32(10).fork()).join();return e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Ni();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.values.push(N.unwrap(N.decode(n,n.uint32())));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Jn.fromPartial(t??{})},fromPartial(t){let e=Ni();return e.values=t.values?.map(n=>n)||[],e},wrap(t){let e=Ni();return e.values=t??[],e},unwrap(t){return t?.hasOwnProperty("values")&&globalThis.Array.isArray(t.values)?t.values:t}},lm=(function(t){return t[t.ADD=0]="ADD",t[t.REMOVE=1]="REMOVE",t[t.REPLACE=2]="REPLACE",t[t.MOVE=3]="MOVE",t[t.COPY=4]="COPY",t[t.TEST=5]="TEST",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function lc(){return{op:0,path:"",from:void 0,value:void 0}}var Eo={encode(t,e=new D){return t.op!==0&&e.uint32(8).int32(t.op),t.path!==""&&e.uint32(18).string(t.path),t.from!==void 0&&e.uint32(26).string(t.from),t.value!==void 0&&N.encode(N.wrap(t.value),e.uint32(34).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=lc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==8)break;o.op=n.int32();continue;case 2:if(s!==18)break;o.path=n.string();continue;case 3:if(s!==26)break;o.from=n.string();continue;case 4:if(s!==34)break;o.value=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Eo.fromPartial(t??{})},fromPartial(t){let e=lc();return e.op=t.op??0,e.path=t.path??"",e.from=t.from??void 0,e.value=t.value??void 0,e}};function cc(){return{id:"",type:"",function:void 0}}var To={encode(t,e=new D){return t.id!==""&&e.uint32(10).string(t.id),t.type!==""&&e.uint32(18).string(t.type),t.function!==void 0&&_o.encode(t.function,e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=cc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.id=n.string();continue;case 2:if(s!==18)break;o.type=n.string();continue;case 3:if(s!==26)break;o.function=_o.decode(n,n.uint32());continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return To.fromPartial(t??{})},fromPartial(t){let e=cc();return e.id=t.id??"",e.type=t.type??"",e.function=t.function!==void 0&&t.function!==null?_o.fromPartial(t.function):void 0,e}};function uc(){return{name:"",arguments:""}}var _o={encode(t,e=new D){return t.name!==""&&e.uint32(10).string(t.name),t.arguments!==""&&e.uint32(18).string(t.arguments),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=uc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.name=n.string();continue;case 2:if(s!==18)break;o.arguments=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return _o.fromPartial(t??{})},fromPartial(t){let e=uc();return e.name=t.name??"",e.arguments=t.arguments??"",e}};function dc(){return{value:"",mimeType:""}}var So={encode(t,e=new D){return t.value!==""&&e.uint32(10).string(t.value),t.mimeType!==""&&e.uint32(18).string(t.mimeType),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=dc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.value=n.string();continue;case 2:if(s!==18)break;o.mimeType=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return So.fromPartial(t??{})},fromPartial(t){let e=dc();return e.value=t.value??"",e.mimeType=t.mimeType??"",e}};function pc(){return{value:"",mimeType:void 0}}var wo={encode(t,e=new D){return t.value!==""&&e.uint32(10).string(t.value),t.mimeType!==void 0&&e.uint32(18).string(t.mimeType),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=pc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.value=n.string();continue;case 2:if(s!==18)break;o.mimeType=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return wo.fromPartial(t??{})},fromPartial(t){let e=pc();return e.value=t.value??"",e.mimeType=t.mimeType??void 0,e}};function fc(){return{data:void 0,url:void 0}}var Ie={encode(t,e=new D){return t.data!==void 0&&So.encode(t.data,e.uint32(10).fork()).join(),t.url!==void 0&&wo.encode(t.url,e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=fc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.data=So.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.url=wo.decode(n,n.uint32());continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Ie.fromPartial(t??{})},fromPartial(t){let e=fc();return e.data=t.data!==void 0&&t.data!==null?So.fromPartial(t.data):void 0,e.url=t.url!==void 0&&t.url!==null?wo.fromPartial(t.url):void 0,e}};function hc(){return{text:""}}var ko={encode(t,e=new D){return t.text!==""&&e.uint32(10).string(t.text),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=hc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.text=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return ko.fromPartial(t??{})},fromPartial(t){let e=hc();return e.text=t.text??"",e}};function mc(){return{source:void 0,metadata:void 0}}var Ao={encode(t,e=new D){return t.source!==void 0&&Ie.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&N.encode(N.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=mc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.source=Ie.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Ao.fromPartial(t??{})},fromPartial(t){let e=mc();return e.source=t.source!==void 0&&t.source!==null?Ie.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function gc(){return{source:void 0,metadata:void 0}}var Io={encode(t,e=new D){return t.source!==void 0&&Ie.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&N.encode(N.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=gc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.source=Ie.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Io.fromPartial(t??{})},fromPartial(t){let e=gc();return e.source=t.source!==void 0&&t.source!==null?Ie.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function vc(){return{source:void 0,metadata:void 0}}var Co={encode(t,e=new D){return t.source!==void 0&&Ie.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&N.encode(N.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=vc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.source=Ie.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Co.fromPartial(t??{})},fromPartial(t){let e=vc();return e.source=t.source!==void 0&&t.source!==null?Ie.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function yc(){return{source:void 0,metadata:void 0}}var No={encode(t,e=new D){return t.source!==void 0&&Ie.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&N.encode(N.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=yc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.source=Ie.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return No.fromPartial(t??{})},fromPartial(t){let e=yc();return e.source=t.source!==void 0&&t.source!==null?Ie.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function bc(){return{text:void 0,image:void 0,audio:void 0,video:void 0,document:void 0}}var Ro={encode(t,e=new D){return t.text!==void 0&&ko.encode(t.text,e.uint32(10).fork()).join(),t.image!==void 0&&Ao.encode(t.image,e.uint32(18).fork()).join(),t.audio!==void 0&&Io.encode(t.audio,e.uint32(26).fork()).join(),t.video!==void 0&&Co.encode(t.video,e.uint32(34).fork()).join(),t.document!==void 0&&No.encode(t.document,e.uint32(42).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=bc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.text=ko.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.image=Ao.decode(n,n.uint32());continue;case 3:if(s!==26)break;o.audio=Io.decode(n,n.uint32());continue;case 4:if(s!==34)break;o.video=Co.decode(n,n.uint32());continue;case 5:if(s!==42)break;o.document=No.decode(n,n.uint32());continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Ro.fromPartial(t??{})},fromPartial(t){let e=bc();return e.text=t.text!==void 0&&t.text!==null?ko.fromPartial(t.text):void 0,e.image=t.image!==void 0&&t.image!==null?Ao.fromPartial(t.image):void 0,e.audio=t.audio!==void 0&&t.audio!==null?Io.fromPartial(t.audio):void 0,e.video=t.video!==void 0&&t.video!==null?Co.fromPartial(t.video):void 0,e.document=t.document!==void 0&&t.document!==null?No.fromPartial(t.document):void 0,e}};function xc(){return{id:"",role:"",content:void 0,name:void 0,toolCalls:[],toolCallId:void 0,error:void 0,contentParts:[]}}var Oo={encode(t,e=new D){t.id!==""&&e.uint32(10).string(t.id),t.role!==""&&e.uint32(18).string(t.role),t.content!==void 0&&e.uint32(26).string(t.content),t.name!==void 0&&e.uint32(34).string(t.name);for(let n of t.toolCalls)To.encode(n,e.uint32(42).fork()).join();t.toolCallId!==void 0&&e.uint32(50).string(t.toolCallId),t.error!==void 0&&e.uint32(58).string(t.error);for(let n of t.contentParts)Ro.encode(n,e.uint32(66).fork()).join();return e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=xc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.id=n.string();continue;case 2:if(s!==18)break;o.role=n.string();continue;case 3:if(s!==26)break;o.content=n.string();continue;case 4:if(s!==34)break;o.name=n.string();continue;case 5:if(s!==42)break;o.toolCalls.push(To.decode(n,n.uint32()));continue;case 6:if(s!==50)break;o.toolCallId=n.string();continue;case 7:if(s!==58)break;o.error=n.string();continue;case 8:if(s!==66)break;o.contentParts.push(Ro.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Oo.fromPartial(t??{})},fromPartial(t){let e=xc();return e.id=t.id??"",e.role=t.role??"",e.content=t.content??void 0,e.name=t.name??void 0,e.toolCalls=t.toolCalls?.map(n=>To.fromPartial(n))||[],e.toolCallId=t.toolCallId??void 0,e.error=t.error??void 0,e.contentParts=t.contentParts?.map(n=>Ro.fromPartial(n))||[],e}};function Ec(){return{id:"",reason:"",message:void 0,toolCallId:void 0,responseSchema:void 0,expiresAt:void 0,metadata:void 0}}var Mo={encode(t,e=new D){return t.id!==""&&e.uint32(10).string(t.id),t.reason!==""&&e.uint32(18).string(t.reason),t.message!==void 0&&e.uint32(26).string(t.message),t.toolCallId!==void 0&&e.uint32(34).string(t.toolCallId),t.responseSchema!==void 0&&N.encode(N.wrap(t.responseSchema),e.uint32(42).fork()).join(),t.expiresAt!==void 0&&e.uint32(50).string(t.expiresAt),t.metadata!==void 0&&N.encode(N.wrap(t.metadata),e.uint32(58).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Ec();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.id=n.string();continue;case 2:if(s!==18)break;o.reason=n.string();continue;case 3:if(s!==26)break;o.message=n.string();continue;case 4:if(s!==34)break;o.toolCallId=n.string();continue;case 5:if(s!==42)break;o.responseSchema=N.unwrap(N.decode(n,n.uint32()));continue;case 6:if(s!==50)break;o.expiresAt=n.string();continue;case 7:if(s!==58)break;o.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Mo.fromPartial(t??{})},fromPartial(t){let e=Ec();return e.id=t.id??"",e.reason=t.reason??"",e.message=t.message??void 0,e.toolCallId=t.toolCallId??void 0,e.responseSchema=t.responseSchema??void 0,e.expiresAt=t.expiresAt??void 0,e.metadata=t.metadata??void 0,e}},cm=(function(t){return t[t.TEXT_MESSAGE_START=0]="TEXT_MESSAGE_START",t[t.TEXT_MESSAGE_CONTENT=1]="TEXT_MESSAGE_CONTENT",t[t.TEXT_MESSAGE_END=2]="TEXT_MESSAGE_END",t[t.TOOL_CALL_START=3]="TOOL_CALL_START",t[t.TOOL_CALL_ARGS=4]="TOOL_CALL_ARGS",t[t.TOOL_CALL_END=5]="TOOL_CALL_END",t[t.STATE_SNAPSHOT=6]="STATE_SNAPSHOT",t[t.STATE_DELTA=7]="STATE_DELTA",t[t.MESSAGES_SNAPSHOT=8]="MESSAGES_SNAPSHOT",t[t.RAW=9]="RAW",t[t.CUSTOM=10]="CUSTOM",t[t.RUN_STARTED=11]="RUN_STARTED",t[t.RUN_FINISHED=12]="RUN_FINISHED",t[t.RUN_ERROR=13]="RUN_ERROR",t[t.STEP_STARTED=14]="STEP_STARTED",t[t.STEP_FINISHED=15]="STEP_FINISHED",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function Tc(){return{type:0,timestamp:void 0,rawEvent:void 0}}var R={encode(t,e=new D){return t.type!==0&&e.uint32(8).int32(t.type),t.timestamp!==void 0&&e.uint32(16).int64(t.timestamp),t.rawEvent!==void 0&&N.encode(N.wrap(t.rawEvent),e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Tc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==8)break;o.type=n.int32();continue;case 2:if(s!==16)break;o.timestamp=um(n.int64());continue;case 3:if(s!==26)break;o.rawEvent=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return R.fromPartial(t??{})},fromPartial(t){let e=Tc();return e.type=t.type??0,e.timestamp=t.timestamp??void 0,e.rawEvent=t.rawEvent??void 0,e}};function _c(){return{baseEvent:void 0,messageId:"",role:void 0,name:void 0}}var Lo={encode(t,e=new D){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==""&&e.uint32(18).string(t.messageId),t.role!==void 0&&e.uint32(26).string(t.role),t.name!==void 0&&e.uint32(34).string(t.name),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=_c();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.messageId=n.string();continue;case 3:if(s!==26)break;o.role=n.string();continue;case 4:if(s!==34)break;o.name=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Lo.fromPartial(t??{})},fromPartial(t){let e=_c();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e.role=t.role??void 0,e.name=t.name??void 0,e}};function Sc(){return{baseEvent:void 0,messageId:"",delta:""}}var Po={encode(t,e=new D){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==""&&e.uint32(18).string(t.messageId),t.delta!==""&&e.uint32(26).string(t.delta),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Sc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.messageId=n.string();continue;case 3:if(s!==26)break;o.delta=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Po.fromPartial(t??{})},fromPartial(t){let e=Sc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e.delta=t.delta??"",e}};function wc(){return{baseEvent:void 0,messageId:""}}var Do={encode(t,e=new D){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==""&&e.uint32(18).string(t.messageId),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=wc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.messageId=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Do.fromPartial(t??{})},fromPartial(t){let e=wc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e}};function kc(){return{baseEvent:void 0,toolCallId:"",toolCallName:"",parentMessageId:void 0}}var Uo={encode(t,e=new D){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==""&&e.uint32(18).string(t.toolCallId),t.toolCallName!==""&&e.uint32(26).string(t.toolCallName),t.parentMessageId!==void 0&&e.uint32(34).string(t.parentMessageId),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=kc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.toolCallId=n.string();continue;case 3:if(s!==26)break;o.toolCallName=n.string();continue;case 4:if(s!==34)break;o.parentMessageId=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Uo.fromPartial(t??{})},fromPartial(t){let e=kc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e.toolCallName=t.toolCallName??"",e.parentMessageId=t.parentMessageId??void 0,e}};function Ac(){return{baseEvent:void 0,toolCallId:"",delta:""}}var Go={encode(t,e=new D){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==""&&e.uint32(18).string(t.toolCallId),t.delta!==""&&e.uint32(26).string(t.delta),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Ac();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.toolCallId=n.string();continue;case 3:if(s!==26)break;o.delta=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Go.fromPartial(t??{})},fromPartial(t){let e=Ac();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e.delta=t.delta??"",e}};function Ic(){return{baseEvent:void 0,toolCallId:""}}var Ho={encode(t,e=new D){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==""&&e.uint32(18).string(t.toolCallId),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Ic();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.toolCallId=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Ho.fromPartial(t??{})},fromPartial(t){let e=Ic();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e}};function Cc(){return{baseEvent:void 0,snapshot:void 0}}var Fo={encode(t,e=new D){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.snapshot!==void 0&&N.encode(N.wrap(t.snapshot),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Cc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.snapshot=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Fo.fromPartial(t??{})},fromPartial(t){let e=Cc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.snapshot=t.snapshot??void 0,e}};function Nc(){return{baseEvent:void 0,delta:[]}}var $o={encode(t,e=new D){t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.delta)Eo.encode(n,e.uint32(18).fork()).join();return e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Nc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.delta.push(Eo.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return $o.fromPartial(t??{})},fromPartial(t){let e=Nc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.delta=t.delta?.map(n=>Eo.fromPartial(n))||[],e}};function Rc(){return{baseEvent:void 0,messages:[]}}var zo={encode(t,e=new D){t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.messages)Oo.encode(n,e.uint32(18).fork()).join();return e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Rc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.messages.push(Oo.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return zo.fromPartial(t??{})},fromPartial(t){let e=Rc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.messages=t.messages?.map(n=>Oo.fromPartial(n))||[],e}};function Oc(){return{baseEvent:void 0,event:void 0,source:void 0}}var Bo={encode(t,e=new D){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.event!==void 0&&N.encode(N.wrap(t.event),e.uint32(18).fork()).join(),t.source!==void 0&&e.uint32(26).string(t.source),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Oc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.event=N.unwrap(N.decode(n,n.uint32()));continue;case 3:if(s!==26)break;o.source=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Bo.fromPartial(t??{})},fromPartial(t){let e=Oc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.event=t.event??void 0,e.source=t.source??void 0,e}};function Mc(){return{baseEvent:void 0,name:"",value:void 0}}var Vo={encode(t,e=new D){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.name!==""&&e.uint32(18).string(t.name),t.value!==void 0&&N.encode(N.wrap(t.value),e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Mc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.name=n.string();continue;case 3:if(s!==26)break;o.value=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Vo.fromPartial(t??{})},fromPartial(t){let e=Mc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.name=t.name??"",e.value=t.value??void 0,e}};function Lc(){return{baseEvent:void 0,threadId:"",runId:""}}var jo={encode(t,e=new D){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.threadId!==""&&e.uint32(18).string(t.threadId),t.runId!==""&&e.uint32(26).string(t.runId),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Lc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.threadId=n.string();continue;case 3:if(s!==26)break;o.runId=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return jo.fromPartial(t??{})},fromPartial(t){let e=Lc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.threadId=t.threadId??"",e.runId=t.runId??"",e}};function Pc(){return{baseEvent:void 0,threadId:"",runId:"",result:void 0,outcome:"",interrupts:[]}}var Wo={encode(t,e=new D){t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.threadId!==""&&e.uint32(18).string(t.threadId),t.runId!==""&&e.uint32(26).string(t.runId),t.result!==void 0&&N.encode(N.wrap(t.result),e.uint32(34).fork()).join(),t.outcome!==""&&e.uint32(42).string(t.outcome);for(let n of t.interrupts)Mo.encode(n,e.uint32(50).fork()).join();return e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Pc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.threadId=n.string();continue;case 3:if(s!==26)break;o.runId=n.string();continue;case 4:if(s!==34)break;o.result=N.unwrap(N.decode(n,n.uint32()));continue;case 5:if(s!==42)break;o.outcome=n.string();continue;case 6:if(s!==50)break;o.interrupts.push(Mo.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Wo.fromPartial(t??{})},fromPartial(t){let e=Pc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.threadId=t.threadId??"",e.runId=t.runId??"",e.result=t.result??void 0,e.outcome=t.outcome??"",e.interrupts=t.interrupts?.map(n=>Mo.fromPartial(n))||[],e}};function Dc(){return{baseEvent:void 0,code:void 0,message:""}}var Xo={encode(t,e=new D){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.code!==void 0&&e.uint32(18).string(t.code),t.message!==""&&e.uint32(26).string(t.message),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Dc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.code=n.string();continue;case 3:if(s!==26)break;o.message=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Xo.fromPartial(t??{})},fromPartial(t){let e=Dc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.code=t.code??void 0,e.message=t.message??"",e}};function Uc(){return{baseEvent:void 0,stepName:""}}var Zo={encode(t,e=new D){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.stepName!==""&&e.uint32(18).string(t.stepName),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Uc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.stepName=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Zo.fromPartial(t??{})},fromPartial(t){let e=Uc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function Gc(){return{baseEvent:void 0,stepName:""}}var Ko={encode(t,e=new D){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.stepName!==""&&e.uint32(18).string(t.stepName),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Gc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.stepName=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Ko.fromPartial(t??{})},fromPartial(t){let e=Gc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function Hc(){return{baseEvent:void 0,messageId:void 0,role:void 0,delta:void 0,name:void 0}}var Yo={encode(t,e=new D){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==void 0&&e.uint32(18).string(t.messageId),t.role!==void 0&&e.uint32(26).string(t.role),t.delta!==void 0&&e.uint32(34).string(t.delta),t.name!==void 0&&e.uint32(42).string(t.name),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Hc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.messageId=n.string();continue;case 3:if(s!==26)break;o.role=n.string();continue;case 4:if(s!==34)break;o.delta=n.string();continue;case 5:if(s!==42)break;o.name=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Yo.fromPartial(t??{})},fromPartial(t){let e=Hc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??void 0,e.role=t.role??void 0,e.delta=t.delta??void 0,e.name=t.name??void 0,e}};function Fc(){return{baseEvent:void 0,toolCallId:void 0,toolCallName:void 0,parentMessageId:void 0,delta:void 0}}var qo={encode(t,e=new D){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==void 0&&e.uint32(18).string(t.toolCallId),t.toolCallName!==void 0&&e.uint32(26).string(t.toolCallName),t.parentMessageId!==void 0&&e.uint32(34).string(t.parentMessageId),t.delta!==void 0&&e.uint32(42).string(t.delta),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Fc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.toolCallId=n.string();continue;case 3:if(s!==26)break;o.toolCallName=n.string();continue;case 4:if(s!==34)break;o.parentMessageId=n.string();continue;case 5:if(s!==42)break;o.delta=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return qo.fromPartial(t??{})},fromPartial(t){let e=Fc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??void 0,e.toolCallName=t.toolCallName??void 0,e.parentMessageId=t.parentMessageId??void 0,e.delta=t.delta??void 0,e}};function $c(){return{textMessageStart:void 0,textMessageContent:void 0,textMessageEnd:void 0,toolCallStart:void 0,toolCallArgs:void 0,toolCallEnd:void 0,stateSnapshot:void 0,stateDelta:void 0,messagesSnapshot:void 0,raw:void 0,custom:void 0,runStarted:void 0,runFinished:void 0,runError:void 0,stepStarted:void 0,stepFinished:void 0,textMessageChunk:void 0,toolCallChunk:void 0}}var zc={encode(t,e=new D){return t.textMessageStart!==void 0&&Lo.encode(t.textMessageStart,e.uint32(10).fork()).join(),t.textMessageContent!==void 0&&Po.encode(t.textMessageContent,e.uint32(18).fork()).join(),t.textMessageEnd!==void 0&&Do.encode(t.textMessageEnd,e.uint32(26).fork()).join(),t.toolCallStart!==void 0&&Uo.encode(t.toolCallStart,e.uint32(34).fork()).join(),t.toolCallArgs!==void 0&&Go.encode(t.toolCallArgs,e.uint32(42).fork()).join(),t.toolCallEnd!==void 0&&Ho.encode(t.toolCallEnd,e.uint32(50).fork()).join(),t.stateSnapshot!==void 0&&Fo.encode(t.stateSnapshot,e.uint32(58).fork()).join(),t.stateDelta!==void 0&&$o.encode(t.stateDelta,e.uint32(66).fork()).join(),t.messagesSnapshot!==void 0&&zo.encode(t.messagesSnapshot,e.uint32(74).fork()).join(),t.raw!==void 0&&Bo.encode(t.raw,e.uint32(82).fork()).join(),t.custom!==void 0&&Vo.encode(t.custom,e.uint32(90).fork()).join(),t.runStarted!==void 0&&jo.encode(t.runStarted,e.uint32(98).fork()).join(),t.runFinished!==void 0&&Wo.encode(t.runFinished,e.uint32(106).fork()).join(),t.runError!==void 0&&Xo.encode(t.runError,e.uint32(114).fork()).join(),t.stepStarted!==void 0&&Zo.encode(t.stepStarted,e.uint32(122).fork()).join(),t.stepFinished!==void 0&&Ko.encode(t.stepFinished,e.uint32(130).fork()).join(),t.textMessageChunk!==void 0&&Yo.encode(t.textMessageChunk,e.uint32(138).fork()).join(),t.toolCallChunk!==void 0&&qo.encode(t.toolCallChunk,e.uint32(146).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=$c();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.textMessageStart=Lo.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.textMessageContent=Po.decode(n,n.uint32());continue;case 3:if(s!==26)break;o.textMessageEnd=Do.decode(n,n.uint32());continue;case 4:if(s!==34)break;o.toolCallStart=Uo.decode(n,n.uint32());continue;case 5:if(s!==42)break;o.toolCallArgs=Go.decode(n,n.uint32());continue;case 6:if(s!==50)break;o.toolCallEnd=Ho.decode(n,n.uint32());continue;case 7:if(s!==58)break;o.stateSnapshot=Fo.decode(n,n.uint32());continue;case 8:if(s!==66)break;o.stateDelta=$o.decode(n,n.uint32());continue;case 9:if(s!==74)break;o.messagesSnapshot=zo.decode(n,n.uint32());continue;case 10:if(s!==82)break;o.raw=Bo.decode(n,n.uint32());continue;case 11:if(s!==90)break;o.custom=Vo.decode(n,n.uint32());continue;case 12:if(s!==98)break;o.runStarted=jo.decode(n,n.uint32());continue;case 13:if(s!==106)break;o.runFinished=Wo.decode(n,n.uint32());continue;case 14:if(s!==114)break;o.runError=Xo.decode(n,n.uint32());continue;case 15:if(s!==122)break;o.stepStarted=Zo.decode(n,n.uint32());continue;case 16:if(s!==130)break;o.stepFinished=Ko.decode(n,n.uint32());continue;case 17:if(s!==138)break;o.textMessageChunk=Yo.decode(n,n.uint32());continue;case 18:if(s!==146)break;o.toolCallChunk=qo.decode(n,n.uint32());continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return zc.fromPartial(t??{})},fromPartial(t){let e=$c();return e.textMessageStart=t.textMessageStart!==void 0&&t.textMessageStart!==null?Lo.fromPartial(t.textMessageStart):void 0,e.textMessageContent=t.textMessageContent!==void 0&&t.textMessageContent!==null?Po.fromPartial(t.textMessageContent):void 0,e.textMessageEnd=t.textMessageEnd!==void 0&&t.textMessageEnd!==null?Do.fromPartial(t.textMessageEnd):void 0,e.toolCallStart=t.toolCallStart!==void 0&&t.toolCallStart!==null?Uo.fromPartial(t.toolCallStart):void 0,e.toolCallArgs=t.toolCallArgs!==void 0&&t.toolCallArgs!==null?Go.fromPartial(t.toolCallArgs):void 0,e.toolCallEnd=t.toolCallEnd!==void 0&&t.toolCallEnd!==null?Ho.fromPartial(t.toolCallEnd):void 0,e.stateSnapshot=t.stateSnapshot!==void 0&&t.stateSnapshot!==null?Fo.fromPartial(t.stateSnapshot):void 0,e.stateDelta=t.stateDelta!==void 0&&t.stateDelta!==null?$o.fromPartial(t.stateDelta):void 0,e.messagesSnapshot=t.messagesSnapshot!==void 0&&t.messagesSnapshot!==null?zo.fromPartial(t.messagesSnapshot):void 0,e.raw=t.raw!==void 0&&t.raw!==null?Bo.fromPartial(t.raw):void 0,e.custom=t.custom!==void 0&&t.custom!==null?Vo.fromPartial(t.custom):void 0,e.runStarted=t.runStarted!==void 0&&t.runStarted!==null?jo.fromPartial(t.runStarted):void 0,e.runFinished=t.runFinished!==void 0&&t.runFinished!==null?Wo.fromPartial(t.runFinished):void 0,e.runError=t.runError!==void 0&&t.runError!==null?Xo.fromPartial(t.runError):void 0,e.stepStarted=t.stepStarted!==void 0&&t.stepStarted!==null?Zo.fromPartial(t.stepStarted):void 0,e.stepFinished=t.stepFinished!==void 0&&t.stepFinished!==null?Ko.fromPartial(t.stepFinished):void 0,e.textMessageChunk=t.textMessageChunk!==void 0&&t.textMessageChunk!==null?Yo.fromPartial(t.textMessageChunk):void 0,e.toolCallChunk=t.toolCallChunk!==void 0&&t.toolCallChunk!==null?qo.fromPartial(t.toolCallChunk):void 0,e}};function um(t){let e=globalThis.Number(t.toString());if(e>globalThis.Number.MAX_SAFE_INTEGER)throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");if(e<globalThis.Number.MIN_SAFE_INTEGER)throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");return e}var xo=t=>{if(!(!t||typeof t!="object")){if(t.data)return{type:"data",value:t.data.value,mimeType:t.data.mimeType};if(t.url)return{type:"url",value:t.url.value,mimeType:t.url.mimeType}}},dm=t=>{if(!(!t||typeof t!="object")){if(t.text)return{type:"text",text:t.text.text};if(t.image)return{type:"image",source:xo(t.image.source),metadata:t.image.metadata};if(t.audio)return{type:"audio",source:xo(t.audio.source),metadata:t.audio.metadata};if(t.video)return{type:"video",source:xo(t.video.source),metadata:t.video.metadata};if(t.document)return{type:"document",source:xo(t.document.source),metadata:t.document.metadata}}};function Bc(t){let e=zc.decode(t),n=Object.values(e).find(r=>r!==void 0);if(!n)throw new Error("Invalid event");if(n.type=cm[n.baseEvent.type],n.timestamp=n.baseEvent.timestamp,n.rawEvent=n.baseEvent.rawEvent,delete n.baseEvent,n.type===v.MESSAGES_SNAPSHOT)for(let r of n.messages){let o=r;if(o.role==="user"&&Array.isArray(o.contentParts)){let s=o.contentParts.map(i=>dm(i)).filter(i=>i!==void 0);s.length>0&&(o.content=s)}Array.isArray(o.contentParts)&&o.contentParts.length===0&&(o.contentParts=void 0),o.toolCalls?.length===0&&(o.toolCalls=void 0)}if(n.type===v.RUN_FINISHED){let r=n,o=typeof r.outcome=="string"&&r.outcome!==""?r.outcome:void 0,s=Array.isArray(r.interrupts)?r.interrupts:[];delete r.interrupts,o==="interrupt"?r.outcome={type:"interrupt",interrupts:s}:o==="success"?r.outcome={type:"success"}:delete r.outcome}if(n.type===v.STATE_DELTA)for(let r of n.delta)r.op=lm[r.op].toLowerCase(),Object.keys(r).forEach(o=>{r[o]===void 0&&delete r[o]});return Object.keys(n).forEach(r=>{n[r]===void 0&&delete n[r]}),Dr.parse(n)}var Oi="application/vnd.ag-ui.event+proto";var fm=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,Mi=t=>{if(typeof t!="string")throw new TypeError("Invalid argument expected string");let e=t.match(fm);if(!e)throw new Error(`Invalid argument not valid semver ('${t}' received)`);return e.shift(),e},Vc=t=>t==="*"||t==="x"||t==="X",jc=t=>{let e=parseInt(t,10);return isNaN(e)?t:e},hm=(t,e)=>typeof t!=typeof e?[String(t),String(e)]:[t,e],mm=(t,e)=>{if(Vc(t)||Vc(e))return 0;let[n,r]=hm(jc(t),jc(e));return n>r?1:n<r?-1:0},Li=(t,e)=>{for(let n=0;n<Math.max(t.length,e.length);n++){let r=mm(t[n]||"0",e[n]||"0");if(r!==0)return r}return 0};var Qn=(t,e)=>{let n=Mi(t),r=Mi(e),o=n.pop(),s=r.pop(),i=Li(n,r);return i!==0?i:o&&s?Li(o.split("."),s.split(".")):o||s?o?-1:1:0};var B=t=>{if(typeof structuredClone=="function")return structuredClone(t);try{return JSON.parse(JSON.stringify(t))}catch{return Array.isArray(t)?[...t]:{...t}}};function ze(){return ht()}function Ui(t){if(Object.freeze(t),typeof t=="object"&&t)for(let e of Object.values(t))typeof e=="object"&&e&&!Object.isFrozen(e)&&Ui(e);return t}async function W(t,e,n,r){let o=typeof process<"u"&&process.env!==void 0,s=o&&!!process.env.VITEST_WORKER_ID,i=o&&!!process.env.VITEST_WORKER_ID,a=B(e),u=B(n),l=a,p=u,m;for(let x of t)try{i&&(Ui(l),Ui(p));let f=await r(x,l,p);if(f===void 0)continue;if(f.messages!==void 0&&f.messages!==l&&(l=B(f.messages)),f.state!==void 0&&f.state!==p&&(p=B(f.state)),m=f.stopPropagation,m===!0)break}catch(f){if(i&&f instanceof TypeError){if(s)throw f;console.error("AG-UI: Subscriber attempted to mutate frozen inputs in-place. Return mutations via AgentStateMutation instead of mutating directly.",f)}else s||console.error("Subscriber error:",f);continue}return{...l===a?{}:{messages:i&&Object.isFrozen(l)?B(l):l},...p===u?{}:{state:i&&Object.isFrozen(p)?B(p):p},...m===void 0?{}:{stopPropagation:m}}}function Jo(t){if(!t)return{enabled:!1,events:!1,lifecycle:!1,verbose:!1};if(t===!0)return{enabled:!0,events:!0,lifecycle:!0,verbose:!0};let e=t.events??!0,n=t.lifecycle??!0,r=t.verbose??!1;return{enabled:e||n,events:e,lifecycle:n,verbose:r}}function er(t){if(t instanceof Gi)return t;if(t===!0)return new Gi(Jo(!0))}var Gi=class{constructor(t){this.config=t}event(t,e,n,r){this.config.events&&(this.config.verbose?console.debug(`[${t}] ${e}`,typeof n=="string"?n:JSON.stringify(n)):console.debug(`[${t}] ${e}`,r??n))}lifecycle(t,e,n){this.config.lifecycle&&(n?console.debug(`[${t}] ${e}`,n):console.debug(`[${t}] ${e}`))}get eventsEnabled(){return this.config.events}get lifecycleEnabled(){return this.config.lifecycle}get enabled(){return this.config.enabled}};function Pi(t){return t.enabled?new Gi(t):void 0}function gm(t,e,n){if(e){let o=t.find(i=>i.id===e);if(o?.role==="assistant")return o;o&&console.warn(`TOOL_CALL_START: parentMessageId '${e}' matches a '${o.role}' message, not assistant \u2014 falling back to toolCallId`);let s={id:o?n:e,role:"assistant",toolCalls:[]};return t.push(s),s}let r={id:n,role:"assistant",toolCalls:[]};return t.push(r),r}var qc=(t,e,n,r,o)=>{let s=er(o),i=B(n.messages),a=B(t.state),u={},l=m=>{m.messages!==void 0&&(i=m.messages,u.messages=m.messages),m.state!==void 0&&(a=m.state,u.state=m.state)},p=()=>{let m=B(u);return u={},m.messages!==void 0||m.state!==void 0?te(m):Qr};return e.pipe(mo(async m=>{let x=await W(r,i,a,(f,h,g)=>f.onEvent?.({event:m,agent:n,input:t,messages:h,state:g}));if(l(x),x.stopPropagation===!0?s?.event("APPLY","Event dropped:",m,{type:m.type,reason:"stopPropagation by subscriber"}):s?.event("APPLY","Event applied:",m,{type:m.type,subscribers:r.length}),x.stopPropagation===!0)return p();switch(m.type){case v.TEXT_MESSAGE_START:{let f=await W(r,i,a,(h,g,T)=>h.onTextMessageStartEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(l(f),f.stopPropagation!==!0){let{messageId:h,role:g="assistant",name:T}=m;if(!i.find(S=>S.id===h)){let S={id:h,role:g,content:"",...T!==void 0&&{name:T}};i.push(S),l({messages:i})}}return p()}case v.TEXT_MESSAGE_CONTENT:{let{messageId:f,delta:h}=m,g=i.find(S=>S.id===f);if(!g)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${f}'`),p();let T=await W(r,i,a,(S,b,H)=>S.onTextMessageContentEvent?.({event:m,messages:b,state:H,agent:n,input:t,textMessageBuffer:typeof g.content=="string"?g.content:""}));return l(T),T.stopPropagation!==!0&&(g.content=`${typeof g.content=="string"?g.content:""}${h}`,l({messages:i})),p()}case v.TEXT_MESSAGE_END:{let{messageId:f}=m,h=i.find(g=>g.id===f);return h?(l(await W(r,i,a,(g,T,S)=>g.onTextMessageEndEvent?.({event:m,messages:T,state:S,agent:n,input:t,textMessageBuffer:typeof h.content=="string"?h.content:""}))),await Promise.all(r.map(g=>{g.onNewMessage?.({message:h,messages:i,state:a,agent:n,input:t})})),p()):(console.warn(`TEXT_MESSAGE_END: No message found with ID '${f}'`),p())}case v.TOOL_CALL_START:{let f=await W(r,i,a,(h,g,T)=>h.onToolCallStartEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(l(f),f.stopPropagation!==!0){let{toolCallId:h,toolCallName:g,parentMessageId:T}=m,S=gm(i,T,h);S.toolCalls??=[],S.toolCalls.push({id:h,type:"function",function:{name:g,arguments:""}}),l({messages:i})}return p()}case v.TOOL_CALL_ARGS:{let{toolCallId:f,delta:h}=m,g=i.find(b=>b.toolCalls?.some(H=>H.id===f));if(!g)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${f}'`),p();let T=g.toolCalls?.find(b=>b.id===f);if(!T)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${f}'`),p();let S=await W(r,i,a,(b,H,X)=>{let ae=T.function.arguments,ee=T.function.name,ut={};try{ut=vo(ae)}catch{}return b.onToolCallArgsEvent?.({event:m,messages:H,state:X,agent:n,input:t,toolCallBuffer:ae,toolCallName:ee,partialToolCallArgs:ut})});return l(S),S.stopPropagation!==!0&&(T.function.arguments+=h,l({messages:i})),p()}case v.TOOL_CALL_END:{let{toolCallId:f}=m,h=i.find(T=>T.toolCalls?.some(S=>S.id===f));if(!h)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${f}'`),p();let g=h.toolCalls?.find(T=>T.id===f);return g?(l(await W(r,i,a,(T,S,b)=>{let H=g.function.arguments,X=g.function.name,ae={};try{ae=JSON.parse(H)}catch{}return T.onToolCallEndEvent?.({event:m,messages:S,state:b,agent:n,input:t,toolCallName:X,toolCallArgs:ae})})),await Promise.all(r.map(T=>{T.onNewToolCall?.({toolCall:g,messages:i,state:a,agent:n,input:t})})),p()):(console.warn(`TOOL_CALL_END: No tool call found with ID '${f}'`),p())}case v.TOOL_CALL_RESULT:{let f=await W(r,i,a,(h,g,T)=>h.onToolCallResultEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(l(f),f.stopPropagation!==!0){let{messageId:h,toolCallId:g,content:T,role:S}=m,b={id:h,toolCallId:g,role:S||"tool",content:T};i.push(b),await Promise.all(r.map(H=>{H.onNewMessage?.({message:b,messages:i,state:a,agent:n,input:t})})),l({messages:i})}return p()}case v.STATE_SNAPSHOT:{let f=await W(r,i,a,(h,g,T)=>h.onStateSnapshotEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(l(f),f.stopPropagation!==!0){let{snapshot:h}=m;a=h,l({state:a})}return p()}case v.STATE_DELTA:{let f=await W(r,i,a,(h,g,T)=>h.onStateDeltaEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(l(f),f.stopPropagation!==!0){let{delta:h}=m;try{a=Vr.applyPatch(a,h,!0,!1).newDocument,l({state:a})}catch(g){let T=g instanceof Error?g.message:String(g);console.warn(`Failed to apply state patch:
702
899
  Current state: ${JSON.stringify(a,null,2)}
703
900
  Patch operations: ${JSON.stringify(h,null,2)}
704
- Error: ${_}`)}}return p()}case v.MESSAGES_SNAPSHOT:{let f=await W(r,i,a,(h,g,_)=>h.onMessagesSnapshotEvent?.({event:m,messages:g,state:_,agent:n,input:e}));if(c(f),f.stopPropagation!==!0){let{messages:h}=m,g=new Map(h.map(b=>[b.id,b])),_=b=>b==="activity"||b==="reasoning";i=i.filter(b=>_(b.role)||g.has(b.id)).map(b=>_(b.role)?b:g.get(b.id));let S=new Set(i.map(b=>b.id));for(let b of h)S.has(b.id)||i.push(b);c({messages:i})}return p()}case v.ACTIVITY_SNAPSHOT:{let f=m,h=i.findIndex(F=>F.id===f.messageId),g=h>=0?i[h]:void 0,_=g?.role==="activity"?g:void 0,S=f.replace??!0,b=await W(r,i,a,(F,X,ae)=>F.onActivitySnapshotEvent?.({event:f,messages:X,state:ae,agent:n,input:e,activityMessage:_,existingMessage:g}));if(c(b),b.stopPropagation!==!0){let F={id:f.messageId,role:"activity",activityType:f.activityType,content:B(f.content)},X;h===-1?(i.push(F),X=F):_?S&&(i[h]={..._,activityType:f.activityType,content:B(f.content)}):S&&(i[h]=F,X=F),c({messages:i}),X&&await Promise.all(r.map(ae=>ae.onNewMessage?.({message:X,messages:i,state:a,agent:n,input:e})))}return p()}case v.ACTIVITY_DELTA:{let f=m,h=i.findIndex(b=>b.id===f.messageId);if(h===-1)return p();let g=i[h];if(g.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${f.messageId}' is not an activity message`),p();let _=g,S=await W(r,i,a,(b,F,X)=>b.onActivityDeltaEvent?.({event:f,messages:F,state:X,agent:n,input:e,activityMessage:_}));if(c(S),S.stopPropagation!==!0)try{let b=B(_.content??{}),F=$r.applyPatch(b,f.patch??[],!0,!1).newDocument;i[h]={..._,content:B(F),activityType:f.activityType},c({messages:i})}catch(b){let F=b instanceof Error?b.message:String(b);console.warn(`Failed to apply activity patch for '${f.messageId}': ${F}`)}return p()}case v.RAW:return c(await W(r,i,a,(f,h,g)=>f.onRawEvent?.({event:m,messages:h,state:g,agent:n,input:e}))),p();case v.CUSTOM:return c(await W(r,i,a,(f,h,g)=>f.onCustomEvent?.({event:m,messages:h,state:g,agent:n,input:e}))),p();case v.RUN_STARTED:{let f=await W(r,i,a,(h,g,_)=>h.onRunStartedEvent?.({event:m,messages:g,state:_,agent:n,input:e}));if(c(f),f.stopPropagation!==!0){let h=m;if(h.input?.messages){for(let g of h.input.messages)i.find(_=>_.id===g.id)||i.push(g);c({messages:i})}}return p()}case v.RUN_FINISHED:{let f=m,h=f.outcome?.type==="interrupt"?{event:f,outcome:"interrupt",interrupts:f.outcome.interrupts}:{event:f,outcome:"success",result:f.result},g=await W(r,i,a,(_,S,b)=>_.onRunFinishedEvent?.({...h,messages:S,state:b,agent:n,input:e}));return c(g),g.stopPropagation!==!0&&(n.pendingInterrupts=h.outcome==="interrupt"?[...h.interrupts]:[]),p()}case v.RUN_ERROR:return c(await W(r,i,a,(f,h,g)=>f.onRunErrorEvent?.({event:m,messages:h,state:g,agent:n,input:e}))),p();case v.STEP_STARTED:return c(await W(r,i,a,(f,h,g)=>f.onStepStartedEvent?.({event:m,messages:h,state:g,agent:n,input:e}))),p();case v.STEP_FINISHED:return c(await W(r,i,a,(f,h,g)=>f.onStepFinishedEvent?.({event:m,messages:h,state:g,agent:n,input:e}))),p();case v.TEXT_MESSAGE_CHUNK:throw Error("TEXT_MESSAGE_CHUNK must be tranformed before being applied");case v.TOOL_CALL_CHUNK:throw Error("TOOL_CALL_CHUNK must be tranformed before being applied");case v.THINKING_START:return p();case v.THINKING_END:return p();case v.THINKING_TEXT_MESSAGE_START:return p();case v.THINKING_TEXT_MESSAGE_CONTENT:return p();case v.THINKING_TEXT_MESSAGE_END:return p();case v.REASONING_START:return c(await W(r,i,a,(f,h,g)=>f.onReasoningStartEvent?.({event:m,messages:h,state:g,agent:n,input:e}))),p();case v.REASONING_MESSAGE_START:{let f=await W(r,i,a,(h,g,_)=>h.onReasoningMessageStartEvent?.({event:m,messages:g,state:_,agent:n,input:e}));if(c(f),f.stopPropagation!==!0){let{messageId:h}=m;if(!i.find(g=>g.id===h)){let g={id:h,role:"reasoning",content:""};i.push(g),c({messages:i})}}return p()}case v.REASONING_MESSAGE_CONTENT:{let{messageId:f,delta:h}=m,g=i.find(S=>S.id===f);if(!g)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${f}'`),p();let _=await W(r,i,a,(S,b,F)=>S.onReasoningMessageContentEvent?.({event:m,messages:b,state:F,agent:n,input:e,reasoningMessageBuffer:typeof g.content=="string"?g.content:""}));return c(_),_.stopPropagation!==!0&&(g.content=`${typeof g.content=="string"?g.content:""}${h}`,c({messages:i})),p()}case v.REASONING_MESSAGE_END:{let{messageId:f}=m,h=i.find(g=>g.id===f);return h?(c(await W(r,i,a,(g,_,S)=>g.onReasoningMessageEndEvent?.({event:m,messages:_,state:S,agent:n,input:e,reasoningMessageBuffer:typeof h.content=="string"?h.content:""}))),await Promise.all(r.map(g=>{g.onNewMessage?.({message:h,messages:i,state:a,agent:n,input:e})})),p()):(console.warn(`REASONING_MESSAGE_END: No message found with ID '${f}'`),p())}case v.REASONING_MESSAGE_CHUNK:throw Error("REASONING_MESSAGE_CHUNK must be transformed before being applied");case v.REASONING_END:return c(await W(r,i,a,(f,h,g)=>f.onReasoningEndEvent?.({event:m,messages:h,state:g,agent:n,input:e}))),p();case v.REASONING_ENCRYPTED_VALUE:{let{subtype:f,entityId:h,encryptedValue:g}=m,_=await W(r,i,a,(S,b,F)=>S.onReasoningEncryptedValueEvent?.({event:m,messages:b,state:F,agent:n,input:e}));if(c(_),_.stopPropagation!==!0){let S=!1;if(f==="tool-call"){for(let b of i)if(b.role==="assistant"&&b.toolCalls){let F=b.toolCalls.find(X=>X.id===h);if(F){F.encryptedValue=g,S=!0;break}}}else{let b=i.find(F=>F.id===h);b?.role!=="activity"&&b&&(b.encryptedValue=g,S=!0)}S&&(u.messages=i)}return p()}}return m.type,p()}),hi(),r.length>0?mi({}):m=>m)},Mi=e=>t=>{let n=Qn(e),r=new Map,o=new Map,s=!1,i=!1,a=!1,u=new Map,c=!1,p=!1,m=!1,x=()=>{r.clear(),o.clear(),u.clear(),c=!1,p=!1,s=!1,i=!1,m=!0};return t.pipe(Ae(f=>{let h=f.type;if(n?.event("VERIFY","Event:",f,{type:f.type}),i)return Q(()=>new q(`Cannot send event type '${h}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(s&&h!==v.RUN_ERROR&&h!==v.RUN_STARTED)return Q(()=>new q(`Cannot send event type '${h}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(a){if(h===v.RUN_STARTED){if(m&&!s)return Q(()=>new q("Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run."));s&&x()}}else if(a=!0,h!==v.RUN_STARTED&&h!==v.RUN_ERROR)return Q(()=>new q("First event must be 'RUN_STARTED'"));switch(h){case v.TEXT_MESSAGE_START:{let g=f.messageId;return r.has(g)?Q(()=>new q(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${g}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(r.set(g,!0),te(f))}case v.TEXT_MESSAGE_CONTENT:{let g=f.messageId;return r.has(g)?te(f):Q(()=>new q(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${g}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case v.TEXT_MESSAGE_END:{let g=f.messageId;return r.has(g)?(r.delete(g),te(f)):Q(()=>new q(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${g}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case v.TOOL_CALL_START:{let g=f.toolCallId;return o.has(g)?Q(()=>new q(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${g}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(o.set(g,!0),te(f))}case v.TOOL_CALL_ARGS:{let g=f.toolCallId;return o.has(g)?te(f):Q(()=>new q(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${g}'. Start a tool call with 'TOOL_CALL_START' first.`))}case v.TOOL_CALL_END:{let g=f.toolCallId;return o.has(g)?(o.delete(g),te(f)):Q(()=>new q(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${g}'. A 'TOOL_CALL_START' event must be sent first.`))}case v.STEP_STARTED:{let g=f.stepName;return u.has(g)?Q(()=>new q(`Step "${g}" is already active for 'STEP_STARTED'`)):(u.set(g,!0),te(f))}case v.STEP_FINISHED:{let g=f.stepName;return u.has(g)?(u.delete(g),te(f)):Q(()=>new q(`Cannot send 'STEP_FINISHED' for step "${g}" that was not started`))}case v.RUN_STARTED:return m=!0,te(f);case v.RUN_FINISHED:if(u.size>0){let g=Array.from(u.keys()).join(", ");return Q(()=>new q(`Cannot send 'RUN_FINISHED' while steps are still active: ${g}`))}if(r.size>0){let g=Array.from(r.keys()).join(", ");return Q(()=>new q(`Cannot send 'RUN_FINISHED' while text messages are still active: ${g}`))}if(o.size>0){let g=Array.from(o.keys()).join(", ");return Q(()=>new q(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${g}`))}return s=!0,te(f);case v.RUN_ERROR:return i=!0,te(f);case v.CUSTOM:return te(f);case v.THINKING_TEXT_MESSAGE_START:return c?p?Q(()=>new q("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(p=!0,te(f)):Q(()=>new q("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case v.THINKING_TEXT_MESSAGE_CONTENT:return p?te(f):Q(()=>new q("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case v.THINKING_TEXT_MESSAGE_END:return p?(p=!1,te(f)):Q(()=>new q("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case v.THINKING_START:return c?Q(()=>new q("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(c=!0,te(f));case v.THINKING_END:return c?(c=!1,te(f)):Q(()=>new q("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return te(f)}}))},Xt=(function(e){return e.HEADERS="headers",e.DATA="data",e})({}),um=e=>uo(()=>Vt(e())).pipe(gi(t=>{if(!t.ok){let o=t.headers.get("content-type")||"";return Vt(t.text()).pipe(Ae(s=>{let i=s;if(o.includes("application/json"))try{i=JSON.parse(s)}catch{}let a=Error(`HTTP ${t.status}: ${typeof i=="string"?i:JSON.stringify(i)}`);return a.status=t.status,a.payload=i,Q(()=>a)}))}let n={type:Xt.HEADERS,status:t.status,headers:t.headers},r=t.body?.getReader();return r?new J(o=>(o.next(n),(async()=>{try{for(;;){let{done:s,value:i}=await r.read();if(s)break;let a={type:Xt.DATA,data:i};o.next(a)}o.complete()}catch(s){o.error(s)}})(),()=>{r.cancel().catch(s=>{if(s?.name!=="AbortError")throw s})})):Q(()=>Error("Failed to getReader() from response"))})),dm=(e,t)=>{let n=Qn(t),r=new rt,o=new TextDecoder("utf-8",{fatal:!1}),s="";e.subscribe({next:a=>{if(a.type!==Xt.HEADERS&&a.type===Xt.DATA&&a.data){let u=o.decode(a.data,{stream:!0});s+=u;let c=s.split(/\n\n/);s=c.pop()||"";for(let p of c)i(p)}},error:a=>r.error(a),complete:()=>{s&&(s+=o.decode(),i(s)),r.complete()}});function i(a){let u=a.split(`
705
- `),c=[];for(let p of u)p.startsWith("data:")&&c.push(p.slice(5).replace(/^ /,""));if(c.length>0)try{let p=c.join(`
706
- `),m=JSON.parse(p);n?.event("SSE","Event received:",m,{type:m.type}),r.next(m)}catch(p){r.error(p)}}return r.asObservable()},pm=e=>{let t=new rt,n=new Uint8Array;e.subscribe({next:o=>{if(o.type!==Xt.HEADERS&&o.type===Xt.DATA&&o.data){let s=new Uint8Array(n.length+o.data.length);s.set(n,0),s.set(o.data,n.length),n=s,r()}},error:o=>t.error(o),complete:()=>{if(n.length>0)try{r()}catch{console.warn("Incomplete or invalid protocol buffer data at stream end")}t.complete()}});function r(){for(;n.length>=4;){let o=4+new DataView(n.buffer,n.byteOffset,4).getUint32(0,!1);if(n.length<o)break;try{let s=n.slice(4,o),i=Fc(s);t.next(i),n=n.slice(o)}catch(s){let i=s instanceof Error?s.message:String(s);t.error(Error(`Failed to decode protocol buffer message: ${i}`));return}}}return t.asObservable()},fm=(e,t)=>{let n=Qn(t),r=new rt,o=new Kr,s=!1;return e.subscribe({next:i=>{if(o.next(i),i.type===Xt.HEADERS&&!s){s=!0;let a=i.headers.get("content-type");n?.lifecycle("HTTP","Stream format detected:",{contentType:a,parser:a===Ci?"protobuf":"sse"}),a===Ci?pm(o).subscribe({next:u=>r.next(u),error:u=>r.error(u),complete:()=>r.complete()}):dm(o,n).subscribe({next:u=>{try{let c=Mr.parse(u);n?.event("HTTP","Event validated:",c,{type:c.type,valid:!0}),r.next(c)}catch(c){n?.event("HTTP","Event invalid:",{json:u,error:String(c)}),r.error(c)}},error:u=>{if(u?.name==="AbortError"){r.next({type:v.RUN_ERROR,message:u.message||"Request aborted",code:"abort",rawEvent:u}),r.complete();return}return r.error(u)},complete:()=>r.complete()})}else s||r.error(Error("No headers event received before data events"))},error:i=>{o.error(i),r.error(i)},complete:()=>{o.complete()}}),r.asObservable()},K=l.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),hm=l.enum(["LangGraphInterruptEvent","PredictState","Exit"]),mm=l.object({type:l.literal(K.enum.TextMessageStart),messageId:l.string(),parentMessageId:l.string().optional(),role:l.string().optional()}),gm=l.object({type:l.literal(K.enum.TextMessageContent),messageId:l.string(),content:l.string()}),vm=l.object({type:l.literal(K.enum.TextMessageEnd),messageId:l.string()}),ym=l.object({type:l.literal(K.enum.ActionExecutionStart),actionExecutionId:l.string(),actionName:l.string(),parentMessageId:l.string().optional()}),bm=l.object({type:l.literal(K.enum.ActionExecutionArgs),actionExecutionId:l.string(),args:l.string()}),xm=l.object({type:l.literal(K.enum.ActionExecutionEnd),actionExecutionId:l.string()}),Em=l.object({type:l.literal(K.enum.ActionExecutionResult),actionName:l.string(),actionExecutionId:l.string(),result:l.string()}),_m=l.object({type:l.literal(K.enum.AgentStateMessage),threadId:l.string(),agentName:l.string(),nodeName:l.string(),runId:l.string(),active:l.boolean(),role:l.string(),state:l.string(),running:l.boolean()}),Tm=l.object({type:l.literal(K.enum.MetaEvent),name:hm,value:l.any()}),Sm=l.object({type:l.literal(K.enum.RunError),message:l.string(),code:l.string().optional()});l.discriminatedUnion("type",[mm,gm,vm,ym,bm,xm,Em,_m,Tm,Sm]),l.object({id:l.string(),role:l.string(),content:l.string(),parentMessageId:l.string().optional()}),l.object({id:l.string(),name:l.string(),arguments:l.any(),parentMessageId:l.string().optional()}),l.object({id:l.string(),result:l.any(),actionExecutionId:l.string(),actionName:l.string()});var wm=e=>{if(typeof e=="string")return e;if(!Array.isArray(e))return;let t=e.filter(n=>n.type==="text").map(n=>n.text).filter(n=>n.length>0);if(t.length!==0)return t.join(`
707
- `)},km=(e,t,n)=>r=>{let o={},s=!0,i=!0,a="",u=null,c=null,p=[],m={},x=f=>{typeof f=="object"&&f&&("messages"in f&&delete f.messages,o=f)};return r.pipe(Ae(f=>{switch(f.type){case v.TEXT_MESSAGE_START:{let h=f;return[{type:K.enum.TextMessageStart,messageId:h.messageId,role:h.role}]}case v.TEXT_MESSAGE_CONTENT:{let h=f;return[{type:K.enum.TextMessageContent,messageId:h.messageId,content:h.delta}]}case v.TEXT_MESSAGE_END:{let h=f;return[{type:K.enum.TextMessageEnd,messageId:h.messageId}]}case v.TOOL_CALL_START:{let h=f;return p.push({id:h.toolCallId,type:"function",function:{name:h.toolCallName,arguments:""}}),i=!0,m[h.toolCallId]=h.toolCallName,[{type:K.enum.ActionExecutionStart,actionExecutionId:h.toolCallId,actionName:h.toolCallName,parentMessageId:h.parentMessageId}]}case v.TOOL_CALL_ARGS:{let h=f,g=p.find(S=>S.id===h.toolCallId);if(!g)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${h.toolCallId}'`),[];g.function.arguments+=h.delta;let _=!1;if(c){let S=c.find(b=>b.tool==g.function.name);if(S)try{let b=JSON.parse(ho(g.function.arguments));S.tool_argument&&S.tool_argument in b?(x({...o,[S.state_key]:b[S.tool_argument]}),_=!0):S.tool_argument||(x({...o,[S.state_key]:b}),_=!0)}catch{}}return[{type:K.enum.ActionExecutionArgs,actionExecutionId:h.toolCallId,args:h.delta},..._?[{type:K.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:a,runId:t,running:s,role:"assistant",state:JSON.stringify(o),active:i}]:[]]}case v.TOOL_CALL_END:{let h=f;return[{type:K.enum.ActionExecutionEnd,actionExecutionId:h.toolCallId}]}case v.TOOL_CALL_RESULT:{let h=f;return[{type:K.enum.ActionExecutionResult,actionExecutionId:h.toolCallId,result:h.content,actionName:m[h.toolCallId]||"unknown"}]}case v.RAW:return[];case v.CUSTOM:{let h=f;switch(h.name){case"Exit":s=!1;break;case"PredictState":c=h.value;break}return[{type:K.enum.MetaEvent,name:h.name,value:h.value}]}case v.STATE_SNAPSHOT:return x(f.snapshot),[{type:K.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:a,runId:t,running:s,role:"assistant",state:JSON.stringify(o),active:i}];case v.STATE_DELTA:{let h=f,g=$r.applyPatch(o,h.delta,!0,!1);return g?(x(g.newDocument),[{type:K.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:a,runId:t,running:s,role:"assistant",state:JSON.stringify(o),active:i}]):[]}case v.MESSAGES_SNAPSHOT:return u=f.messages,[{type:K.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:a,runId:t,running:s,role:"assistant",state:JSON.stringify({...o,...u?{messages:u}:{}}),active:!0}];case v.RUN_STARTED:return[];case v.RUN_FINISHED:return u&&(o.messages=u),Object.keys(o).length===0?[]:[{type:K.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:a,runId:t,running:s,role:"assistant",state:JSON.stringify({...o,...u?{messages:Am(u)}:{}}),active:!1}];case v.RUN_ERROR:{let h=f;return[{type:K.enum.RunError,message:h.message,code:h.code}]}case v.STEP_STARTED:return a=f.stepName,p=[],c=null,[{type:K.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:a,runId:t,running:s,role:"assistant",state:JSON.stringify(o),active:!0}];case v.STEP_FINISHED:return p=[],c=null,[{type:K.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:a,runId:t,running:s,role:"assistant",state:JSON.stringify(o),active:!1}];default:return[]}}))};function Am(e){let t=[];for(let n of e)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let r=wm(n.content);if(r){let o={id:n.id,role:n.role,content:r};t.push(o)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let o of n.toolCalls){let s={id:o.id,name:o.function.name,arguments:JSON.parse(o.function.arguments),parentMessageId:n.id};t.push(s)}}else if(n.role==="tool"){let r="unknown";for(let s of e)if(s.role==="assistant"&&s.toolCalls?.length){for(let i of s.toolCalls)if(i.id===n.toolCallId){r=i.function.name;break}}let o={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:r};t.push(o)}return t}var Yo=e=>t=>{let n=Qn(e),r,o,s,i,a=()=>{if(!r||i!=="text")throw Error("No text message to close");let m={type:v.TEXT_MESSAGE_END,messageId:r.messageId};return i=void 0,r=void 0,n?.event("TRANSFORM","TEXT_MESSAGE_END",m,{messageId:m.messageId}),m},u=()=>{if(!o||i!=="tool")throw Error("No tool call to close");let m={type:v.TOOL_CALL_END,toolCallId:o.toolCallId};return i=void 0,o=void 0,n?.event("TRANSFORM","TOOL_CALL_END",m,{toolCallId:m.toolCallId}),m},c=()=>{if(!s||i!=="reasoning")throw Error("No reasoning message to close");let m={type:v.REASONING_MESSAGE_END,messageId:s.messageId};return i=void 0,s=void 0,n?.event("TRANSFORM","REASONING_MESSAGE_END",m,{messageId:m.messageId}),m},p=()=>i==="text"?[a()]:i==="tool"?[u()]:i==="reasoning"?[c()]:[];return t.pipe(Ae(m=>{switch(m.type){case v.TEXT_MESSAGE_START:case v.TEXT_MESSAGE_CONTENT:case v.TEXT_MESSAGE_END:case v.TOOL_CALL_START:case v.TOOL_CALL_ARGS:case v.TOOL_CALL_END:case v.TOOL_CALL_RESULT:case v.STATE_SNAPSHOT:case v.STATE_DELTA:case v.MESSAGES_SNAPSHOT:case v.CUSTOM:case v.RUN_STARTED:case v.RUN_FINISHED:case v.RUN_ERROR:case v.STEP_STARTED:case v.STEP_FINISHED:case v.THINKING_START:case v.THINKING_END:case v.THINKING_TEXT_MESSAGE_START:case v.THINKING_TEXT_MESSAGE_CONTENT:case v.THINKING_TEXT_MESSAGE_END:case v.REASONING_START:case v.REASONING_MESSAGE_START:case v.REASONING_MESSAGE_CONTENT:case v.REASONING_MESSAGE_END:case v.REASONING_END:return[...p(),m];case v.RAW:case v.ACTIVITY_SNAPSHOT:case v.ACTIVITY_DELTA:case v.REASONING_ENCRYPTED_VALUE:return[m];case v.TEXT_MESSAGE_CHUNK:let x=m,f=[];if((i!=="text"||x.messageId!==void 0&&x.messageId!==r?.messageId)&&f.push(...p()),i!=="text"){if(x.messageId===void 0)throw Error("First TEXT_MESSAGE_CHUNK must have a messageId");r={messageId:x.messageId,name:x.name},i="text";let b={type:v.TEXT_MESSAGE_START,messageId:x.messageId,role:x.role||"assistant",...x.name!==void 0&&{name:x.name}};f.push(b),n?.event("TRANSFORM","TEXT_MESSAGE_START",b,{messageId:x.messageId})}if(x.delta!==void 0){let b={type:v.TEXT_MESSAGE_CONTENT,messageId:r.messageId,delta:x.delta};f.push(b),n?.event("TRANSFORM","TEXT_MESSAGE_CONTENT",b,{messageId:r.messageId})}return f;case v.TOOL_CALL_CHUNK:let h=m,g=[];if((i!=="tool"||h.toolCallId!==void 0&&h.toolCallId!==o?.toolCallId)&&g.push(...p()),i!=="tool"){if(h.toolCallId===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallId");if(h.toolCallName===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallName");o={toolCallId:h.toolCallId,toolCallName:h.toolCallName,parentMessageId:h.parentMessageId},i="tool";let b={type:v.TOOL_CALL_START,toolCallId:h.toolCallId,toolCallName:h.toolCallName,parentMessageId:h.parentMessageId};g.push(b),n?.event("TRANSFORM","TOOL_CALL_START",b,{toolCallId:h.toolCallId,toolCallName:h.toolCallName})}if(h.delta!==void 0){let b={type:v.TOOL_CALL_ARGS,toolCallId:o.toolCallId,delta:h.delta};g.push(b),n?.event("TRANSFORM","TOOL_CALL_ARGS",b,{toolCallId:o.toolCallId})}return g;case v.REASONING_MESSAGE_CHUNK:let _=m,S=[];if((i!=="reasoning"||_.messageId&&_.messageId!==s?.messageId)&&S.push(...p()),i!=="reasoning"){if(_.messageId===void 0)throw Error("First REASONING_MESSAGE_CHUNK must have a messageId");s={messageId:_.messageId},i="reasoning";let b={type:v.REASONING_MESSAGE_START,messageId:_.messageId};S.push(b),n?.event("TRANSFORM","REASONING_MESSAGE_START",b,{messageId:_.messageId})}if(_.delta!==void 0){let b={type:v.REASONING_MESSAGE_CONTENT,messageId:s.messageId,delta:_.delta};S.push(b),n?.event("TRANSFORM","REASONING_MESSAGE_CONTENT",b,{messageId:s.messageId})}return S}return m.type,[]}),Wt(()=>{p()}))};function Im(e,t=new Date){return e.expiresAt===void 0?!1:new Date(e.expiresAt)<=t}var qo=class{runNext(e,t){return t.run(e).pipe(Yo(!1))}runNextWithState(e,t){let n=B(e.messages||[]),r=B(e.state||{}),o=new Kr;return Xc(e,o,t,[]).subscribe(s=>{s.messages!==void 0&&(n=s.messages),s.state!==void 0&&(r=s.state)}),this.runNext(e,t).pipe(po(async s=>(o.next(s),await new Promise(i=>setTimeout(i,0)),{event:s,messages:B(n),state:B(r)})))}},Cm=class extends qo{constructor(e){super(),this.fn=e}run(e,t){return this.fn(e,t)}};function Nm(e){let t=e.content;if(Array.isArray(t)){let n=t.filter(r=>typeof r=="object"&&!!r&&"type"in r&&r.type==="text"&&typeof r.text=="string").map(r=>r.text).join("");return{...e,content:n}}return typeof t=="string"?e:{...e,content:""}}var Rm=class extends qo{run(e,t){let{parentRunId:n,...r}=e,o={...r,messages:r.messages.map(Nm)};return this.runNext(o,t)}},zc="THINKING_START",Bc="THINKING_END",Vc="THINKING_TEXT_MESSAGE_START",jc="THINKING_TEXT_MESSAGE_CONTENT",Wc="THINKING_TEXT_MESSAGE_END",Om=class extends qo{constructor(...e){super(...e),this.currentReasoningId=null,this.currentMessageId=null}warnAboutTransformation(e,t){typeof process<"u"&&process.env!==void 0&&process.env.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is converting ${e} to ${t}. To remove this warning, upgrade your AG-UI integration package (e.g. @ag-ui/langgraph). To surpress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(e,t){return this.currentReasoningId=null,this.currentMessageId=null,this.runNext(e,t).pipe(jt(n=>this.transformEvent(n)))}transformEvent(e){switch(e.type){case zc:{this.currentReasoningId=ze();let{title:t,...n}=e;return this.warnAboutTransformation(zc,v.REASONING_START),{...n,type:v.REASONING_START,messageId:this.currentReasoningId}}case Vc:return this.currentMessageId=ze(),this.warnAboutTransformation(Vc,v.REASONING_MESSAGE_START),{...e,type:v.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:"assistant"};case jc:{let{delta:t,...n}=e;return this.warnAboutTransformation(jc,v.REASONING_MESSAGE_CONTENT),{...n,type:v.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??ze(),delta:t}}case Wc:{let t=this.currentMessageId??ze();return this.warnAboutTransformation(Wc,v.REASONING_MESSAGE_END),{...e,type:v.REASONING_MESSAGE_END,messageId:t}}case Bc:{let t=this.currentReasoningId??ze();return this.warnAboutTransformation(Bc,v.REASONING_END),{...e,type:v.REASONING_END,messageId:t}}default:return e}}};function Mm(e){return e.startsWith("image/")?"image":e.startsWith("audio/")?"audio":e.startsWith("video/")?"video":"document"}function Lm(e){return typeof e=="object"&&!!e&&"type"in e&&e.type==="binary"&&"mimeType"in e&&typeof e.mimeType=="string"}function Pm(e){let t=Mm(e.mimeType);return e.data?{type:t,source:{type:"data",value:e.data,mimeType:e.mimeType},...e.filename?{metadata:{filename:e.filename}}:{}}:e.url?{type:t,source:{type:"url",value:e.url,mimeType:e.mimeType},...e.filename?{metadata:{filename:e.filename}}:{}}:e}function Dm(e){let t=e.content;if(!Array.isArray(t))return e;let n=t.map(r=>Lm(r)?Pm(r):r);return{...e,content:n}}var Um=class extends qo{run(e,t){let n={...e,messages:e.messages.map(Dm)};return this.runNext(n,t)}},Gm="0.0.54",Fm=class{get maxVersion(){return Gm}get debug(){return this._debug}set debug(e){this._debug=Ko(e),this._debugLogger=Oi(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(e){typeof e=="boolean"?this._debugLogger=e?Oi(Ko(!0)):void 0:this._debugLogger=e}constructor({agentId:e,description:t,threadId:n,initialMessages:r,initialState:o,debug:s}={}){this.subscribers=[],this.isRunning=!1,this.pendingInterrupts=[],this.middlewares=[],this.agentId=e,this.description=t??"",this.threadId=n??ht(),this.messages=B(r??[]),this.state=B(o??{}),this._debug=Ko(s),this._debugLogger=Oi(this._debug),Jn(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new Rm),Jn(this.maxVersion,"0.0.45")<=0&&this.middlewares.unshift(new Om),Jn(this.maxVersion,"0.0.47")<=0&&this.middlewares.unshift(new Um)}subscribe(e){return this.subscribers.push(e),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(t=>t!==e)}}}use(...e){let t=e.map(n=>typeof n=="function"?new Cm(n):n);return this.middlewares.push(...t),this}async runAgent(e,t){try{this.isRunning=!0,this.agentId=this.agentId??ht();let n=this.prepareRunAgentInput(e);this.debugLogger?.lifecycle("LIFECYCLE","Run started:",{agentId:this.agentId,threadId:this.threadId});let r,o=new Set(this.messages.map(u=>u.id)),s=[{onRunFinishedEvent:u=>{u.outcome==="success"&&(r=u.result)}},...this.subscribers,t??{}];await this.onInitialize(n,s),this.activeRunDetach$=new rt;let i;this.activeRunCompletionPromise=new Promise(u=>{i=u}),await co(Zr(()=>this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((u,c)=>({run:p=>c.run(p,u),get messages(){return u.messages},get state(){return u.state}}),this).run(n),Yo(this.debugLogger),Mi(this.debugLogger),u=>u.pipe(fo(this.activeRunDetach$)),u=>this.apply(n,u,s),u=>this.processApplyEvents(n,u,s),Kn(u=>(this.debugLogger?.lifecycle("LIFECYCLE","Run errored:",{agentId:this.agentId,error:u instanceof Error?u.message:String(u)}),this.isRunning=!1,this.onError(n,u,s))),Wt(()=>{this.debugLogger?.lifecycle("LIFECYCLE","Run finished:",{agentId:this.agentId,threadId:this.threadId}),this.isRunning=!1,this.onFinalize(n,s),i?.(),i=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(te(null)));let a=B(this.messages).filter(u=>!o.has(u.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}connect(e){throw new ti}async connectAgent(e,t){try{this.isRunning=!0,this.agentId=this.agentId??ht();let n=this.prepareRunAgentInput(e),r,o=new Set(this.messages.map(u=>u.id)),s=[{onRunFinishedEvent:u=>{u.outcome==="success"&&(r=u.result)}},...this.subscribers,t??{}];await this.onInitialize(n,s),this.activeRunDetach$=new rt;let i;this.activeRunCompletionPromise=new Promise(u=>{i=u}),await co(Zr(()=>uo(()=>this.connect(n)),Yo(this.debugLogger),Mi(this.debugLogger),u=>u.pipe(fo(this.activeRunDetach$)),u=>this.apply(n,u,s),u=>this.processApplyEvents(n,u,s),Kn(u=>(this.isRunning=!1,u instanceof ti?Yr:this.onError(n,u,s))),Wt(()=>{this.isRunning=!1,this.onFinalize(n,s),i?.(),i=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(te(null)),{defaultValue:void 0});let a=B(this.messages).filter(u=>!o.has(u.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let e=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await e}apply(e,t,n){return Xc(e,t,this,n,this.debugLogger)}processApplyEvents(e,t,n){return t.pipe(vi(r=>{r.messages&&(this.messages=r.messages,n.forEach(o=>{o.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),r.state&&(this.state=r.state,n.forEach(o=>{o.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})}))}))}prepareRunAgentInput(e){let t=B(this.messages).filter(n=>n.role!=="activity");return{threadId:this.threadId,runId:e?.runId||ht(),tools:B(e?.tools??[]),context:B(e?.context??[]),forwardedProps:B(e?.forwardedProps??{}),state:B(this.state),messages:t,...e?.resume===void 0?{}:{resume:B(e.resume)}}}async onInitialize(e,t){if(this.pendingInterrupts.length>0){let r=new Set((e.resume??[]).map(s=>s.interruptId)),o=this.pendingInterrupts.map(s=>s.id).filter(s=>!r.has(s));if(o.length>0)throw new q(`Thread has ${o.length} pending interrupt(s) not addressed by resume: ${o.join(", ")}`);for(let s of this.pendingInterrupts)if(Im(s))throw new q(`Interrupt ${s.id} expired at ${s.expiresAt}`)}let n=await W(t,this.messages,this.state,(r,o,s)=>r.onRunInitialized?.({messages:o,state:s,agent:this,input:e}));(n.messages!==void 0||n.state!==void 0)&&(n.messages&&(this.messages=n.messages,e.messages=n.messages,t.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),n.state&&(this.state=n.state,e.state=n.state,t.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})})))}onError(e,t,n){return Vt(W(n,this.messages,this.state,(r,o,s)=>r.onRunFailed?.({error:t,messages:o,state:s,agent:this,input:e}))).pipe(jt(r=>{let o=r;if((o.messages!==void 0||o.state!==void 0)&&(o.messages!==void 0&&(this.messages=o.messages,n.forEach(s=>{s.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),o.state!==void 0&&(this.state=o.state,n.forEach(s=>{s.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})}))),o.stopPropagation!==!0){let s=String(t);if(!(t.name==="AbortError"||t.message==="Fetch is aborted"||t.message==="signal is aborted without reason"||t.message==="component unmounted"||s==="component unmounted"))throw console.error("Agent execution failed:",t),t}return{}}))}async onFinalize(e,t){let n=await W(t,this.messages,this.state,(r,o,s)=>r.onRunFinalized?.({messages:o,state:s,agent:this,input:e}));(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,t.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),n.state!==void 0&&(this.state=n.state,t.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})})))}clone(){let e=Object.create(Object.getPrototypeOf(this));return e.agentId=this.agentId,e.description=this.description,e.threadId=this.threadId,e.messages=B(this.messages),e.state=B(this.state),e._debug=this._debug,e._debugLogger=this._debugLogger,e.isRunning=this.isRunning,e.subscribers=[...this.subscribers],e.middlewares=[...this.middlewares],e.pendingInterrupts=B(this.pendingInterrupts),e}addMessage(e){this.messages.push(e),(async()=>{for(let t of this.subscribers)await t.onNewMessage?.({message:e,messages:this.messages,state:this.state,agent:this});if(e.role==="assistant"&&e.toolCalls)for(let t of e.toolCalls)for(let n of this.subscribers)await n.onNewToolCall?.({toolCall:t,messages:this.messages,state:this.state,agent:this});for(let t of this.subscribers)await t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}addMessages(e){this.messages.push(...e),(async()=>{for(let t of e){for(let n of this.subscribers)await n.onNewMessage?.({message:t,messages:this.messages,state:this.state,agent:this});if(t.role==="assistant"&&t.toolCalls)for(let n of t.toolCalls)for(let r of this.subscribers)await r.onNewToolCall?.({toolCall:n,messages:this.messages,state:this.state,agent:this})}for(let t of this.subscribers)await t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setMessages(e){this.messages=B(e),(async()=>{for(let t of this.subscribers)await t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(e){this.state=B(e),(async()=>{for(let t of this.subscribers)await t.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(e){this.agentId=this.agentId??ht();let t=this.prepareRunAgentInput(e);return(this.middlewares.length===0?this.run(t):this.middlewares.reduceRight((n,r)=>({run:o=>r.run(o,n),get messages(){return n.messages},get state(){return n.state}}),this).run(t)).pipe(Yo(this.debugLogger),Mi(this.debugLogger),km(this.threadId,t.runId,this.agentId),n=>n.pipe(jt(r=>(this.debugLogger?.event("LEGACY","Event:",r,{type:r.type}),r))))}},Zc=class extends Fm{requestInit(e){return{method:"POST",headers:{...this.headers,"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify(e),signal:this.abortController.signal}}runAgent(e,t){return this.abortController=e?.abortController??new AbortController,super.runAgent(e,t)}abortRun(){this.abortController.abort(),super.abortRun()}constructor(e){super(e),this.abortController=new AbortController,this.url=e.url,this.headers=B(e.headers??{}),this.fetch=e.fetch??fetch}run(e){return fm(um(()=>this.fetch(this.url,this.requestInit(e))),this.debugLogger)}clone(){let e=super.clone();e.url=this.url,e.headers=B(this.headers??{}),e.fetch=this.fetch;let t=new AbortController,n=this.abortController.signal;return n.aborted&&t.abort(n.reason),e.abortController=t,e}};var er=class{#e;#n;#i;#u;#a;#o;constructor(t){this.#e=t.agent,this.#n=t.handlers,this.#i=t.getTools??(()=>[]),this.#u=t.getContext??(()=>[]),this.#a=t.executeTool??null,this.#o=t.onPersist??(()=>{})}get running(){return this.#e.isRunning}get messages(){return this.#e.messages}async send(t){this.#e.addMessage({id:ze(),role:"user",content:t}),this.#o(this.#e.messages),await this.#t()}async resume(){await this.#t()}addToolResult(t,n){this.#e.addMessage({id:ze(),role:"tool",content:n,toolCallId:t}),this.#o(this.#e.messages)}async#t(){try{await this.#r()}catch(t){this.#n.onError(t instanceof Error?t.message:String(t))}finally{this.#n.onSettled()}}async#r(){for(let t=0;t<bs;t+=1){let n=[];if(await this.#e.runAgent({tools:this.#i(),context:this.#u()},this.#s(n)),this.#o(this.#e.messages),this.#a===null||n.length===0)return;let r=!1;for(let o of n){let s=await this.#a(o);if(s!==null){if(s.halt===!0)return;this.#e.addMessage({id:ze(),role:"tool",content:s.content,toolCallId:o.id}),this.#o(this.#e.messages),r=!0}}if(!r)return}}#s(t){let n=this.#n;return{onRunInitialized(){n.onRunStart()},onTextMessageContentEvent({textMessageBuffer:r}){n.onTextDelta(r)},onTextMessageEndEvent({textMessageBuffer:r}){n.onTextEnd(r)},onToolCallEndEvent({event:r,toolCallName:o,toolCallArgs:s}){let i={id:r.toolCallId,name:o,args:s};t.push(i),n.onToolCall(i)},onToolCallResultEvent({event:r}){n.onToolResult(r.toolCallId,r.content)},onRunErrorEvent({event:r}){n.onError(r.message)},onRunFinalized(){n.onRunEnd()}}}};var Di="ag-ui-chat:thread",Ui="ag-ui-chat:messages:",Gi="ag-ui-chat:checkpoint:",tr=class{threadId(){let t=sessionStorage.getItem(Di);if(t!==null)return t;let n=ze();return sessionStorage.setItem(Di,n),n}loadMessages(t){return Promise.resolve(this.#e(Ui+t))}saveMessages(t,n){sessionStorage.setItem(Ui+t,JSON.stringify(n))}loadCheckpoint(t){return this.#e(Gi+t)}saveCheckpoint(t,n){let r=Gi+t;if(n===null){sessionStorage.removeItem(r);return}sessionStorage.setItem(r,JSON.stringify(n))}clear(t){sessionStorage.removeItem(Ui+t),sessionStorage.removeItem(Gi+t),sessionStorage.removeItem(Di)}#e(t){let n=sessionStorage.getItem(t);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function Fi(e){return new Zc({url:e.endpoint,headers:e.headers??{},fetch:(t,n)=>{let r=e.getHeaders?.();if(r===void 0)return fetch(t,n);let o=new Headers(n?.headers);for(let[s,i]of Object.entries(r))o.set(s,i);return fetch(t,{...n,headers:o})},...e.threadId!==void 0?{threadId:e.threadId}:{},...e.initialMessages!==void 0?{initialMessages:[...e.initialMessages]}:{}})}var Kc="ag-ui-chat:collapsed",nr=class extends HTMLElement{agentFactory=Fi;headers={};allowImages=!1;autoConfirm=!1;confirmPredicate=null;getTools=()=>[...this.#k().map(t=>({name:t.name,description:t.description,parameters:t.parameters})),...this.#n.tools()];getContext=()=>Ts(this.getPageMap,this.autoInjectPageMap);routeMap=[];navigate=null;getPageMap=null;autoInjectPageMap=!0;conversationStore=new tr;navigationResult=()=>({navigated:!0,url:window.location.href});skillContext=()=>({});toolSummaries={};#e={};#n=new On;#i=new Map;#u=new Set;#a;#o;#t;#r;#s;#f;#l;#p;#m=null;#d=null;#y=0;#g=null;#c="";#b=[];#T=[];#S=[];#w=[];constructor(){super(),this.#a=this.attachShadow({mode:"open"}),this.#o=document.createElement("div"),this.#t=document.createElement("div"),this.#r=document.createElement("textarea"),this.#s=document.createElement("button"),this.#f=document.createElement("span"),this.#p=document.createElement("div"),this.#l=new wr(t=>this.#U(t))}static get observedAttributes(){return["title-text"]}attributeChangedCallback(t,n,r){this.#f.textContent=r??"Assistant"}registerTool(t){this.#n.register(t)}registerStateHook(t){for(let n of ks(t))this.#n.register(n)}#R(){return this.routeMap.length===0?[]:ws(()=>this.routeMap,()=>this.navigate)}#O(){let t=this.getPageMap;return t===null?[]:[{name:"read_page",description:"Read the current page's structure (fields, buttons, route). Call after acting to observe the result within the same turn.",parameters:{type:"object",properties:{},required:[],[Xe]:"Read the page"},handler:()=>t()}]}#k(){return[...this.#R(),...this.#O()]}#A(t){let n=this.#k().find(r=>r.name===t);return n!==void 0?n:this.#n.has(t)?this.#n.get(t):null}get endpoint(){return this.getAttribute("endpoint")??""}set endpoint(t){this.setAttribute("endpoint",t)}get toolDisplay(){let t=this.getAttribute("data-tool-display");return t===Ze.MINIMAL||t===Ze.COMPACT?t:Ze.FULL}set toolDisplay(t){this.setAttribute("data-tool-display",t)}connectedCallback(){this.#z(),sessionStorage.getItem(Kc)==="1"&&this.setAttribute("collapsed",""),this.#L(),this.#M(),this.#c=this.conversationStore.threadId(),this.#G()}async#M(){let t=this.getAttribute("data-tools-url");if(t!==null)try{let n=await fetch(t,{headers:this.headers});this.#e=Ss(await n.json())}catch{}}setSkills(t){this.#w=t,this.#x()}#L(){this.#l.enableChips(this.getAttribute("data-prompt-chips")==="true"),this.#l.enableSlash(this.getAttribute("data-slash-commands")==="true"),this.#S=this.#P(),this.#x(),this.#D()}#P(){let t=this.getAttribute("data-skills");if(t===null)return[];try{return xs(JSON.parse(t))}catch{return[]}}async#D(){let t=this.getAttribute("data-skills-url");if(t!==null)try{let n=await fetch(t,{headers:this.headers});this.#T=xs(await n.json()),this.#x()}catch{}}#x(){let t=new Map;for(let n of[...this.#T,...this.#S,...this.#w])t.set(n.name,n);this.#l.setSkills([...t.values()])}#U(t){let{text:n,missing:r}=va(t.prompt,this.skillContext());if(r.length>0){this.#p.textContent=`\u201C${t.title}\u201D needs: ${r.join(", ")}`,this.#p.hidden=!1;return}this.#p.hidden=!0,this.#r.value=n,t.sendImmediately===!0?this.#E():this.#r.focus()}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(t){this.setCollapsed(t)}setCollapsed(t){t?this.setAttribute("collapsed",""):this.removeAttribute("collapsed"),sessionStorage.setItem(Kc,t?"1":"0"),this.dispatchEvent(new CustomEvent(vs,{detail:{collapsed:t},bubbles:!0,composed:!0}))}toggleCollapsed(){this.setCollapsed(!this.collapsed)}newChat(){this.conversationStore.clear(this.#c),this.#m=null,this.#d=null,this.#h(),this.#i.clear(),this.#u.clear(),this.#b=[],this.#t.replaceChildren(),this.#c=this.conversationStore.threadId(),this.#s.disabled=!1}async#G(){let t=await this.conversationStore.loadMessages(this.#c);if(t!==null){this.#b=t;for(let r of t)this.#F(r)}let n=this.conversationStore.loadCheckpoint(this.#c);n!==null&&await this.#$(n)}#F(t){let n=typeof t.content=="string"?t.content:"";if(t.role===We.USER){n!==""&&this.appendMessage(We.USER,n);return}if(t.role===We.ASSISTANT){n!==""&&this.appendMessage(We.ASSISTANT,n).classList.add("message--restored");let r=t.toolCalls;if(r!==void 0)for(let o of r)this.#_({id:o.id,name:o.function.name,args:this.#H(o.function.arguments)});return}if(t.role==="tool"){let r=this.#i.get(t.toolCallId);r!==void 0&&r.settle(de.DONE,t.content)}}#H(t){try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#I(t){this.getAttribute("data-text-animation")==="word"&&rl(t)}async#$(t){this.conversationStore.saveCheckpoint(this.#c,null);let n=this.#C();n.addToolResult(t.toolCallId,JSON.stringify(this.navigationResult(t))),await n.resume()}appendMessage(t,n){let r=document.createElement("div");return r.className=`message message--${t}`,t===We.ASSISTANT?r.innerHTML=Sr(n,{allowImages:this.allowImages}):r.textContent=n,this.#t.appendChild(r),this.#t.scrollTop=this.#t.scrollHeight,r}#z(){let t=document.createElement("style");t.textContent=ol,this.#o.className="chat";let n=document.createElement("div");n.className="header";let r=this.#f;r.className="header-title",r.textContent=this.getAttribute("title-text")??"Assistant";let o=document.createElement("div");o.className="header-controls";let s=document.createElement("button");s.type="button",s.className="header-btn header-btn--new",s.title="New chat",s.setAttribute("aria-label","New chat"),s.textContent="\u271A",s.addEventListener("click",()=>this.newChat());let i=document.createElement("button");i.type="button",i.className="header-btn header-btn--collapse",i.title="Collapse",i.setAttribute("aria-label","Collapse"),i.textContent="\u2014",i.addEventListener("click",()=>this.toggleCollapsed()),o.append(s,i),n.append(r,o),this.#t.className="messages",this.#t.setAttribute("role","log"),this.#t.setAttribute("aria-live","polite"),this.#t.setAttribute("aria-label","Conversation");let a=document.createElement("div");a.className="input-row",this.#r.className="input",this.#r.setAttribute("aria-label","Message"),this.#r.rows=2,this.#r.placeholder="Ask anything\u2026",this.#r.addEventListener("keydown",u=>this.#V(u)),this.#r.addEventListener("input",()=>this.#B()),this.#s.className="send",this.#s.type="button",this.#s.textContent="Send",this.#s.addEventListener("click",()=>{this.#E()}),this.#p.className="skill-hint",this.#p.hidden=!0,a.append(this.#r,this.#s),this.#o.append(n,this.#t,this.#l.palette,this.#l.chips,this.#p,a),this.#a.append(t,this.#o)}#B(){this.#l.onInput(this.#r.value),this.#p.hidden=!0}#V(t){if(this.#l.onKeydown(t)){t.preventDefault();return}t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),this.#E())}async#E(){let t=this.#r.value.trim();t!==""&&(this.appendMessage(We.USER,t),this.#r.value="",this.dispatchEvent(new CustomEvent(gs,{detail:{content:t},bubbles:!0,composed:!0})),await this.#j(t))}async#j(t){this.endpoint!==""&&await this.#C().send(t)}#C(){if(this.#m===null){let t=this.agentFactory({endpoint:this.endpoint,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#c,initialMessages:this.#b});this.#m=new er({agent:t,handlers:this.#Z(),getTools:()=>this.getTools(),getContext:()=>this.getContext(),executeTool:n=>this.#X(n),onPersist:n=>this.conversationStore.saveMessages(this.#c,n)})}return this.#m}async#W(t,n){return this.autoConfirm?!1:this.confirmPredicate!==null?await this.confirmPredicate(t.name,t.args)===!0:Es(n.parameters)}async#X(t){let n=this.#_(t);this.#i.delete(t.id);let r=this.#A(t.name);if(r===null)return this.#u.has(t.id)||n.settle(de.DONE,"No result returned."),null;if(await this.#W(t,r)){let s={toolName:t.name,args:t.args},i=r.parameters[ys];typeof i=="string"&&(s.message=i);let a=As(this.#t,s);if(this.#t.scrollTop=this.#t.scrollHeight,!await a){let c="User declined the action.";return n.settle(de.DECLINED,c),this.#v(),{content:c}}}let o=_s(r.parameters)&&this.navigate===null;o&&this.conversationStore.saveCheckpoint(this.#c,{toolCallId:t.id});try{let s=await r.handler(t.args);if(o)return n.settle(de.DONE,"Navigating\u2026"),{content:"",halt:!0};let i=JSON.stringify(s??null);return n.settle(de.DONE,i),this.#v(),{content:i}}catch(s){o&&this.conversationStore.saveCheckpoint(this.#c,null);let i=s instanceof Error?s.message:String(s);return n.settle(de.ERROR,i),this.#v(),{content:`Error: ${i}`,error:i}}}#Z(){return{onRunStart:()=>{this.#s.disabled=!0,this.#v()},onTextDelta:t=>{this.#h(),this.#N(t),this.#y+=1},onTextEnd:t=>{let n=this.#N(t);this.#y<=1&&this.#I(n),this.#d=null},onToolCall:t=>{this.#h(),this.#_(t)},onToolResult:(t,n)=>{let r=this.#i.get(t);r!==void 0&&(r.settle(de.DONE,n),this.#u.add(t))},onRunEnd:()=>{this.#h(),this.#s.disabled=!1,this.#d=null},onError:t=>{this.#h(),this.#I(this.appendMessage(We.ASSISTANT,`\u26A0\uFE0F ${t}`)),this.#s.disabled=!1,this.#d=null},onSettled:()=>{this.#h(),this.#s.disabled=!1,this.#d=null}}}#v(){if(this.#g!==null)return;let t=document.createElement("div");t.className="pending",t.setAttribute("role","status"),t.setAttribute("aria-label","Assistant is thinking\u2026");for(let n=0;n<3;n+=1){let r=document.createElement("span");r.className="pending-dot",t.appendChild(r)}this.#g=t,this.#t.appendChild(t),this.#t.scrollTop=this.#t.scrollHeight}#h(){this.#g?.remove(),this.#g=null}#N(t){return this.#d===null&&(this.#d=this.appendMessage(We.ASSISTANT,""),this.#y=0),this.#d.innerHTML=Sr(t,{allowImages:this.allowImages}),this.#t.scrollTop=this.#t.scrollHeight,this.#d}#_(t){let n=this.#i.get(t.id);if(n!==void 0)return n;let r=this.#A(t.name)?.parameters[Xe],o=typeof r=="string"?r:this.toolSummaries[t.name]??this.#e[t.name]??Is(t.name),s=new Fn(t.name,t.args,this.toolDisplay,o);return this.#i.set(t.id,s),this.#t.appendChild(s.element),this.#t.scrollTop=this.#t.scrollHeight,s}};function Hm(){customElements.get(gr)===void 0&&customElements.define(gr,nr)}function Jo(e,t){return Object.getOwnPropertyDescriptor(e,t).set}var $m=Jo(HTMLInputElement.prototype,"value"),zm=Jo(HTMLTextAreaElement.prototype,"value"),Bm=Jo(HTMLSelectElement.prototype,"value"),Vm=Jo(HTMLInputElement.prototype,"checked");function Zt(e,t){e instanceof HTMLTextAreaElement?zm.call(e,t):e instanceof HTMLSelectElement?Bm.call(e,t):$m.call(e,t)}function rr(e,t){Vm.call(e,t)}var Yc="#4f46e5";function Qo(e){return new Promise(t=>{setTimeout(t,e)})}async function Hi(e,t,n={}){let r=n.charDelayMs??35;Zt(e,""),e.dispatchEvent(new Event("input",{bubbles:!0}));for(let o of t)Zt(e,e.value+o),e.dispatchEvent(new Event("input",{bubbles:!0})),r>0&&await Qo(r);e.dispatchEvent(new Event("change",{bubbles:!0}))}async function $i(e,t={}){let n=t.highlightMs??280,r=e.style.outline,o=e.style.outlineOffset;e.style.outline=`2px solid ${Yc}`,e.style.outlineOffset="2px",await Qo(n),e.style.outline=r,e.style.outlineOffset=o,e.click()}function Kt(e){e.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}async function zi(e,t={}){let n=t.flashMs??200;e.focus();let r=e.style.boxShadow;e.style.boxShadow="0 0 0 3px rgba(79, 70, 229, 0.4)",await Qo(n),e.style.boxShadow=r}var qc="0 0 0 3px rgba(79, 70, 229, 0.4)";function Jc(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Bi(e){return e<=0||Jc()?Promise.resolve():Qo(e)}async function Vi(e,t={}){let n=t.pressMs??140,r=e.style.transform,o=e.style.transition,s=e.style.boxShadow;e.style.transition="transform 80ms ease",e.style.transform="scale(0.96)",e.style.boxShadow=qc,await Bi(n),e.style.transform=r,e.style.transition=o,e.style.boxShadow=s,e.click()}function jm(e,t){for(let n of Array.from(e.options))if(n.value===t||n.text===t)return n;return null}async function ji(e,t,n={}){let r=jm(e,t);if(r===null)throw new Error(`no <option> matching "${t}"`);let o=n.highlightMs??220,s=e.style.outline,i=e.style.outlineOffset;e.style.outline=`2px solid ${Yc}`,e.style.outlineOffset="2px",await Bi(o),Zt(e,r.value),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.style.outline=s,e.style.outlineOffset=i}async function Wi(e,t,n={}){let r=n.flashMs??200,o=e.style.boxShadow;e.style.boxShadow=qc,await Bi(r),rr(e,t),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.style.boxShadow=o}async function Wm(e,t,n={}){Kt(e),await zi(e,{flashMs:n.flashMs??0}),await Hi(e,t,n)}async function Xm(e,t={}){Kt(e),await $i(e,t)}async function Zm(e,t={}){Kt(e),await Vi(e,t)}async function Km(e,t,n={}){Kt(e),await ji(e,t,n)}async function Ym(e,t,n={}){Kt(e),await Wi(e,t,n)}function qm(e,t){e instanceof HTMLInputElement&&e.type==="checkbox"?rr(e,!!t):Zt(e,String(t)),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}))}var Jm="0.3.1";export{nr as AgUiChat,er as AgUiClient,On as ClientToolRegistry,gr as ELEMENT_TAG,bs as MAX_TOOL_ROUNDS,We as MESSAGE_ROLE,gs as SUBMIT_EVENT,tr as SessionStorageStore,vs as TOGGLE_EVENT,de as TOOL_CALL_STATUS,Ze as TOOL_DISPLAY,Fn as ToolCallCard,Jm as VERSION,ys as X_CONFIRM_KEY,Nn as X_DESTRUCTIVE_KEY,Rn as X_NAVIGATES_KEY,Xe as X_SUMMARY_KEY,Xm as clickElement,Fi as createHttpAgent,Ts as createPageMapContext,ws as createRouteTools,ks as createStateHookTools,Hm as defineAgUiChat,Wm as fillField,zi as focusWithFlash,$i as highlightThenClick,Es as isDestructive,_s as isNavigates,Ss as parseToolCatalog,Jc as prefersReducedMotion,Zm as pressButton,Vi as pressThenClick,Is as prettifyToolName,Sr as renderMarkdown,As as requestConfirmation,Kt as scrollIntoCenterView,Km as selectControl,ji as selectOption,qm as setControlValue,rr as setNativeChecked,Zt as setNativeValue,Ym as toggleCheckbox,Wi as toggleControl,Hi as typeInto};
901
+ Error: ${T}`)}}return p()}case v.MESSAGES_SNAPSHOT:{let f=await W(r,i,a,(h,g,T)=>h.onMessagesSnapshotEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(l(f),f.stopPropagation!==!0){let{messages:h}=m,g=new Map(h.map(b=>[b.id,b])),T=b=>b==="activity"||b==="reasoning";i=i.filter(b=>T(b.role)||g.has(b.id)).map(b=>T(b.role)?b:g.get(b.id));let S=new Set(i.map(b=>b.id));for(let b of h)S.has(b.id)||i.push(b);l({messages:i})}return p()}case v.ACTIVITY_SNAPSHOT:{let f=m,h=i.findIndex(H=>H.id===f.messageId),g=h>=0?i[h]:void 0,T=g?.role==="activity"?g:void 0,S=f.replace??!0,b=await W(r,i,a,(H,X,ae)=>H.onActivitySnapshotEvent?.({event:f,messages:X,state:ae,agent:n,input:t,activityMessage:T,existingMessage:g}));if(l(b),b.stopPropagation!==!0){let H={id:f.messageId,role:"activity",activityType:f.activityType,content:B(f.content)},X;h===-1?(i.push(H),X=H):T?S&&(i[h]={...T,activityType:f.activityType,content:B(f.content)}):S&&(i[h]=H,X=H),l({messages:i}),X&&await Promise.all(r.map(ae=>ae.onNewMessage?.({message:X,messages:i,state:a,agent:n,input:t})))}return p()}case v.ACTIVITY_DELTA:{let f=m,h=i.findIndex(b=>b.id===f.messageId);if(h===-1)return p();let g=i[h];if(g.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${f.messageId}' is not an activity message`),p();let T=g,S=await W(r,i,a,(b,H,X)=>b.onActivityDeltaEvent?.({event:f,messages:H,state:X,agent:n,input:t,activityMessage:T}));if(l(S),S.stopPropagation!==!0)try{let b=B(T.content??{}),H=Vr.applyPatch(b,f.patch??[],!0,!1).newDocument;i[h]={...T,content:B(H),activityType:f.activityType},l({messages:i})}catch(b){let H=b instanceof Error?b.message:String(b);console.warn(`Failed to apply activity patch for '${f.messageId}': ${H}`)}return p()}case v.RAW:return l(await W(r,i,a,(f,h,g)=>f.onRawEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.CUSTOM:return l(await W(r,i,a,(f,h,g)=>f.onCustomEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.RUN_STARTED:{let f=await W(r,i,a,(h,g,T)=>h.onRunStartedEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(l(f),f.stopPropagation!==!0){let h=m;if(h.input?.messages){for(let g of h.input.messages)i.find(T=>T.id===g.id)||i.push(g);l({messages:i})}}return p()}case v.RUN_FINISHED:{let f=m,h=f.outcome?.type==="interrupt"?{event:f,outcome:"interrupt",interrupts:f.outcome.interrupts}:{event:f,outcome:"success",result:f.result},g=await W(r,i,a,(T,S,b)=>T.onRunFinishedEvent?.({...h,messages:S,state:b,agent:n,input:t}));return l(g),g.stopPropagation!==!0&&(n.pendingInterrupts=h.outcome==="interrupt"?[...h.interrupts]:[]),p()}case v.RUN_ERROR:return l(await W(r,i,a,(f,h,g)=>f.onRunErrorEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.STEP_STARTED:return l(await W(r,i,a,(f,h,g)=>f.onStepStartedEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.STEP_FINISHED:return l(await W(r,i,a,(f,h,g)=>f.onStepFinishedEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.TEXT_MESSAGE_CHUNK:throw Error("TEXT_MESSAGE_CHUNK must be tranformed before being applied");case v.TOOL_CALL_CHUNK:throw Error("TOOL_CALL_CHUNK must be tranformed before being applied");case v.THINKING_START:return p();case v.THINKING_END:return p();case v.THINKING_TEXT_MESSAGE_START:return p();case v.THINKING_TEXT_MESSAGE_CONTENT:return p();case v.THINKING_TEXT_MESSAGE_END:return p();case v.REASONING_START:return l(await W(r,i,a,(f,h,g)=>f.onReasoningStartEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.REASONING_MESSAGE_START:{let f=await W(r,i,a,(h,g,T)=>h.onReasoningMessageStartEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(l(f),f.stopPropagation!==!0){let{messageId:h}=m;if(!i.find(g=>g.id===h)){let g={id:h,role:"reasoning",content:""};i.push(g),l({messages:i})}}return p()}case v.REASONING_MESSAGE_CONTENT:{let{messageId:f,delta:h}=m,g=i.find(S=>S.id===f);if(!g)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${f}'`),p();let T=await W(r,i,a,(S,b,H)=>S.onReasoningMessageContentEvent?.({event:m,messages:b,state:H,agent:n,input:t,reasoningMessageBuffer:typeof g.content=="string"?g.content:""}));return l(T),T.stopPropagation!==!0&&(g.content=`${typeof g.content=="string"?g.content:""}${h}`,l({messages:i})),p()}case v.REASONING_MESSAGE_END:{let{messageId:f}=m,h=i.find(g=>g.id===f);return h?(l(await W(r,i,a,(g,T,S)=>g.onReasoningMessageEndEvent?.({event:m,messages:T,state:S,agent:n,input:t,reasoningMessageBuffer:typeof h.content=="string"?h.content:""}))),await Promise.all(r.map(g=>{g.onNewMessage?.({message:h,messages:i,state:a,agent:n,input:t})})),p()):(console.warn(`REASONING_MESSAGE_END: No message found with ID '${f}'`),p())}case v.REASONING_MESSAGE_CHUNK:throw Error("REASONING_MESSAGE_CHUNK must be transformed before being applied");case v.REASONING_END:return l(await W(r,i,a,(f,h,g)=>f.onReasoningEndEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.REASONING_ENCRYPTED_VALUE:{let{subtype:f,entityId:h,encryptedValue:g}=m,T=await W(r,i,a,(S,b,H)=>S.onReasoningEncryptedValueEvent?.({event:m,messages:b,state:H,agent:n,input:t}));if(l(T),T.stopPropagation!==!0){let S=!1;if(f==="tool-call"){for(let b of i)if(b.role==="assistant"&&b.toolCalls){let H=b.toolCalls.find(X=>X.id===h);if(H){H.encryptedValue=g,S=!0;break}}}else{let b=i.find(H=>H.id===h);b?.role!=="activity"&&b&&(b.encryptedValue=g,S=!0)}S&&(u.messages=i)}return p()}}return m.type,p()}),vi(),r.length>0?yi({}):m=>m)},Di=t=>e=>{let n=er(t),r=new Map,o=new Map,s=!1,i=!1,a=!1,u=new Map,l=!1,p=!1,m=!1,x=()=>{r.clear(),o.clear(),u.clear(),l=!1,p=!1,s=!1,i=!1,m=!0};return e.pipe(Ae(f=>{let h=f.type;if(n?.event("VERIFY","Event:",f,{type:f.type}),i)return Q(()=>new q(`Cannot send event type '${h}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(s&&h!==v.RUN_ERROR&&h!==v.RUN_STARTED)return Q(()=>new q(`Cannot send event type '${h}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(a){if(h===v.RUN_STARTED){if(m&&!s)return Q(()=>new q("Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run."));s&&x()}}else if(a=!0,h!==v.RUN_STARTED&&h!==v.RUN_ERROR)return Q(()=>new q("First event must be 'RUN_STARTED'"));switch(h){case v.TEXT_MESSAGE_START:{let g=f.messageId;return r.has(g)?Q(()=>new q(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${g}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(r.set(g,!0),te(f))}case v.TEXT_MESSAGE_CONTENT:{let g=f.messageId;return r.has(g)?te(f):Q(()=>new q(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${g}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case v.TEXT_MESSAGE_END:{let g=f.messageId;return r.has(g)?(r.delete(g),te(f)):Q(()=>new q(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${g}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case v.TOOL_CALL_START:{let g=f.toolCallId;return o.has(g)?Q(()=>new q(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${g}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(o.set(g,!0),te(f))}case v.TOOL_CALL_ARGS:{let g=f.toolCallId;return o.has(g)?te(f):Q(()=>new q(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${g}'. Start a tool call with 'TOOL_CALL_START' first.`))}case v.TOOL_CALL_END:{let g=f.toolCallId;return o.has(g)?(o.delete(g),te(f)):Q(()=>new q(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${g}'. A 'TOOL_CALL_START' event must be sent first.`))}case v.STEP_STARTED:{let g=f.stepName;return u.has(g)?Q(()=>new q(`Step "${g}" is already active for 'STEP_STARTED'`)):(u.set(g,!0),te(f))}case v.STEP_FINISHED:{let g=f.stepName;return u.has(g)?(u.delete(g),te(f)):Q(()=>new q(`Cannot send 'STEP_FINISHED' for step "${g}" that was not started`))}case v.RUN_STARTED:return m=!0,te(f);case v.RUN_FINISHED:if(u.size>0){let g=Array.from(u.keys()).join(", ");return Q(()=>new q(`Cannot send 'RUN_FINISHED' while steps are still active: ${g}`))}if(r.size>0){let g=Array.from(r.keys()).join(", ");return Q(()=>new q(`Cannot send 'RUN_FINISHED' while text messages are still active: ${g}`))}if(o.size>0){let g=Array.from(o.keys()).join(", ");return Q(()=>new q(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${g}`))}return s=!0,te(f);case v.RUN_ERROR:return i=!0,te(f);case v.CUSTOM:return te(f);case v.THINKING_TEXT_MESSAGE_START:return l?p?Q(()=>new q("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(p=!0,te(f)):Q(()=>new q("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case v.THINKING_TEXT_MESSAGE_CONTENT:return p?te(f):Q(()=>new q("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case v.THINKING_TEXT_MESSAGE_END:return p?(p=!1,te(f)):Q(()=>new q("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case v.THINKING_START:return l?Q(()=>new q("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(l=!0,te(f));case v.THINKING_END:return l?(l=!1,te(f)):Q(()=>new q("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return te(f)}}))},Xt=(function(t){return t.HEADERS="headers",t.DATA="data",t})({}),vm=t=>ho(()=>Vt(t())).pipe(bi(e=>{if(!e.ok){let o=e.headers.get("content-type")||"";return Vt(e.text()).pipe(Ae(s=>{let i=s;if(o.includes("application/json"))try{i=JSON.parse(s)}catch{}let a=Error(`HTTP ${e.status}: ${typeof i=="string"?i:JSON.stringify(i)}`);return a.status=e.status,a.payload=i,Q(()=>a)}))}let n={type:Xt.HEADERS,status:e.status,headers:e.headers},r=e.body?.getReader();return r?new J(o=>(o.next(n),(async()=>{try{for(;;){let{done:s,value:i}=await r.read();if(s)break;let a={type:Xt.DATA,data:i};o.next(a)}o.complete()}catch(s){o.error(s)}})(),()=>{r.cancel().catch(s=>{if(s?.name!=="AbortError")throw s})})):Q(()=>Error("Failed to getReader() from response"))})),ym=(t,e)=>{let n=er(e),r=new rt,o=new TextDecoder("utf-8",{fatal:!1}),s="";t.subscribe({next:a=>{if(a.type!==Xt.HEADERS&&a.type===Xt.DATA&&a.data){let u=o.decode(a.data,{stream:!0});s+=u;let l=s.split(/\n\n/);s=l.pop()||"";for(let p of l)i(p)}},error:a=>r.error(a),complete:()=>{s&&(s+=o.decode(),i(s)),r.complete()}});function i(a){let u=a.split(`
902
+ `),l=[];for(let p of u)p.startsWith("data:")&&l.push(p.slice(5).replace(/^ /,""));if(l.length>0)try{let p=l.join(`
903
+ `),m=JSON.parse(p);n?.event("SSE","Event received:",m,{type:m.type}),r.next(m)}catch(p){r.error(p)}}return r.asObservable()},bm=t=>{let e=new rt,n=new Uint8Array;t.subscribe({next:o=>{if(o.type!==Xt.HEADERS&&o.type===Xt.DATA&&o.data){let s=new Uint8Array(n.length+o.data.length);s.set(n,0),s.set(o.data,n.length),n=s,r()}},error:o=>e.error(o),complete:()=>{if(n.length>0)try{r()}catch{console.warn("Incomplete or invalid protocol buffer data at stream end")}e.complete()}});function r(){for(;n.length>=4;){let o=4+new DataView(n.buffer,n.byteOffset,4).getUint32(0,!1);if(n.length<o)break;try{let s=n.slice(4,o),i=Bc(s);e.next(i),n=n.slice(o)}catch(s){let i=s instanceof Error?s.message:String(s);e.error(Error(`Failed to decode protocol buffer message: ${i}`));return}}}return e.asObservable()},xm=(t,e)=>{let n=er(e),r=new rt,o=new Jr,s=!1;return t.subscribe({next:i=>{if(o.next(i),i.type===Xt.HEADERS&&!s){s=!0;let a=i.headers.get("content-type");n?.lifecycle("HTTP","Stream format detected:",{contentType:a,parser:a===Oi?"protobuf":"sse"}),a===Oi?bm(o).subscribe({next:u=>r.next(u),error:u=>r.error(u),complete:()=>r.complete()}):ym(o,n).subscribe({next:u=>{try{let l=Dr.parse(u);n?.event("HTTP","Event validated:",l,{type:l.type,valid:!0}),r.next(l)}catch(l){n?.event("HTTP","Event invalid:",{json:u,error:String(l)}),r.error(l)}},error:u=>{if(u?.name==="AbortError"){r.next({type:v.RUN_ERROR,message:u.message||"Request aborted",code:"abort",rawEvent:u}),r.complete();return}return r.error(u)},complete:()=>r.complete()})}else s||r.error(Error("No headers event received before data events"))},error:i=>{o.error(i),r.error(i)},complete:()=>{o.complete()}}),r.asObservable()},K=c.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),Em=c.enum(["LangGraphInterruptEvent","PredictState","Exit"]),Tm=c.object({type:c.literal(K.enum.TextMessageStart),messageId:c.string(),parentMessageId:c.string().optional(),role:c.string().optional()}),_m=c.object({type:c.literal(K.enum.TextMessageContent),messageId:c.string(),content:c.string()}),Sm=c.object({type:c.literal(K.enum.TextMessageEnd),messageId:c.string()}),wm=c.object({type:c.literal(K.enum.ActionExecutionStart),actionExecutionId:c.string(),actionName:c.string(),parentMessageId:c.string().optional()}),km=c.object({type:c.literal(K.enum.ActionExecutionArgs),actionExecutionId:c.string(),args:c.string()}),Am=c.object({type:c.literal(K.enum.ActionExecutionEnd),actionExecutionId:c.string()}),Im=c.object({type:c.literal(K.enum.ActionExecutionResult),actionName:c.string(),actionExecutionId:c.string(),result:c.string()}),Cm=c.object({type:c.literal(K.enum.AgentStateMessage),threadId:c.string(),agentName:c.string(),nodeName:c.string(),runId:c.string(),active:c.boolean(),role:c.string(),state:c.string(),running:c.boolean()}),Nm=c.object({type:c.literal(K.enum.MetaEvent),name:Em,value:c.any()}),Rm=c.object({type:c.literal(K.enum.RunError),message:c.string(),code:c.string().optional()});c.discriminatedUnion("type",[Tm,_m,Sm,wm,km,Am,Im,Cm,Nm,Rm]),c.object({id:c.string(),role:c.string(),content:c.string(),parentMessageId:c.string().optional()}),c.object({id:c.string(),name:c.string(),arguments:c.any(),parentMessageId:c.string().optional()}),c.object({id:c.string(),result:c.any(),actionExecutionId:c.string(),actionName:c.string()});var Om=t=>{if(typeof t=="string")return t;if(!Array.isArray(t))return;let e=t.filter(n=>n.type==="text").map(n=>n.text).filter(n=>n.length>0);if(e.length!==0)return e.join(`
904
+ `)},Mm=(t,e,n)=>r=>{let o={},s=!0,i=!0,a="",u=null,l=null,p=[],m={},x=f=>{typeof f=="object"&&f&&("messages"in f&&delete f.messages,o=f)};return r.pipe(Ae(f=>{switch(f.type){case v.TEXT_MESSAGE_START:{let h=f;return[{type:K.enum.TextMessageStart,messageId:h.messageId,role:h.role}]}case v.TEXT_MESSAGE_CONTENT:{let h=f;return[{type:K.enum.TextMessageContent,messageId:h.messageId,content:h.delta}]}case v.TEXT_MESSAGE_END:{let h=f;return[{type:K.enum.TextMessageEnd,messageId:h.messageId}]}case v.TOOL_CALL_START:{let h=f;return p.push({id:h.toolCallId,type:"function",function:{name:h.toolCallName,arguments:""}}),i=!0,m[h.toolCallId]=h.toolCallName,[{type:K.enum.ActionExecutionStart,actionExecutionId:h.toolCallId,actionName:h.toolCallName,parentMessageId:h.parentMessageId}]}case v.TOOL_CALL_ARGS:{let h=f,g=p.find(S=>S.id===h.toolCallId);if(!g)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${h.toolCallId}'`),[];g.function.arguments+=h.delta;let T=!1;if(l){let S=l.find(b=>b.tool==g.function.name);if(S)try{let b=JSON.parse(vo(g.function.arguments));S.tool_argument&&S.tool_argument in b?(x({...o,[S.state_key]:b[S.tool_argument]}),T=!0):S.tool_argument||(x({...o,[S.state_key]:b}),T=!0)}catch{}}return[{type:K.enum.ActionExecutionArgs,actionExecutionId:h.toolCallId,args:h.delta},...T?[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:i}]:[]]}case v.TOOL_CALL_END:{let h=f;return[{type:K.enum.ActionExecutionEnd,actionExecutionId:h.toolCallId}]}case v.TOOL_CALL_RESULT:{let h=f;return[{type:K.enum.ActionExecutionResult,actionExecutionId:h.toolCallId,result:h.content,actionName:m[h.toolCallId]||"unknown"}]}case v.RAW:return[];case v.CUSTOM:{let h=f;switch(h.name){case"Exit":s=!1;break;case"PredictState":l=h.value;break}return[{type:K.enum.MetaEvent,name:h.name,value:h.value}]}case v.STATE_SNAPSHOT:return x(f.snapshot),[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:i}];case v.STATE_DELTA:{let h=f,g=Vr.applyPatch(o,h.delta,!0,!1);return g?(x(g.newDocument),[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:i}]):[]}case v.MESSAGES_SNAPSHOT:return u=f.messages,[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:s,role:"assistant",state:JSON.stringify({...o,...u?{messages:u}:{}}),active:!0}];case v.RUN_STARTED:return[];case v.RUN_FINISHED:return u&&(o.messages=u),Object.keys(o).length===0?[]:[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:s,role:"assistant",state:JSON.stringify({...o,...u?{messages:Lm(u)}:{}}),active:!1}];case v.RUN_ERROR:{let h=f;return[{type:K.enum.RunError,message:h.message,code:h.code}]}case v.STEP_STARTED:return a=f.stepName,p=[],l=null,[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:!0}];case v.STEP_FINISHED:return p=[],l=null,[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:!1}];default:return[]}}))};function Lm(t){let e=[];for(let n of t)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let r=Om(n.content);if(r){let o={id:n.id,role:n.role,content:r};e.push(o)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let o of n.toolCalls){let s={id:o.id,name:o.function.name,arguments:JSON.parse(o.function.arguments),parentMessageId:n.id};e.push(s)}}else if(n.role==="tool"){let r="unknown";for(let s of t)if(s.role==="assistant"&&s.toolCalls?.length){for(let i of s.toolCalls)if(i.id===n.toolCallId){r=i.function.name;break}}let o={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:r};e.push(o)}return e}var Qo=t=>e=>{let n=er(t),r,o,s,i,a=()=>{if(!r||i!=="text")throw Error("No text message to close");let m={type:v.TEXT_MESSAGE_END,messageId:r.messageId};return i=void 0,r=void 0,n?.event("TRANSFORM","TEXT_MESSAGE_END",m,{messageId:m.messageId}),m},u=()=>{if(!o||i!=="tool")throw Error("No tool call to close");let m={type:v.TOOL_CALL_END,toolCallId:o.toolCallId};return i=void 0,o=void 0,n?.event("TRANSFORM","TOOL_CALL_END",m,{toolCallId:m.toolCallId}),m},l=()=>{if(!s||i!=="reasoning")throw Error("No reasoning message to close");let m={type:v.REASONING_MESSAGE_END,messageId:s.messageId};return i=void 0,s=void 0,n?.event("TRANSFORM","REASONING_MESSAGE_END",m,{messageId:m.messageId}),m},p=()=>i==="text"?[a()]:i==="tool"?[u()]:i==="reasoning"?[l()]:[];return e.pipe(Ae(m=>{switch(m.type){case v.TEXT_MESSAGE_START:case v.TEXT_MESSAGE_CONTENT:case v.TEXT_MESSAGE_END:case v.TOOL_CALL_START:case v.TOOL_CALL_ARGS:case v.TOOL_CALL_END:case v.TOOL_CALL_RESULT:case v.STATE_SNAPSHOT:case v.STATE_DELTA:case v.MESSAGES_SNAPSHOT:case v.CUSTOM:case v.RUN_STARTED:case v.RUN_FINISHED:case v.RUN_ERROR:case v.STEP_STARTED:case v.STEP_FINISHED:case v.THINKING_START:case v.THINKING_END:case v.THINKING_TEXT_MESSAGE_START:case v.THINKING_TEXT_MESSAGE_CONTENT:case v.THINKING_TEXT_MESSAGE_END:case v.REASONING_START:case v.REASONING_MESSAGE_START:case v.REASONING_MESSAGE_CONTENT:case v.REASONING_MESSAGE_END:case v.REASONING_END:return[...p(),m];case v.RAW:case v.ACTIVITY_SNAPSHOT:case v.ACTIVITY_DELTA:case v.REASONING_ENCRYPTED_VALUE:return[m];case v.TEXT_MESSAGE_CHUNK:let x=m,f=[];if((i!=="text"||x.messageId!==void 0&&x.messageId!==r?.messageId)&&f.push(...p()),i!=="text"){if(x.messageId===void 0)throw Error("First TEXT_MESSAGE_CHUNK must have a messageId");r={messageId:x.messageId,name:x.name},i="text";let b={type:v.TEXT_MESSAGE_START,messageId:x.messageId,role:x.role||"assistant",...x.name!==void 0&&{name:x.name}};f.push(b),n?.event("TRANSFORM","TEXT_MESSAGE_START",b,{messageId:x.messageId})}if(x.delta!==void 0){let b={type:v.TEXT_MESSAGE_CONTENT,messageId:r.messageId,delta:x.delta};f.push(b),n?.event("TRANSFORM","TEXT_MESSAGE_CONTENT",b,{messageId:r.messageId})}return f;case v.TOOL_CALL_CHUNK:let h=m,g=[];if((i!=="tool"||h.toolCallId!==void 0&&h.toolCallId!==o?.toolCallId)&&g.push(...p()),i!=="tool"){if(h.toolCallId===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallId");if(h.toolCallName===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallName");o={toolCallId:h.toolCallId,toolCallName:h.toolCallName,parentMessageId:h.parentMessageId},i="tool";let b={type:v.TOOL_CALL_START,toolCallId:h.toolCallId,toolCallName:h.toolCallName,parentMessageId:h.parentMessageId};g.push(b),n?.event("TRANSFORM","TOOL_CALL_START",b,{toolCallId:h.toolCallId,toolCallName:h.toolCallName})}if(h.delta!==void 0){let b={type:v.TOOL_CALL_ARGS,toolCallId:o.toolCallId,delta:h.delta};g.push(b),n?.event("TRANSFORM","TOOL_CALL_ARGS",b,{toolCallId:o.toolCallId})}return g;case v.REASONING_MESSAGE_CHUNK:let T=m,S=[];if((i!=="reasoning"||T.messageId&&T.messageId!==s?.messageId)&&S.push(...p()),i!=="reasoning"){if(T.messageId===void 0)throw Error("First REASONING_MESSAGE_CHUNK must have a messageId");s={messageId:T.messageId},i="reasoning";let b={type:v.REASONING_MESSAGE_START,messageId:T.messageId};S.push(b),n?.event("TRANSFORM","REASONING_MESSAGE_START",b,{messageId:T.messageId})}if(T.delta!==void 0){let b={type:v.REASONING_MESSAGE_CONTENT,messageId:s.messageId,delta:T.delta};S.push(b),n?.event("TRANSFORM","REASONING_MESSAGE_CONTENT",b,{messageId:s.messageId})}return S}return m.type,[]}),Wt(()=>{p()}))};function Pm(t,e=new Date){return t.expiresAt===void 0?!1:new Date(t.expiresAt)<=e}var es=class{runNext(t,e){return e.run(t).pipe(Qo(!1))}runNextWithState(t,e){let n=B(t.messages||[]),r=B(t.state||{}),o=new Jr;return qc(t,o,e,[]).subscribe(s=>{s.messages!==void 0&&(n=s.messages),s.state!==void 0&&(r=s.state)}),this.runNext(t,e).pipe(mo(async s=>(o.next(s),await new Promise(i=>setTimeout(i,0)),{event:s,messages:B(n),state:B(r)})))}},Dm=class extends es{constructor(t){super(),this.fn=t}run(t,e){return this.fn(t,e)}};function Um(t){let e=t.content;if(Array.isArray(e)){let n=e.filter(r=>typeof r=="object"&&!!r&&"type"in r&&r.type==="text"&&typeof r.text=="string").map(r=>r.text).join("");return{...t,content:n}}return typeof e=="string"?t:{...t,content:""}}var Gm=class extends es{run(t,e){let{parentRunId:n,...r}=t,o={...r,messages:r.messages.map(Um)};return this.runNext(o,e)}},Wc="THINKING_START",Xc="THINKING_END",Zc="THINKING_TEXT_MESSAGE_START",Kc="THINKING_TEXT_MESSAGE_CONTENT",Yc="THINKING_TEXT_MESSAGE_END",Hm=class extends es{constructor(...t){super(...t),this.currentReasoningId=null,this.currentMessageId=null}warnAboutTransformation(t,e){typeof process<"u"&&process.env!==void 0&&process.env.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is converting ${t} to ${e}. To remove this warning, upgrade your AG-UI integration package (e.g. @ag-ui/langgraph). To surpress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(t,e){return this.currentReasoningId=null,this.currentMessageId=null,this.runNext(t,e).pipe(jt(n=>this.transformEvent(n)))}transformEvent(t){switch(t.type){case Wc:{this.currentReasoningId=ze();let{title:e,...n}=t;return this.warnAboutTransformation(Wc,v.REASONING_START),{...n,type:v.REASONING_START,messageId:this.currentReasoningId}}case Zc:return this.currentMessageId=ze(),this.warnAboutTransformation(Zc,v.REASONING_MESSAGE_START),{...t,type:v.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:"assistant"};case Kc:{let{delta:e,...n}=t;return this.warnAboutTransformation(Kc,v.REASONING_MESSAGE_CONTENT),{...n,type:v.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??ze(),delta:e}}case Yc:{let e=this.currentMessageId??ze();return this.warnAboutTransformation(Yc,v.REASONING_MESSAGE_END),{...t,type:v.REASONING_MESSAGE_END,messageId:e}}case Xc:{let e=this.currentReasoningId??ze();return this.warnAboutTransformation(Xc,v.REASONING_END),{...t,type:v.REASONING_END,messageId:e}}default:return t}}};function Fm(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"document"}function $m(t){return typeof t=="object"&&!!t&&"type"in t&&t.type==="binary"&&"mimeType"in t&&typeof t.mimeType=="string"}function zm(t){let e=Fm(t.mimeType);return t.data?{type:e,source:{type:"data",value:t.data,mimeType:t.mimeType},...t.filename?{metadata:{filename:t.filename}}:{}}:t.url?{type:e,source:{type:"url",value:t.url,mimeType:t.mimeType},...t.filename?{metadata:{filename:t.filename}}:{}}:t}function Bm(t){let e=t.content;if(!Array.isArray(e))return t;let n=e.map(r=>$m(r)?zm(r):r);return{...t,content:n}}var Vm=class extends es{run(t,e){let n={...t,messages:t.messages.map(Bm)};return this.runNext(n,e)}},jm="0.0.54",Wm=class{get maxVersion(){return jm}get debug(){return this._debug}set debug(t){this._debug=Jo(t),this._debugLogger=Pi(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(t){typeof t=="boolean"?this._debugLogger=t?Pi(Jo(!0)):void 0:this._debugLogger=t}constructor({agentId:t,description:e,threadId:n,initialMessages:r,initialState:o,debug:s}={}){this.subscribers=[],this.isRunning=!1,this.pendingInterrupts=[],this.middlewares=[],this.agentId=t,this.description=e??"",this.threadId=n??ht(),this.messages=B(r??[]),this.state=B(o??{}),this._debug=Jo(s),this._debugLogger=Pi(this._debug),Qn(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new Gm),Qn(this.maxVersion,"0.0.45")<=0&&this.middlewares.unshift(new Hm),Qn(this.maxVersion,"0.0.47")<=0&&this.middlewares.unshift(new Vm)}subscribe(t){return this.subscribers.push(t),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(e=>e!==t)}}}use(...t){let e=t.map(n=>typeof n=="function"?new Dm(n):n);return this.middlewares.push(...e),this}async runAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??ht();let n=this.prepareRunAgentInput(t);this.debugLogger?.lifecycle("LIFECYCLE","Run started:",{agentId:this.agentId,threadId:this.threadId});let r,o=new Set(this.messages.map(u=>u.id)),s=[{onRunFinishedEvent:u=>{u.outcome==="success"&&(r=u.result)}},...this.subscribers,e??{}];await this.onInitialize(n,s),this.activeRunDetach$=new rt;let i;this.activeRunCompletionPromise=new Promise(u=>{i=u}),await fo(qr(()=>this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((u,l)=>({run:p=>l.run(p,u),get messages(){return u.messages},get state(){return u.state}}),this).run(n),Qo(this.debugLogger),Di(this.debugLogger),u=>u.pipe(go(this.activeRunDetach$)),u=>this.apply(n,u,s),u=>this.processApplyEvents(n,u,s),Yn(u=>(this.debugLogger?.lifecycle("LIFECYCLE","Run errored:",{agentId:this.agentId,error:u instanceof Error?u.message:String(u)}),this.isRunning=!1,this.onError(n,u,s))),Wt(()=>{this.debugLogger?.lifecycle("LIFECYCLE","Run finished:",{agentId:this.agentId,threadId:this.threadId}),this.isRunning=!1,this.onFinalize(n,s),i?.(),i=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(te(null)));let a=B(this.messages).filter(u=>!o.has(u.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}connect(t){throw new oi}async connectAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??ht();let n=this.prepareRunAgentInput(t),r,o=new Set(this.messages.map(u=>u.id)),s=[{onRunFinishedEvent:u=>{u.outcome==="success"&&(r=u.result)}},...this.subscribers,e??{}];await this.onInitialize(n,s),this.activeRunDetach$=new rt;let i;this.activeRunCompletionPromise=new Promise(u=>{i=u}),await fo(qr(()=>ho(()=>this.connect(n)),Qo(this.debugLogger),Di(this.debugLogger),u=>u.pipe(go(this.activeRunDetach$)),u=>this.apply(n,u,s),u=>this.processApplyEvents(n,u,s),Yn(u=>(this.isRunning=!1,u instanceof oi?Qr:this.onError(n,u,s))),Wt(()=>{this.isRunning=!1,this.onFinalize(n,s),i?.(),i=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(te(null)),{defaultValue:void 0});let a=B(this.messages).filter(u=>!o.has(u.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let t=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await t}apply(t,e,n){return qc(t,e,this,n,this.debugLogger)}processApplyEvents(t,e,n){return e.pipe(xi(r=>{r.messages&&(this.messages=r.messages,n.forEach(o=>{o.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),r.state&&(this.state=r.state,n.forEach(o=>{o.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))}))}prepareRunAgentInput(t){let e=B(this.messages).filter(n=>n.role!=="activity");return{threadId:this.threadId,runId:t?.runId||ht(),tools:B(t?.tools??[]),context:B(t?.context??[]),forwardedProps:B(t?.forwardedProps??{}),state:B(this.state),messages:e,...t?.resume===void 0?{}:{resume:B(t.resume)}}}async onInitialize(t,e){if(this.pendingInterrupts.length>0){let r=new Set((t.resume??[]).map(s=>s.interruptId)),o=this.pendingInterrupts.map(s=>s.id).filter(s=>!r.has(s));if(o.length>0)throw new q(`Thread has ${o.length} pending interrupt(s) not addressed by resume: ${o.join(", ")}`);for(let s of this.pendingInterrupts)if(Pm(s))throw new q(`Interrupt ${s.id} expired at ${s.expiresAt}`)}let n=await W(e,this.messages,this.state,(r,o,s)=>r.onRunInitialized?.({messages:o,state:s,agent:this,input:t}));(n.messages!==void 0||n.state!==void 0)&&(n.messages&&(this.messages=n.messages,t.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),n.state&&(this.state=n.state,t.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}onError(t,e,n){return Vt(W(n,this.messages,this.state,(r,o,s)=>r.onRunFailed?.({error:e,messages:o,state:s,agent:this,input:t}))).pipe(jt(r=>{let o=r;if((o.messages!==void 0||o.state!==void 0)&&(o.messages!==void 0&&(this.messages=o.messages,n.forEach(s=>{s.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),o.state!==void 0&&(this.state=o.state,n.forEach(s=>{s.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))),o.stopPropagation!==!0){let s=String(e);if(!(e.name==="AbortError"||e.message==="Fetch is aborted"||e.message==="signal is aborted without reason"||e.message==="component unmounted"||s==="component unmounted"))throw console.error("Agent execution failed:",e),e}return{}}))}async onFinalize(t,e){let n=await W(e,this.messages,this.state,(r,o,s)=>r.onRunFinalized?.({messages:o,state:s,agent:this,input:t}));(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),n.state!==void 0&&(this.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}clone(){let t=Object.create(Object.getPrototypeOf(this));return t.agentId=this.agentId,t.description=this.description,t.threadId=this.threadId,t.messages=B(this.messages),t.state=B(this.state),t._debug=this._debug,t._debugLogger=this._debugLogger,t.isRunning=this.isRunning,t.subscribers=[...this.subscribers],t.middlewares=[...this.middlewares],t.pendingInterrupts=B(this.pendingInterrupts),t}addMessage(t){this.messages.push(t),(async()=>{for(let e of this.subscribers)await e.onNewMessage?.({message:t,messages:this.messages,state:this.state,agent:this});if(t.role==="assistant"&&t.toolCalls)for(let e of t.toolCalls)for(let n of this.subscribers)await n.onNewToolCall?.({toolCall:e,messages:this.messages,state:this.state,agent:this});for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}addMessages(t){this.messages.push(...t),(async()=>{for(let e of t){for(let n of this.subscribers)await n.onNewMessage?.({message:e,messages:this.messages,state:this.state,agent:this});if(e.role==="assistant"&&e.toolCalls)for(let n of e.toolCalls)for(let r of this.subscribers)await r.onNewToolCall?.({toolCall:n,messages:this.messages,state:this.state,agent:this})}for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setMessages(t){this.messages=B(t),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(t){this.state=B(t),(async()=>{for(let e of this.subscribers)await e.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(t){this.agentId=this.agentId??ht();let e=this.prepareRunAgentInput(t);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((n,r)=>({run:o=>r.run(o,n),get messages(){return n.messages},get state(){return n.state}}),this).run(e)).pipe(Qo(this.debugLogger),Di(this.debugLogger),Mm(this.threadId,e.runId,this.agentId),n=>n.pipe(jt(r=>(this.debugLogger?.event("LEGACY","Event:",r,{type:r.type}),r))))}},Jc=class extends Wm{requestInit(t){return{method:"POST",headers:{...this.headers,"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify(t),signal:this.abortController.signal}}runAgent(t,e){return this.abortController=t?.abortController??new AbortController,super.runAgent(t,e)}abortRun(){this.abortController.abort(),super.abortRun()}constructor(t){super(t),this.abortController=new AbortController,this.url=t.url,this.headers=B(t.headers??{}),this.fetch=t.fetch??fetch}run(t){return xm(vm(()=>this.fetch(this.url,this.requestInit(t))),this.debugLogger)}clone(){let t=super.clone();t.url=this.url,t.headers=B(this.headers??{}),t.fetch=this.fetch;let e=new AbortController,n=this.abortController.signal;return n.aborted&&e.abort(n.reason),t.abortController=e,t}};var tr=class{#e;#n;#r;#a;#l;#s;#t=!1;constructor(e){this.#e=e.agent,this.#n=e.handlers,this.#r=e.getTools??(()=>[]),this.#a=e.getContext??(()=>[]),this.#l=e.executeTool??null,this.#s=e.onPersist??(()=>{})}get running(){return this.#e.isRunning}get messages(){return this.#e.messages}async send(e){this.#e.addMessage({id:ze(),role:"user",content:e}),this.#s(this.#e.messages),await this.#o()}async resume(){await this.#o()}addToolResult(e,n){this.#e.addMessage({id:ze(),role:"tool",content:n,toolCallId:e}),this.#s(this.#e.messages)}cancel(){this.#t=!0,this.#e.abortRun()}async#o(){this.#t=!1;try{await this.#p(),this.#t&&this.#i()}catch(e){this.#t||Xm(e)?this.#i():this.#n.onError(e instanceof Error?e.message:String(e))}finally{this.#n.onSettled()}}#i(){this.#s(this.#e.messages),this.#n.onCancelled()}async#p(){for(let e=0;e<Ts;e+=1){if(this.#t)return;let n=[];if(await this.#e.runAgent({tools:this.#r(),context:this.#a()},this.#u(n)),this.#s(this.#e.messages),this.#t||this.#l===null||n.length===0)return;let r=!1;for(let o of n){let s=await this.#l(o);if(s!==null){if(s.halt===!0)return;this.#e.addMessage({id:ze(),role:"tool",content:s.content,toolCallId:o.id}),this.#s(this.#e.messages),r=!0}}if(!r)return}}#u(e){let n=this.#n;return{onRunInitialized(){n.onRunStart()},onTextMessageContentEvent({textMessageBuffer:r}){n.onTextDelta(r)},onTextMessageEndEvent({textMessageBuffer:r}){n.onTextEnd(r)},onToolCallEndEvent({event:r,toolCallName:o,toolCallArgs:s}){let i={id:r.toolCallId,name:o,args:s};e.push(i),n.onToolCall(i)},onToolCallResultEvent({event:r}){n.onToolResult(r.toolCallId,r.content)},onRunErrorEvent({event:r}){n.onError(r.message)},onRunFinalized(){n.onRunEnd()}}}};function Xm(t){return t instanceof Error&&t.name==="AbortError"}var nr="ag-ui-chat:thread",Hi="ag-ui-chat:threads",Fi="ag-ui-chat:messages:",$i="ag-ui-chat:checkpoint:",Zm=60,Km=100,Ym="New conversation",Zt=class{threadId(){let e=sessionStorage.getItem(nr);if(e!==null)return e;let n=ze();return sessionStorage.setItem(nr,n),n}loadMessages(e){return Promise.resolve(this.#a(Fi+e))}saveMessages(e,n){sessionStorage.setItem(Fi+e,JSON.stringify(n)),this.#e(e,n)}loadCheckpoint(e){return this.#a($i+e)}saveCheckpoint(e,n){let r=$i+e;if(n===null){sessionStorage.removeItem(r);return}sessionStorage.setItem(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(Fi+e),sessionStorage.removeItem($i+e),this.#r(this.#n().filter(n=>n.threadId!==e)),sessionStorage.getItem(nr)===e&&sessionStorage.removeItem(nr)}listThreads(){let e=this.#n().sort((n,r)=>r.updatedAt-n.updatedAt).map(({threadId:n,title:r,updatedAt:o,preview:s})=>({threadId:n,title:r,updatedAt:o,preview:s}));return Promise.resolve(e)}setActiveThread(e){sessionStorage.setItem(nr,e)}renameThread(e,n){let r=this.#n(),o=r.find(s=>s.threadId===e);o!==void 0&&(o.title=n,o.titleCustom=!0,this.#r(r))}#e(e,n){let r=this.#n(),o=r.find(a=>a.threadId===e),s=qm(n),i=Date.now();o===void 0?r.push({threadId:e,title:Qc(n),titleCustom:!1,preview:s,updatedAt:i}):(o.preview=s,o.updatedAt=i,o.titleCustom||(o.title=Qc(n))),this.#r(r)}#n(){return this.#a(Hi)??[]}#r(e){if(e.length===0){sessionStorage.removeItem(Hi);return}sessionStorage.setItem(Hi,JSON.stringify(e))}#a(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function Qc(t){for(let e of t)if(e.role==="user"){let n=eu(e.content);if(n!=="")return tu(n,Zm)}return Ym}function qm(t){for(let e of[...t].reverse()){let n=eu(e.content);if(n!=="")return tu(n,Km)}return""}function eu(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function tu(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function zi(t){return new Jc({url:t.endpoint,headers:t.headers??{},fetch:(e,n)=>{let r=t.getHeaders?.();if(r===void 0)return fetch(e,n);let o=new Headers(n?.headers);for(let[s,i]of Object.entries(r))o.set(s,i);return fetch(e,{...n,headers:o})},...t.threadId!==void 0?{threadId:t.threadId}:{},...t.initialMessages!==void 0?{initialMessages:[...t.initialMessages]}:{}})}var rr=class{#e;#n;#r;#a=new Set;#l=new Map;constructor(e,n=()=>({}),r=new Zt){this.#e=e.endsWith("/")?e:`${e}/`,this.#n=n,this.#r=r}threadId(){return this.#r.threadId()}setActiveThread(e){this.#r.setActiveThread(e)}saveMessages(e,n){this.#r.saveMessages(e,n)}loadCheckpoint(e){return this.#r.loadCheckpoint(e)}saveCheckpoint(e,n){this.#r.saveCheckpoint(e,n)}renameThread(e,n){this.#r.renameThread(e,n),this.#l.set(e,n),this.#i(e,"PATCH",{title:n})}clear(e){this.#r.clear(e),this.#a.add(e),this.#i(e,"DELETE")}async listThreads(){let e=await this.#s();return e===null?this.#r.listThreads():e.filter(n=>!this.#a.has(n.thread_id)).map(n=>this.#t(n))}async loadMessages(e){let n=await this.#o(this.#e+encodeURIComponent(e)+"/");return n===null||!n.ok?this.#r.loadMessages(e):(await n.json()).messages??null}async#s(){let e=await this.#o(this.#e);return e===null||!e.ok?null:(await e.json()).threads??[]}#t(e){return{threadId:e.thread_id,title:this.#l.get(e.thread_id)??e.title,updatedAt:e.updated_at===null?0:Date.parse(e.updated_at),preview:e.preview}}async#o(e){try{return await fetch(e,{headers:this.#n()})}catch{return null}}async#i(e,n,r){let o=this.#n();try{await fetch(this.#e+encodeURIComponent(e)+"/",{method:n,headers:r===void 0?o:{...o,"content-type":"application/json"},body:r===void 0?null:JSON.stringify(r)})}catch{}}};var nu="ag-ui-chat:collapsed",or=class extends HTMLElement{agentFactory=zi;headers={};allowImages=!1;autoConfirm=!1;confirmPredicate=null;getTools=()=>[...this.#M().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#n.tools()];getContext=()=>ks(this.getPageMap,this.autoInjectPageMap);routeMap=[];navigate=null;getPageMap=null;autoInjectPageMap=!0;conversationStore=new Zt;navigationResult=()=>({navigated:!0,url:window.location.href});skillContext=()=>({});toolSummaries={};#e={};#n=new Mn;#r=new Map;#a=new Set;#l;#s;#t;#o;#i;#p;#u;#y;#f;#m=null;#_=!1;#b=null;#d=null;#S=0;#x=null;#c="";#w=[];#N=[];#R=[];#O=[];constructor(){super(),this.#l=this.attachShadow({mode:"open"}),this.#s=document.createElement("div"),this.#t=document.createElement("div"),this.#o=document.createElement("textarea"),this.#i=document.createElement("button"),this.#p=document.createElement("span"),this.#f=document.createElement("div"),this.#u=new Ar(e=>this.#W(e)),this.#y=new Ir({onSelect:e=>{this.#X(e)},onNew:()=>{this.newChat(),this.#E()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#E()},onDelete:e=>{this.#Z(e)}})}static get observedAttributes(){return["title-text"]}attributeChangedCallback(e,n,r){this.#p.textContent=r??"Assistant"}registerTool(e){this.#n.register(e)}registerStateHook(e){for(let n of Cs(e))this.#n.register(n)}#H(){return this.routeMap.length===0?[]:Is(()=>this.routeMap,()=>this.navigate)}#F(){let e=this.getPageMap;return e===null?[]:[{name:"read_page",description:"Read the current page's structure (fields, buttons, route). Call after acting to observe the result within the same turn.",parameters:{type:"object",properties:{},required:[],[Xe]:"Read the page"},handler:()=>e()}]}#M(){return[...this.#H(),...this.#F()]}#L(e){let n=this.#M().find(r=>r.name===e);return n!==void 0?n:this.#n.has(e)?this.#n.get(e):null}get endpoint(){return this.getAttribute("endpoint")??""}set endpoint(e){this.setAttribute("endpoint",e)}get toolDisplay(){let e=this.getAttribute("data-tool-display");return e===Ze.MINIMAL||e===Ze.COMPACT?e:Ze.FULL}set toolDisplay(e){this.setAttribute("data-tool-display",e)}connectedCallback(){this.#J(),sessionStorage.getItem(nu)==="1"&&this.setAttribute("collapsed",""),this.#B(),this.#z(),this.#$(),this.#c=this.conversationStore.threadId(),this.#P()}#$(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new rr(e,()=>this.headers,this.conversationStore))}async#z(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#e=As(await n.json())}catch{}}setSkills(e){this.#O=e,this.#k()}#B(){this.#u.enableChips(this.getAttribute("data-prompt-chips")==="true"),this.#u.enableSlash(this.getAttribute("data-slash-commands")==="true"),this.#R=this.#V(),this.#k(),this.#j()}#V(){let e=this.getAttribute("data-skills");if(e===null)return[];try{return _s(JSON.parse(e))}catch{return[]}}async#j(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#N=_s(await n.json()),this.#k()}catch{}}#k(){let e=new Map;for(let n of[...this.#N,...this.#R,...this.#O])e.set(n.name,n);this.#u.setSkills([...e.values()])}#W(e){let{text:n,missing:r}=xa(e.prompt,this.skillContext());if(r.length>0){this.#f.textContent=`\u201C${e.title}\u201D needs: ${r.join(", ")}`,this.#f.hidden=!1;return}this.#f.hidden=!0,this.#o.value=n,e.sendImmediately===!0?this.#I():this.#o.focus()}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(e){this.setCollapsed(e)}setCollapsed(e){e?this.setAttribute("collapsed",""):this.removeAttribute("collapsed"),sessionStorage.setItem(nu,e?"1":"0"),this.dispatchEvent(new CustomEvent(xs,{detail:{collapsed:e},bubbles:!0,composed:!0}))}toggleCollapsed(){this.setCollapsed(!this.collapsed)}newChat(){this.#g(),this.conversationStore.clear(this.#c),this.#A(),this.#c=this.conversationStore.threadId(),this.#v(!1)}#A(){this.#m=null,this.#d=null,this.#h(),this.#r.clear(),this.#a.clear(),this.#w=[],this.#t.replaceChildren()}async#X(e){e!==this.#c&&(this.#g(),this.#A(),this.conversationStore.setActiveThread(e),this.#c=e,this.#v(!1),await this.#P())}#Z(e){let n=e===this.#c;n&&this.#g(),this.conversationStore.clear(e),n&&(this.#A(),this.#c=this.conversationStore.threadId(),this.#v(!1)),this.#E()}async#E(){this.#y.setThreads(await this.conversationStore.listThreads(),this.#c)}async#P(){let e=await this.conversationStore.loadMessages(this.#c);if(e!==null){this.#w=e;for(let r of e)this.#K(r)}let n=this.conversationStore.loadCheckpoint(this.#c);n!==null&&await this.#q(n)}#K(e){let n=typeof e.content=="string"?e.content:"";if(e.role===We.USER){n!==""&&this.appendMessage(We.USER,n);return}if(e.role===We.ASSISTANT){n!==""&&this.appendMessage(We.ASSISTANT,n).classList.add("message--restored");let r=e.toolCalls;if(r!==void 0)for(let o of r)this.#C({id:o.id,name:o.function.name,args:this.#Y(o.function.arguments)});return}if(e.role==="tool"){let r=this.#r.get(e.toolCallId);r!==void 0&&r.settle(de.DONE,e.content)}}#Y(e){try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#D(e){this.getAttribute("data-text-animation")==="word"&&il(e)}async#q(e){this.conversationStore.saveCheckpoint(this.#c,null);let n=this.#U();n.addToolResult(e.toolCallId,JSON.stringify(this.navigationResult(e))),await n.resume()}appendMessage(e,n){let r=document.createElement("div");return r.className=`message message--${e}`,e===We.ASSISTANT?r.innerHTML=kr(n,{allowImages:this.allowImages}):r.textContent=n,this.#t.appendChild(r),this.#t.scrollTop=this.#t.scrollHeight,r}#J(){let e=document.createElement("style");e.textContent=al,this.#s.className="chat";let n=document.createElement("div");n.className="header";let r=this.#p;r.className="header-title",r.textContent=this.getAttribute("title-text")??"Assistant";let o=document.createElement("div");o.className="header-controls";let s=document.createElement("button");s.type="button",s.className="header-btn header-btn--history",s.title="Chat history",s.setAttribute("aria-label","Chat history"),s.textContent="\u2630",s.addEventListener("click",()=>{this.#E(),this.#y.open()});let i=document.createElement("button");i.type="button",i.className="header-btn header-btn--new",i.title="New chat",i.setAttribute("aria-label","New chat"),i.textContent="\u271A",i.addEventListener("click",()=>this.newChat());let a=document.createElement("button");a.type="button",a.className="header-btn header-btn--collapse",a.title="Collapse",a.setAttribute("aria-label","Collapse"),a.textContent="\u2014",a.addEventListener("click",()=>this.toggleCollapsed()),o.append(s,i,a),n.append(r,o),this.#t.className="messages",this.#t.setAttribute("role","log"),this.#t.setAttribute("aria-live","polite"),this.#t.setAttribute("aria-label","Conversation");let u=document.createElement("div");u.className="input-row",this.#o.className="input",this.#o.setAttribute("aria-label","Message"),this.#o.rows=2,this.#o.placeholder="Ask anything\u2026",this.#o.addEventListener("keydown",l=>this.#ee(l)),this.#o.addEventListener("input",()=>this.#Q()),this.#i.className="send",this.#i.type="button",this.#i.textContent="Send",this.#i.setAttribute("aria-label","Send"),this.#i.dataset.state="idle",this.#i.addEventListener("click",()=>{if(this.#_){this.#g();return}this.#I()}),this.#f.className="skill-hint",this.#f.hidden=!0,u.append(this.#o,this.#i),this.#s.append(n,this.#t,this.#u.palette,this.#u.chips,this.#f,u,this.#y.element),this.#l.append(e,this.#s)}#Q(){this.#u.onInput(this.#o.value),this.#f.hidden=!0}#ee(e){if(this.#u.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#_){e.preventDefault(),this.#g();return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this.#I())}#g(){this.#b?.abort(),this.#m?.cancel()}#v(e){this.#_=e;let n=e?"Stop":"Send";this.#i.textContent=n,this.#i.setAttribute("aria-label",n),this.#i.dataset.state=e?"running":"idle"}async#I(){let e=this.#o.value.trim();e!==""&&(this.appendMessage(We.USER,e),this.#o.value="",this.dispatchEvent(new CustomEvent(bs,{detail:{content:e},bubbles:!0,composed:!0})),await this.#te(e))}async#te(e){this.endpoint!==""&&await this.#U().send(e)}#U(){if(this.#m===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#c,initialMessages:this.#w});this.#m=new tr({agent:e,handlers:this.#oe(),getTools:()=>this.getTools(),getContext:()=>this.getContext(),executeTool:n=>this.#re(n),onPersist:n=>this.conversationStore.saveMessages(this.#c,n)})}return this.#m}async#ne(e,n){return this.autoConfirm?!1:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0:Ss(n.parameters)}async#re(e){let n=this.#C(e);this.#r.delete(e.id);let r=this.#L(e.name);if(r===null)return this.#a.has(e.id)||n.settle(de.DONE,"No result returned."),null;if(await this.#ne(e,r)){let s={toolName:e.name,args:e.args},i=r.parameters[Es];typeof i=="string"&&(s.message=i),this.#b=new AbortController;let a=Ns(this.#t,s,{signal:this.#b.signal});this.#t.scrollTop=this.#t.scrollHeight;let u=await a;if(this.#b=null,!u){let l="User declined the action.";return n.settle(de.DECLINED,l),this.#T(),{content:l}}}let o=ws(r.parameters)&&this.navigate===null;o&&this.conversationStore.saveCheckpoint(this.#c,{toolCallId:e.id});try{let s=await r.handler(e.args);if(o)return n.settle(de.DONE,"Navigating\u2026"),{content:"",halt:!0};let i=JSON.stringify(s??null);return n.settle(de.DONE,i),this.#T(),{content:i}}catch(s){o&&this.conversationStore.saveCheckpoint(this.#c,null);let i=s instanceof Error?s.message:String(s);return n.settle(de.ERROR,i),this.#T(),{content:`Error: ${i}`,error:i}}}#oe(){return{onRunStart:()=>{this.#v(!0),this.#T()},onTextDelta:e=>{this.#h(),this.#G(e),this.#S+=1},onTextEnd:e=>{let n=this.#G(e);this.#S<=1&&this.#D(n),this.#d=null},onToolCall:e=>{this.#h(),this.#C(e)},onToolResult:(e,n)=>{let r=this.#r.get(e);r!==void 0&&(r.settle(de.DONE,n),this.#a.add(e))},onRunEnd:()=>{this.#h(),this.#d=null},onError:e=>{this.#h(),this.#D(this.appendMessage(We.ASSISTANT,`\u26A0\uFE0F ${e}`)),this.#d=null},onCancelled:()=>{this.#h(),this.#se(),this.#d=null},onSettled:()=>{this.#h(),this.#v(!1),this.#d=null}}}#se(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("role","status"),e.textContent="\u23F9 Stopped",this.#t.appendChild(e),this.#t.scrollTop=this.#t.scrollHeight}#T(){if(this.#x!==null)return;let e=document.createElement("div");e.className="pending",e.setAttribute("role","status"),e.setAttribute("aria-label","Assistant is thinking\u2026");for(let n=0;n<3;n+=1){let r=document.createElement("span");r.className="pending-dot",e.appendChild(r)}this.#x=e,this.#t.appendChild(e),this.#t.scrollTop=this.#t.scrollHeight}#h(){this.#x?.remove(),this.#x=null}#G(e){return this.#d===null&&(this.#d=this.appendMessage(We.ASSISTANT,""),this.#S=0),this.#d.innerHTML=kr(e,{allowImages:this.allowImages}),this.#t.scrollTop=this.#t.scrollHeight,this.#d}#C(e){let n=this.#r.get(e.id);if(n!==void 0)return n;let r=this.#L(e.name)?.parameters[Xe],o=typeof r=="string"?r:this.toolSummaries[e.name]??this.#e[e.name]??Rs(e.name),s=new Fn(e.name,e.args,this.toolDisplay,o);return this.#r.set(e.id,s),this.#t.appendChild(s.element),this.#t.scrollTop=this.#t.scrollHeight,s}};function Jm(){customElements.get(yr)===void 0&&customElements.define(yr,or)}function ts(t,e){return Object.getOwnPropertyDescriptor(t,e).set}var Qm=ts(HTMLInputElement.prototype,"value"),eg=ts(HTMLTextAreaElement.prototype,"value"),tg=ts(HTMLSelectElement.prototype,"value"),ng=ts(HTMLInputElement.prototype,"checked");function Kt(t,e){t instanceof HTMLTextAreaElement?eg.call(t,e):t instanceof HTMLSelectElement?tg.call(t,e):Qm.call(t,e)}function sr(t,e){ng.call(t,e)}var ru="#4f46e5";function ns(t){return new Promise(e=>{setTimeout(e,t)})}async function Bi(t,e,n={}){let r=n.charDelayMs??35;Kt(t,""),t.dispatchEvent(new Event("input",{bubbles:!0}));for(let o of e)Kt(t,t.value+o),t.dispatchEvent(new Event("input",{bubbles:!0})),r>0&&await ns(r);t.dispatchEvent(new Event("change",{bubbles:!0}))}async function Vi(t,e={}){let n=e.highlightMs??280,r=t.style.outline,o=t.style.outlineOffset;t.style.outline=`2px solid ${ru}`,t.style.outlineOffset="2px",await ns(n),t.style.outline=r,t.style.outlineOffset=o,t.click()}function Yt(t){t.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}async function ji(t,e={}){let n=e.flashMs??200;t.focus();let r=t.style.boxShadow;t.style.boxShadow="0 0 0 3px rgba(79, 70, 229, 0.4)",await ns(n),t.style.boxShadow=r}var ou="0 0 0 3px rgba(79, 70, 229, 0.4)";function su(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Wi(t){return t<=0||su()?Promise.resolve():ns(t)}async function Xi(t,e={}){let n=e.pressMs??140,r=t.style.transform,o=t.style.transition,s=t.style.boxShadow;t.style.transition="transform 80ms ease",t.style.transform="scale(0.96)",t.style.boxShadow=ou,await Wi(n),t.style.transform=r,t.style.transition=o,t.style.boxShadow=s,t.click()}function rg(t,e){for(let n of Array.from(t.options))if(n.value===e||n.text===e)return n;return null}async function Zi(t,e,n={}){let r=rg(t,e);if(r===null)throw new Error(`no <option> matching "${e}"`);let o=n.highlightMs??220,s=t.style.outline,i=t.style.outlineOffset;t.style.outline=`2px solid ${ru}`,t.style.outlineOffset="2px",await Wi(o),Kt(t,r.value),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.outline=s,t.style.outlineOffset=i}async function Ki(t,e,n={}){let r=n.flashMs??200,o=t.style.boxShadow;t.style.boxShadow=ou,await Wi(r),sr(t,e),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.boxShadow=o}async function og(t,e,n={}){Yt(t),await ji(t,{flashMs:n.flashMs??0}),await Bi(t,e,n)}async function sg(t,e={}){Yt(t),await Vi(t,e)}async function ig(t,e={}){Yt(t),await Xi(t,e)}async function ag(t,e,n={}){Yt(t),await Zi(t,e,n)}async function lg(t,e,n={}){Yt(t),await Ki(t,e,n)}function cg(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?sr(t,!!e):Kt(t,String(e)),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}var ug="0.5.0";export{or as AgUiChat,tr as AgUiClient,Mn as ClientToolRegistry,yr as ELEMENT_TAG,Ts as MAX_TOOL_ROUNDS,We as MESSAGE_ROLE,rr as RemoteConversationStore,bs as SUBMIT_EVENT,Zt as SessionStorageStore,xs as TOGGLE_EVENT,de as TOOL_CALL_STATUS,Ze as TOOL_DISPLAY,Fn as ToolCallCard,ug as VERSION,Es as X_CONFIRM_KEY,Rn as X_DESTRUCTIVE_KEY,On as X_NAVIGATES_KEY,Xe as X_SUMMARY_KEY,sg as clickElement,zi as createHttpAgent,ks as createPageMapContext,Is as createRouteTools,Cs as createStateHookTools,Jm as defineAgUiChat,og as fillField,ji as focusWithFlash,Vi as highlightThenClick,Ss as isDestructive,ws as isNavigates,As as parseToolCatalog,su as prefersReducedMotion,ig as pressButton,Xi as pressThenClick,Rs as prettifyToolName,kr as renderMarkdown,Ns as requestConfirmation,Yt as scrollIntoCenterView,ag as selectControl,Zi as selectOption,cg as setControlValue,sr as setNativeChecked,Kt as setNativeValue,lg as toggleCheckbox,Ki as toggleControl,Bi as typeInto};
708
905
  /*! Bundled license information:
709
906
 
710
907
  dompurify/dist/purify.es.mjs: