@artooi/ag-ui-web-component 0.4.0 → 0.6.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +50 -1
  2. package/README.md +69 -2
  3. package/dist/ag-ui-web-component.bundle.js +355 -59
  4. package/dist/ag-ui-web-component.bundle.js.map +4 -4
  5. package/dist/constants.d.ts +16 -0
  6. package/dist/constants.d.ts.map +1 -1
  7. package/dist/core/ag_ui_chat.d.ts +17 -1
  8. package/dist/core/ag_ui_chat.d.ts.map +1 -1
  9. package/dist/core/agui_client.d.ts +7 -1
  10. package/dist/core/agui_client.d.ts.map +1 -1
  11. package/dist/core/attachment.d.ts +35 -0
  12. package/dist/core/attachment.d.ts.map +1 -0
  13. package/dist/core/conversation_store.d.ts +37 -8
  14. package/dist/core/conversation_store.d.ts.map +1 -1
  15. package/dist/core/remote_conversation_store.d.ts +35 -0
  16. package/dist/core/remote_conversation_store.d.ts.map +1 -0
  17. package/dist/core/upload_attachment.d.ts +32 -0
  18. package/dist/core/upload_attachment.d.ts.map +1 -0
  19. package/dist/index.d.ts +4 -1
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +1198 -24
  22. package/dist/index.js.map +4 -4
  23. package/dist/ui/attachment_chips.d.ts +13 -0
  24. package/dist/ui/attachment_chips.d.ts.map +1 -0
  25. package/dist/ui/attachment_tray.d.ts +42 -0
  26. package/dist/ui/attachment_tray.d.ts.map +1 -0
  27. package/dist/ui/relative_time.d.ts +11 -0
  28. package/dist/ui/relative_time.d.ts.map +1 -0
  29. package/dist/ui/styles.d.ts +1 -1
  30. package/dist/ui/styles.d.ts.map +1 -1
  31. package/dist/ui/thread_drawer.d.ts +33 -0
  32. package/dist/ui/thread_drawer.d.ts.map +1 -0
  33. package/package.json +1 -1
  34. package/src/constants.ts +18 -0
  35. package/src/core/ag_ui_chat.ts +267 -14
  36. package/src/core/agui_client.ts +15 -2
  37. package/src/core/attachment.ts +39 -0
  38. package/src/core/conversation_store.ts +148 -9
  39. package/src/core/remote_conversation_store.ts +147 -0
  40. package/src/core/upload_attachment.ts +113 -0
  41. package/src/index.ts +8 -0
  42. package/src/ui/attachment_chips.ts +68 -0
  43. package/src/ui/attachment_tray.ts +237 -0
  44. package/src/ui/relative_time.ts +28 -0
  45. package/src/ui/styles.ts +294 -0
  46. package/src/ui/thread_drawer.ts +200 -0
  47. package/src/version.ts +1 -1
@@ -1,15 +1,25 @@
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,n={}){return new Promise(r=>{let o=document.createElement("div");o.className="confirm",o.setAttribute("data-tool-name",t.toolName),o.setAttribute("role","group"),o.setAttribute("aria-label","Confirm action");let s=document.createElement("div");s.className="confirm-body",s.textContent=t.message??`Run \u201C${t.toolName}\u201D?`;let i=document.createElement("pre");i.className="confirm-args",i.textContent=JSON.stringify(t.args,null,2);let a=document.createElement("div");a.className="confirm-actions";let u=ba("cancel","Cancel"),c=ba("confirm","Confirm"),p=!1,m=x=>{p||(p=!0,u.disabled=!0,c.disabled=!0,o.setAttribute("data-resolved",x?"confirmed":"declined"),r(x))};if(u.addEventListener("click",()=>m(!1)),c.addEventListener("click",()=>m(!0)),n.signal?.addEventListener("abort",()=>m(!1),{once:!0}),a.append(u,c),o.append(s,i,a),e.appendChild(o),n.signal?.aborted===!0){m(!1);return}c.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 Iu=Object.defineProperty;var Es=(t,e)=>{for(var n in e)Iu(t,n,{get:e[n],enumerable:!0})};var br="ag-ui-chat",Ts="ag-ui-submit",_s="ag-ui-toggle",Xe={USER:"user",ASSISTANT:"assistant"},On="x-destructive",Ss="x-confirm",Ze="x-summary",Mn="x-navigates",ws=10,de={PENDING:"pending",DONE:"done",ERROR:"error",DECLINED:"declined"},Ge={UPLOADING:"uploading",READY:"ready",ERROR:"error"},As=10*1024*1024,Ke={MINIMAL:"minimal",COMPACT:"compact",FULL:"full"};var Cu=/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;function Ia(t,e){let n=[];return{text:t.replace(Cu,(o,s)=>{let i=e[s];return i==null||i===""?(n.includes(s)||n.push(s),o):String(i)}),missing:n}}function Nu(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 ks(t){return Array.isArray(t)?t.filter(Nu):[]}var Ln=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 Is(t){return t[On]===!0}function Cs(t){return t[Mn]===!0}function Ns(t,e){return!e||t===null?[]:[{description:"page_map",value:JSON.stringify(t())}]}function Rs(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 Ca=/:([A-Za-z_][A-Za-z0-9_]*)/g;function Ru(t){let e=[];for(let n of t.matchAll(Ca)){let r=n[1];r!==void 0&&e.push(r)}return e}function Ou(t,e,n){let r={...n};return{path:e.replace(Ca,(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 Mu(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 Os(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:[],[Ze]:"List pages"},handler:()=>t().map(n=>({...n,pathParams:Ru(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"],[Mn]:!0,[Ze]:"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}=Ou(o.id,o.path,s),l=Mu(i,a),c=e();return c!==null?c(l):window.location.assign(l),{navigated:!0,path:l}}}]}function Ms(t){let e=[{name:`read_${t.name}`,description:`Read the "${t.name}" state.`,parameters:{type:"object",properties:{},required:[],[Ze]:`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"},[On]:!0,[Ze]:`Update ${t.name}`},handler:r=>n(r)}),e}function Ls(t){let e=document.createElement("div");e.className="attachment-chips";for(let n of t)e.appendChild(Lu(n));return e}function Lu(t){let e=document.createElement("div");e.className="attachment-chip attachment-chip--ready";let n=document.createElement("span");n.className="attachment-chip-icon",n.textContent=Ps(t.mime),n.setAttribute("aria-hidden","true");let r=document.createElement("span");r.className="attachment-chip-name",r.textContent=t.name,r.title=t.name;let o=document.createElement("span");return o.className="attachment-chip-size",o.textContent=xr(t.size),e.append(n,r,o),e}function Ps(t){return t.startsWith("image/")?"\u{1F5BC}":t==="application/pdf"?"\u{1F4D5}":t.startsWith("text/")?"\u{1F4C4}":"\u{1F4CE}"}function xr(t){if(t<1024)return`${t} B`;let e=["KB","MB","GB"],n=t/1024,r=0;for(;n>=1024&&r<e.length-1;)n/=1024,r+=1;return`${n<10?Math.round(n*10)/10:Math.round(n)} ${e[r]}`}var ge=[];for(let t=0;t<256;++t)ge.push((t+256).toString(16).slice(1));function Na(t,e=0){return(ge[t[e+0]]+ge[t[e+1]]+ge[t[e+2]]+ge[t[e+3]]+"-"+ge[t[e+4]]+ge[t[e+5]]+"-"+ge[t[e+6]]+ge[t[e+7]]+"-"+ge[t[e+8]]+ge[t[e+9]]+"-"+ge[t[e+10]]+ge[t[e+11]]+ge[t[e+12]]+ge[t[e+13]]+ge[t[e+14]]+ge[t[e+15]]).toLowerCase()}var Ds,Pu=new Uint8Array(16);function Us(){if(!Ds){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Ds=crypto.getRandomValues.bind(crypto)}return Ds(Pu)}var Du=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Gs={randomUUID:Du};function Uu(t,e,n){if(Gs.randomUUID&&!e&&!t)return Gs.randomUUID();t=t||{};let r=t.random??t.rng?.()??Us();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 Na(r)}var ht=Uu;var u={};Es(u,{BRAND:()=>cd,DIRTY:()=>_t,EMPTY_PATH:()=>$u,INVALID:()=>O,NEVER:()=>Xd,OK:()=>xe,ParseStatus:()=>ve,Schema:()=>U,ZodAny:()=>vt,ZodArray:()=>ct,ZodBigInt:()=>wt,ZodBoolean:()=>At,ZodBranded:()=>Dn,ZodCatch:()=>Ut,ZodDate:()=>kt,ZodDefault:()=>Dt,ZodDiscriminatedUnion:()=>_r,ZodEffects:()=>Me,ZodEnum:()=>Lt,ZodError:()=>we,ZodFirstPartyTypeKind:()=>M,ZodFunction:()=>wr,ZodIntersection:()=>Rt,ZodIssueCode:()=>E,ZodLazy:()=>Ot,ZodLiteral:()=>Mt,ZodMap:()=>cn,ZodNaN:()=>dn,ZodNativeEnum:()=>Pt,ZodNever:()=>He,ZodNull:()=>Ct,ZodNullable:()=>Je,ZodNumber:()=>St,ZodObject:()=>Ae,ZodOptional:()=>Re,ZodParsedType:()=>k,ZodPipeline:()=>Un,ZodPromise:()=>yt,ZodReadonly:()=>Gt,ZodRecord:()=>Sr,ZodSchema:()=>U,ZodSet:()=>un,ZodString:()=>gt,ZodSymbol:()=>an,ZodTransformer:()=>Me,ZodTuple:()=>qe,ZodType:()=>U,ZodUndefined:()=>It,ZodUnion:()=>Nt,ZodUnknown:()=>lt,ZodVoid:()=>ln,addIssueToContext:()=>w,any:()=>yd,array:()=>Td,bigint:()=>fd,boolean:()=>$a,coerce:()=>Wd,custom:()=>Ga,date:()=>hd,datetimeRegex:()=>Da,defaultErrorMap:()=>it,discriminatedUnion:()=>Ad,effect:()=>Gd,enum:()=>Pd,function:()=>Od,getErrorMap:()=>rn,getParsedType:()=>Ye,instanceof:()=>dd,intersection:()=>kd,isAborted:()=>Er,isAsync:()=>on,isDirty:()=>Tr,isValid:()=>mt,late:()=>ud,lazy:()=>Md,literal:()=>Ld,makeIssue:()=>Pn,map:()=>Nd,nan:()=>pd,nativeEnum:()=>Dd,never:()=>xd,null:()=>vd,nullable:()=>Fd,number:()=>Fa,object:()=>_d,objectUtil:()=>Hs,oboolean:()=>jd,onumber:()=>Vd,optional:()=>Hd,ostring:()=>Bd,pipeline:()=>zd,preprocess:()=>$d,promise:()=>Ud,quotelessJson:()=>Gu,record:()=>Cd,set:()=>Rd,setErrorMap:()=>Fu,strictObject:()=>Sd,string:()=>Ha,symbol:()=>md,transformer:()=>Gd,tuple:()=>Id,undefined:()=>gd,union:()=>wd,unknown:()=>bd,util:()=>F,void:()=>Ed});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 Hs;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Hs||(Hs={}));var k=F.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ye=t=>{switch(typeof t){case"undefined":return k.undefined;case"string":return k.string;case"number":return Number.isNaN(t)?k.nan:k.number;case"boolean":return k.boolean;case"function":return k.function;case"bigint":return k.bigint;case"symbol":return k.symbol;case"object":return Array.isArray(t)?k.array:t===null?k.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?k.promise:typeof Map<"u"&&t instanceof Map?k.map:typeof Set<"u"&&t instanceof Set?k.set:typeof Date<"u"&&t instanceof Date?k.date:k.object;default:return k.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"]),Gu=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,l=0;for(;l<i.path.length;){let c=i.path[l];l===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(i))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};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 Hu=(t,e)=>{let n;switch(t.code){case E.invalid_type:t.received===k.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}},it=Hu;var Ra=it;function Fu(t){Ra=t}function rn(){return Ra}var Pn=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="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},$u=[];function w(t,e){let n=rn(),r=Pn({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===it?void 0:it].filter(o=>!!o)});t.common.issues.push(r)}var ve=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"}),_t=t=>({status:"dirty",value:t}),xe=t=>({status:"valid",value:t}),Er=t=>t.status==="aborted",Tr=t=>t.status==="dirty",mt=t=>t.status==="valid",on=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}},Oa=(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:l}=t;return i.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:o}}var U=class{get description(){return this._def.description}_getType(e){return Ye(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Ye(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ve,ctx:{common:e.parent.common,data:e.data,parsedType:Ye(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(on(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:Ye(e)},o=this._parseSync({data:e,path:r.path,parent:r});return Oa(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ye(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:Ye(e)},o=this._parse({data:e,path:r.path,parent:r}),s=await(on(o)?o:Promise.resolve(o));return Oa(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(l=>l?!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 Je.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ct.create(this)}promise(){return yt.create(this,this._def)}or(e){return Nt.create([this,e],this._def)}and(e){return Rt.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 Dt({...L(this._def),innerType:this,defaultValue:n,typeName:M.ZodDefault})}brand(){return new Dn({typeName:M.ZodBranded,type:this,...L(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Ut({...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 Un.create(this,e)}readonly(){return Gt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},zu=/^c[^\s-]{8,}$/i,Bu=/^[0-9a-z]+$/,Vu=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ju=/^[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,Wu=/^[a-z0-9_-]{21}$/i,Xu=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Zu=/^[-+]?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)?)??$/,Ku=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Yu="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Fs,qu=/^(?:(?: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])$/,Ju=/^(?:(?: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])$/,Qu=/^(([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]))$/,ed=/^(([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])$/,td=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,La="((\\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])))",rd=new RegExp(`^${La}$`);function Pa(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 od(t){return new RegExp(`^${Pa(t)}$`)}function Da(t){let e=`${La}T${Pa(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 sd(t,e){return!!((e==="v4"||!e)&&qu.test(t)||(e==="v6"||!e)&&Qu.test(t))}function id(t,e){if(!Xu.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 ad(t,e){return!!((e==="v4"||!e)&&Ju.test(t)||(e==="v6"||!e)&&ed.test(t))}var gt=class t extends U{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==k.string){let s=this._getOrReturnCtx(e);return w(s,{code:E.invalid_type,expected:k.string,received:s.parsedType}),O}let r=new ve,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")Ku.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")Fs||(Fs=new RegExp(Yu,"u")),Fs.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")ju.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")Wu.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")zu.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")Bu.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")Vu.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"?Da(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"?rd.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{code:E.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?od(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"?Zu.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"duration",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?sd(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"?id(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"?ad(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"?td.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"base64",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?nd.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 ld(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 St=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)!==k.number){let s=this._getOrReturnCtx(e);return w(s,{code:E.invalid_type,expected:k.number,received:s.parsedType}),O}let r,o=new ve;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"?ld(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)}};St.create=t=>new St({checks:[],typeName:M.ZodNumber,coerce:t?.coerce||!1,...L(t)});var wt=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)!==k.bigint)return this._getInvalidInput(e);let r,o=new ve;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:k.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}};wt.create=t=>new wt({checks:[],typeName:M.ZodBigInt,coerce:t?.coerce??!1,...L(t)});var At=class extends U{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==k.boolean){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:k.boolean,received:r.parsedType}),O}return xe(e.data)}};At.create=t=>new At({typeName:M.ZodBoolean,coerce:t?.coerce||!1,...L(t)});var kt=class t extends U{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==k.date){let s=this._getOrReturnCtx(e);return w(s,{code:E.invalid_type,expected:k.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 ve,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}};kt.create=t=>new kt({checks:[],coerce:t?.coerce||!1,typeName:M.ZodDate,...L(t)});var an=class extends U{_parse(e){if(this._getType(e)!==k.symbol){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:k.symbol,received:r.parsedType}),O}return xe(e.data)}};an.create=t=>new an({typeName:M.ZodSymbol,...L(t)});var It=class extends U{_parse(e){if(this._getType(e)!==k.undefined){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:k.undefined,received:r.parsedType}),O}return xe(e.data)}};It.create=t=>new It({typeName:M.ZodUndefined,...L(t)});var Ct=class extends U{_parse(e){if(this._getType(e)!==k.null){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:k.null,received:r.parsedType}),O}return xe(e.data)}};Ct.create=t=>new Ct({typeName:M.ZodNull,...L(t)});var vt=class extends U{constructor(){super(...arguments),this._any=!0}_parse(e){return xe(e.data)}};vt.create=t=>new vt({typeName:M.ZodAny,...L(t)});var lt=class extends U{constructor(){super(...arguments),this._unknown=!0}_parse(e){return xe(e.data)}};lt.create=t=>new lt({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:k.never,received:n.parsedType}),O}};He.create=t=>new He({typeName:M.ZodNever,...L(t)});var ln=class extends U{_parse(e){if(this._getType(e)!==k.undefined){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:k.void,received:r.parsedType}),O}return xe(e.data)}};ln.create=t=>new ln({typeName:M.ZodVoid,...L(t)});var ct=class t extends U{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==k.array)return w(n,{code:E.invalid_type,expected:k.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=>ve.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new Oe(n,i,n.path,a)));return ve.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)}};ct.create=(t,e)=>new ct({type:t,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...L(e)});function sn(t){if(t instanceof Ae){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Re.create(sn(r))}return new Ae({...t._def,shape:()=>e})}else return t instanceof ct?new ct({...t._def,type:sn(t.element)}):t instanceof Re?Re.create(sn(t.unwrap())):t instanceof Je?Je.create(sn(t.unwrap())):t instanceof qe?qe.create(t.items.map(e=>sn(e))):t}var Ae=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)!==k.object){let c=this._getOrReturnCtx(e);return w(c,{code:E.invalid_type,expected:k.object,received:c.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 c in o.data)i.includes(c)||a.push(c);let l=[];for(let c of i){let p=s[c],m=o.data[c];l.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 He){let c=this._def.unknownKeys;if(c==="passthrough")for(let p of a)l.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];l.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 l){let m=await p.key,x=await p.value;c.push({key:m,value:x,alwaysSet:p.alwaysSet})}return c}).then(c=>ve.mergeObjectSync(r,c)):ve.mergeObjectSync(r,l)}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 sn(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 Ua(F.objectKeys(this.shape))}};Ae.create=(t,e)=>new Ae({shape:()=>t,unknownKeys:"strip",catchall:He.create(),typeName:M.ZodObject,...L(e)});Ae.strictCreate=(t,e)=>new Ae({shape:()=>t,unknownKeys:"strict",catchall:He.create(),typeName:M.ZodObject,...L(e)});Ae.lazycreate=(t,e)=>new Ae({shape:t,unknownKeys:"strip",catchall:He.create(),typeName:M.ZodObject,...L(e)});var Nt=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 l of r){let c={...n,common:{...n.common,issues:[]},parent:null},p=l._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(l=>new we(l));return w(n,{code:E.invalid_union,unionErrors:a}),O}}get options(){return this._def.options}};Nt.create=(t,e)=>new Nt({options:t,typeName:M.ZodUnion,...L(e)});var at=t=>t instanceof Ot?at(t.schema):t instanceof Me?at(t.innerType()):t instanceof Mt?[t.value]:t instanceof Lt?t.options:t instanceof Pt?F.objectValues(t.enum):t instanceof Dt?at(t._def.innerType):t instanceof It?[void 0]:t instanceof Ct?[null]:t instanceof Re?[void 0,...at(t.unwrap())]:t instanceof Je?[null,...at(t.unwrap())]:t instanceof Dn||t instanceof Gt?at(t.unwrap()):t instanceof Ut?at(t._def.innerType):[],_r=class t extends U{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==k.object)return w(n,{code:E.invalid_type,expected:k.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=at(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 $s(t,e){let n=Ye(t),r=Ye(e);if(t===e)return{valid:!0,data:t};if(n===k.object&&r===k.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 l=$s(t[a],e[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}else if(n===k.array&&r===k.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],l=$s(i,a);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===k.date&&r===k.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Rt=class extends U{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(Er(s)||Er(i))return O;let a=$s(s.value,i.value);return a.valid?((Tr(s)||Tr(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}))}};Rt.create=(t,e,n)=>new Rt({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!==k.array)return w(r,{code:E.invalid_type,expected:k.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 l=this._def.items[a]||this._def.rest;return l?l._parse(new Oe(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>ve.mergeArray(n,i)):ve.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 Sr=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!==k.object)return w(r,{code:E.invalid_type,expected:k.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?ve.mergeObjectAsync(n,o):ve.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)})}},cn=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!==k.map)return w(r,{code:E.invalid_type,expected:k.map,received:r.parsedType}),O;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,l],c)=>({key:o._parse(new Oe(r,a,r.path,[c,"key"])),value:s._parse(new Oe(r,l,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of i){let c=await l.key,p=await l.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 l of i){let c=l.key,p=l.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}}}};cn.create=(t,e,n)=>new cn({valueType:e,keyType:t,typeName:M.ZodMap,...L(n)});var un=class t extends U{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.set)return w(r,{code:E.invalid_type,expected:k.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(l){let c=new Set;for(let p of l){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((l,c)=>s._parse(new Oe(r,l,r.path,c)));return r.common.async?Promise.all(a).then(l=>i(l)):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)}};un.create=(t,e)=>new un({valueType:t,minSize:null,maxSize:null,typeName:M.ZodSet,...L(e)});var wr=class t extends U{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==k.function)return w(n,{code:E.invalid_type,expected:k.function,received:n.parsedType}),O;function r(a,l){return Pn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,rn(),it].filter(c=>!!c),issueData:{code:E.invalid_arguments,argumentsError:l}})}function o(a,l){return Pn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,rn(),it].filter(c=>!!c),issueData:{code:E.invalid_return_type,returnTypeError:l}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof yt){let a=this;return xe(async function(...l){let c=new we([]),p=await a._def.args.parseAsync(l,s).catch(f=>{throw c.addIssue(r(l,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 xe(function(...l){let c=a._def.args.safeParse(l,s);if(!c.success)throw new we([r(l,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(...e){return new t({...this._def,args:qe.create(e).rest(lt.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(lt.create()),returns:n||lt.create(),typeName:M.ZodFunction,...L(r)})}},Ot=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})}};Ot.create=(t,e)=>new Ot({getter:t,typeName:M.ZodLazy,...L(e)});var Mt=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}};Mt.create=(t,e)=>new Mt({value:t,typeName:M.ZodLiteral,...L(e)});function Ua(t,e){return new Lt({values:t,typeName:M.ZodEnum,...L(e)})}var Lt=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 xe(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})}};Lt.create=Ua;var Pt=class extends U{_parse(e){let n=F.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==k.string&&r.parsedType!==k.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 xe(e.data)}get enum(){return this._def.values}};Pt.create=(t,e)=>new Pt({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!==k.promise&&n.common.async===!1)return w(n,{code:E.invalid_type,expected:k.promise,received:n.parsedType}),O;let r=n.parsedType===k.promise?n.data:Promise.resolve(n.data);return xe(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 l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?O:l.status==="dirty"?_t(l.value):n.value==="dirty"?_t(l.value):l});{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"?_t(a.value):n.value==="dirty"?_t(a.value):a}}if(o.type==="refinement"){let i=a=>{let l=o.refinement(a,s);if(r.common.async)return Promise.resolve(l);if(l 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)===k.undefined?xe(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 Je=class extends U{_parse(e){return this._getType(e)===k.null?xe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Je.create=(t,e)=>new Je({innerType:t,typeName:M.ZodNullable,...L(e)});var Dt=class extends U{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===k.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Dt.create=(t,e)=>new Dt({innerType:t,typeName:M.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...L(e)});var Ut=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 on(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}};Ut.create=(t,e)=>new Ut({innerType:t,typeName:M.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...L(e)});var dn=class extends U{_parse(e){if(this._getType(e)!==k.nan){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:k.nan,received:r.parsedType}),O}return{status:"valid",value:e.data}}};dn.create=t=>new dn({typeName:M.ZodNaN,...L(t)});var cd=Symbol("zod_brand"),Dn=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}},Un=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(),_t(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})}},Gt=class extends U{_parse(e){let n=this._def.innerType._parse(e),r=o=>(mt(o)&&(o.value=Object.freeze(o.value)),o);return on(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Gt.create=(t,e)=>new Gt({innerType:t,typeName:M.ZodReadonly,...L(e)});function Ma(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Ga(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=Ma(e,r),l=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:l})}});if(!s){let i=Ma(e,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):vt.create()}var ud={object:Ae.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 dd=(t,e={message:`Input not instance of ${t.name}`})=>Ga(n=>n instanceof t,e),Ha=gt.create,Fa=St.create,pd=dn.create,fd=wt.create,$a=At.create,hd=kt.create,md=an.create,gd=It.create,vd=Ct.create,yd=vt.create,bd=lt.create,xd=He.create,Ed=ln.create,Td=ct.create,_d=Ae.create,Sd=Ae.strictCreate,wd=Nt.create,Ad=_r.create,kd=Rt.create,Id=qe.create,Cd=Sr.create,Nd=cn.create,Rd=un.create,Od=wr.create,Md=Ot.create,Ld=Mt.create,Pd=Lt.create,Dd=Pt.create,Ud=yt.create,Gd=Me.create,Hd=Re.create,Fd=Je.create,$d=Me.createWithPreprocess,zd=Un.create,Bd=()=>Ha().optional(),Vd=()=>Fa().optional(),jd=()=>$a().optional(),Wd={string:(t=>gt.create({...t,coerce:!0})),number:(t=>St.create({...t,coerce:!0})),boolean:(t=>At.create({...t,coerce:!0})),bigint:(t=>wt.create({...t,coerce:!0})),date:(t=>kt.create({...t,coerce:!0}))};var Xd=O;var Zd=u.object({name:u.string(),arguments:u.string()}),Kd=u.object({id:u.string(),type:u.literal("function"),function:Zd,encryptedValue:u.string().optional()}),Ar=u.object({id:u.string(),role:u.string(),content:u.string().optional(),name:u.string().optional(),encryptedValue:u.string().optional()}),Yd=u.object({type:u.literal("text"),text:u.string()}),qd=u.object({type:u.literal("data"),value:u.string(),mimeType:u.string()}),Jd=u.object({type:u.literal("url"),value:u.string(),mimeType:u.string().optional()}),kr=u.discriminatedUnion("type",[qd,Jd]),Qd=u.object({type:u.literal("image"),source:kr,metadata:u.unknown().optional()}),ep=u.object({type:u.literal("audio"),source:kr,metadata:u.unknown().optional()}),tp=u.object({type:u.literal("video"),source:kr,metadata:u.unknown().optional()}),np=u.object({type:u.literal("document"),source:kr,metadata:u.unknown().optional()});var za=u.object({type:u.literal("binary"),mimeType:u.string(),id:u.string().optional(),url:u.string().optional(),data:u.string().optional(),filename:u.string().optional()}),Ba=(t,e)=>{!t.id&&!t.url&&!t.data&&e.addIssue({code:u.ZodIssueCode.custom,message:"BinaryInputContent requires at least one of id, url, or data.",path:["id"]})},Ev=za.superRefine((t,e)=>{Ba(t,e)}),rp=u.discriminatedUnion("type",[Yd,Qd,ep,tp,np,za]),op=rp.superRefine((t,e)=>{t.type==="binary"&&Ba(t,e)}),sp=Ar.extend({role:u.literal("developer"),content:u.string()}),ip=Ar.extend({role:u.literal("system"),content:u.string()}),ap=Ar.extend({role:u.literal("assistant"),content:u.string().optional(),toolCalls:u.array(Kd).optional()}),lp=Ar.extend({role:u.literal("user"),content:u.union([u.string(),u.array(op)])}),cp=u.object({id:u.string(),content:u.string(),role:u.literal("tool"),toolCallId:u.string(),error:u.string().optional(),encryptedValue:u.string().optional()}),up=u.object({id:u.string(),role:u.literal("activity"),activityType:u.string(),content:u.record(u.any())}),dp=u.object({id:u.string(),role:u.literal("reasoning"),content:u.string(),encryptedValue:u.string().optional()}),Va=u.discriminatedUnion("role",[sp,ip,ap,lp,cp,up,dp]),Tv=u.union([u.literal("developer"),u.literal("system"),u.literal("assistant"),u.literal("user"),u.literal("tool"),u.literal("activity"),u.literal("reasoning")]),pp=u.object({description:u.string(),value:u.string()}),ja=u.object({name:u.string(),description:u.string(),parameters:u.any(),metadata:u.record(u.any()).optional()}),fp=u.object({id:u.string(),reason:u.string(),message:u.string().optional(),toolCallId:u.string().optional(),responseSchema:u.record(u.any()).optional(),expiresAt:u.string().optional(),metadata:u.record(u.any()).optional()}),hp=u.object({interruptId:u.string(),status:u.enum(["resolved","cancelled"]),payload:u.any().optional()}),mp=u.object({threadId:u.string(),runId:u.string(),parentRunId:u.string().optional(),state:u.any(),messages:u.array(Va),tools:u.array(ja),context:u.array(pp),forwardedProps:u.any(),resume:u.array(hp).optional()}),gp=u.any(),q=class extends Error{constructor(t){super(t)}},zs=class extends q{constructor(){super("Connect not implemented. This method is not supported by the current agent.")}},vp=u.object({name:u.string(),description:u.string().optional()}),yp=u.object({name:u.string().optional(),type:u.string().optional(),description:u.string().optional(),version:u.string().optional(),provider:u.string().optional(),documentationUrl:u.string().optional(),metadata:u.record(u.unknown()).optional()}),bp=u.object({streaming:u.boolean().optional(),websocket:u.boolean().optional(),httpBinary:u.boolean().optional(),pushNotifications:u.boolean().optional(),resumable:u.boolean().optional()}),xp=u.object({supported:u.boolean().optional(),items:u.array(ja).optional(),parallelCalls:u.boolean().optional(),clientProvided:u.boolean().optional()}),Ep=u.object({structuredOutput:u.boolean().optional(),supportedMimeTypes:u.array(u.string()).optional()}),Tp=u.object({snapshots:u.boolean().optional(),deltas:u.boolean().optional(),memory:u.boolean().optional(),persistentState:u.boolean().optional()}),_p=u.object({supported:u.boolean().optional(),delegation:u.boolean().optional(),handoffs:u.boolean().optional(),subAgents:u.array(vp).optional()}),Sp=u.object({supported:u.boolean().optional(),streaming:u.boolean().optional(),encrypted:u.boolean().optional()}),wp=u.object({image:u.boolean().optional(),audio:u.boolean().optional(),video:u.boolean().optional(),pdf:u.boolean().optional(),file:u.boolean().optional()}),Ap=u.object({image:u.boolean().optional(),audio:u.boolean().optional()}),kp=u.object({input:wp.optional(),output:Ap.optional()}),Ip=u.object({codeExecution:u.boolean().optional(),sandboxed:u.boolean().optional(),maxIterations:u.number().optional(),maxExecutionTime:u.number().optional()}),Cp=u.object({supported:u.boolean().optional(),approvals:u.boolean().optional(),interventions:u.boolean().optional(),feedback:u.boolean().optional(),interrupts:u.boolean().optional(),approveWithEdits:u.boolean().optional()}),_v=u.object({identity:yp.optional(),transport:bp.optional(),tools:xp.optional(),output:Ep.optional(),state:Tp.optional(),multiAgent:_p.optional(),reasoning:Sp.optional(),multimodal:kp.optional(),execution:Ip.optional(),humanInTheLoop:Cp.optional(),custom:u.record(u.unknown()).optional()}),Wa=u.union([u.literal("developer"),u.literal("system"),u.literal("assistant"),u.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=u.object({type:u.nativeEnum(v),timestamp:u.number().optional(),rawEvent:u.any().optional()}).passthrough(),Np=V.extend({type:u.literal(v.TEXT_MESSAGE_START),messageId:u.string(),role:Wa.default("assistant"),name:u.string().optional()}),Xa=V.extend({type:u.literal(v.TEXT_MESSAGE_CONTENT),messageId:u.string(),delta:u.string()}),Rp=V.extend({type:u.literal(v.TEXT_MESSAGE_END),messageId:u.string()}),Op=V.extend({type:u.literal(v.TEXT_MESSAGE_CHUNK),messageId:u.string().optional(),role:Wa.optional(),delta:u.string().optional(),name:u.string().optional()}),Mp=V.extend({type:u.literal(v.THINKING_TEXT_MESSAGE_START)}),Lp=Xa.omit({messageId:!0,type:!0}).extend({type:u.literal(v.THINKING_TEXT_MESSAGE_CONTENT)}),Pp=V.extend({type:u.literal(v.THINKING_TEXT_MESSAGE_END)}),Dp=V.extend({type:u.literal(v.TOOL_CALL_START),toolCallId:u.string(),toolCallName:u.string(),parentMessageId:u.string().optional()}),Up=V.extend({type:u.literal(v.TOOL_CALL_ARGS),toolCallId:u.string(),delta:u.string()}),Gp=V.extend({type:u.literal(v.TOOL_CALL_END),toolCallId:u.string()}),Hp=V.extend({messageId:u.string(),type:u.literal(v.TOOL_CALL_RESULT),toolCallId:u.string(),content:u.string(),role:u.literal("tool").optional()}),Fp=V.extend({type:u.literal(v.TOOL_CALL_CHUNK),toolCallId:u.string().optional(),toolCallName:u.string().optional(),parentMessageId:u.string().optional(),delta:u.string().optional()}),$p=V.extend({type:u.literal(v.THINKING_START),title:u.string().optional()}),zp=V.extend({type:u.literal(v.THINKING_END)}),Bp=V.extend({type:u.literal(v.STATE_SNAPSHOT),snapshot:gp}),Vp=V.extend({type:u.literal(v.STATE_DELTA),delta:u.array(u.any())}),jp=V.extend({type:u.literal(v.MESSAGES_SNAPSHOT),messages:u.array(Va)}),Wp=V.extend({type:u.literal(v.ACTIVITY_SNAPSHOT),messageId:u.string(),activityType:u.string(),content:u.record(u.any()),replace:u.boolean().optional().default(!0)}),Xp=V.extend({type:u.literal(v.ACTIVITY_DELTA),messageId:u.string(),activityType:u.string(),patch:u.array(u.any())}),Zp=V.extend({type:u.literal(v.RAW),event:u.any(),source:u.string().optional()}),Kp=V.extend({type:u.literal(v.CUSTOM),name:u.string(),value:u.any()}),Yp=V.extend({type:u.literal(v.RUN_STARTED),threadId:u.string(),runId:u.string(),parentRunId:u.string().optional(),input:mp.optional()}),qp=u.object({type:u.literal("success")}).strict(),Jp=u.object({type:u.literal("interrupt"),interrupts:u.array(fp).min(1)}).strict(),Qp=u.discriminatedUnion("type",[qp,Jp]),ef=V.extend({type:u.literal(v.RUN_FINISHED),threadId:u.string(),runId:u.string(),result:u.any().optional(),outcome:Qp.nullable().optional().transform(t=>t??void 0)}),tf=V.extend({type:u.literal(v.RUN_ERROR),message:u.string(),code:u.string().optional()}),nf=V.extend({type:u.literal(v.STEP_STARTED),stepName:u.string()}),rf=V.extend({type:u.literal(v.STEP_FINISHED),stepName:u.string()}),of=u.union([u.literal("tool-call"),u.literal("message")]),sf=V.extend({type:u.literal(v.REASONING_START),messageId:u.string()}),af=V.extend({type:u.literal(v.REASONING_MESSAGE_START),messageId:u.string(),role:u.literal("reasoning")}),lf=V.extend({type:u.literal(v.REASONING_MESSAGE_CONTENT),messageId:u.string(),delta:u.string()}),cf=V.extend({type:u.literal(v.REASONING_MESSAGE_END),messageId:u.string()}),uf=V.extend({type:u.literal(v.REASONING_MESSAGE_CHUNK),messageId:u.string().optional(),delta:u.string().optional()}),df=V.extend({type:u.literal(v.REASONING_END),messageId:u.string()}),pf=V.extend({type:u.literal(v.REASONING_ENCRYPTED_VALUE),subtype:of,entityId:u.string(),encryptedValue:u.string()}),Ir=u.discriminatedUnion("type",[Np,Xa,Rp,Op,$p,zp,Mp,Lp,Pp,Dp,Up,Gp,Fp,Hp,Bp,Vp,jp,Wp,Xp,Zp,Kp,Yp,ef,tf,nf,rf,sf,af,lf,cf,uf,df,pf]);var Bs={};Es(Bs,{JsonPatchError:()=>ne,_areEquals:()=>Fn,applyOperation:()=>Ht,applyPatch:()=>Pr,applyReducer:()=>vf,deepClone:()=>mf,getValueByPointer:()=>Mr,validate:()=>Ka,validator:()=>Lr});var ff=(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)}})(),hf=Object.prototype.hasOwnProperty;function Nr(t,e){return hf.call(t,e)}function Rr(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)Nr(t,o)&&r.push(o);return r}function ye(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Or(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 Qe(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function Gn(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Cr(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,n=t.length;e<n;e++)if(Cr(t[e]))return!0}else if(typeof t=="object"){for(var r=Rr(t),o=r.length,s=0;s<o;s++)if(Cr(t[r[s]]))return!0}}return!1}function Za(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(`
2
+ `)}var Hn=(function(t){ff(e,t);function e(n,r,o,s,i){var a=this.constructor,l=t.call(this,Za(n,{name:r,index:o,operation:s,tree:i}))||this;return l.name=r,l.index=o,l.operation=s,l.tree=i,Object.setPrototypeOf(l,a.prototype),l.message=Za(n,{name:r,index:o,operation:s,tree:i}),l}return e})(Error);var ne=Hn,mf=ye,pn={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=Mr(n,this.path);r&&(r=ye(r));var o=Ht(n,{op:"remove",path:this.from}).removed;return Ht(n,{op:"add",path:this.path,value:o}),{newDocument:n,removed:r}},copy:function(t,e,n){var r=Mr(n,this.from);return Ht(n,{op:"add",path:this.path,value:ye(r)}),{newDocument:n}},test:function(t,e,n){return{newDocument:n,test:Fn(t[e],this.value)}},_get:function(t,e,n){return this.value=t[e],{newDocument:n}}},gf={add:function(t,e,n){return Or(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:pn.move,copy:pn.copy,test:pn.test,_get:pn._get};function Mr(t,e){if(e=="")return t;var n={op:"_get",path:e};return Ht(t,n),n.value}function Ht(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):Lr(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=Mr(t,e.from),e.op==="move"&&(i.removed=t),i;if(e.op==="test"){if(i.test=Fn(t,e.value),i.test===!1)throw new ne("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 ne("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,t);return i}}else{r||(t=ye(t));var a=e.path||"",l=a.split("/"),c=t,p=1,m=l.length,x=void 0,f=void 0,h=void 0;for(typeof n=="function"?h=n:h=Lr;;){if(f=l[p],f&&f.indexOf("~")!=-1&&(f=Gn(f)),o&&(f=="__proto__"||f=="prototype"&&p>0&&l[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=l.slice(0,p).join("/"):p==m-1&&(x=e.path),x!==void 0&&h(e,0,t,x)),p++,Array.isArray(c)){if(f==="-")f=c.length;else{if(n&&!Or(f))throw new ne("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);Or(f)&&(f=~~f)}if(p>=m){if(n&&e.op==="add"&&f>c.length)throw new ne("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=gf[e.op].call(e,c,f,t);if(i.test===!1)throw new ne("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i}}else if(p>=m){var i=pn[e.op].call(e,c,f,t);if(i.test===!1)throw new ne("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i}if(c=c[f],n&&p<m&&(!c||typeof c!="object"))throw new ne("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,t)}}}function Pr(t,e,n,r,o){if(r===void 0&&(r=!0),o===void 0&&(o=!0),n&&!Array.isArray(e))throw new ne("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(t=ye(t));for(var s=new Array(e.length),i=0,a=e.length;i<a;i++)s[i]=Ht(t,e[i],n,!0,o,i),t=s[i].newDocument;return s.newDocument=t,s}function vf(t,e,n){var r=Ht(t,e);if(r.test===!1)throw new ne("Test operation failed","TEST_OPERATION_FAILED",n,e,t);return r.newDocument}function Lr(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t))throw new ne("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,n);if(pn[t.op]){if(typeof t.path!="string")throw new ne("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,n);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new ne('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 ne("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 ne("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")&&Cr(t.value))throw new ne("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 ne("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 ne("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=Ka([i],n);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new ne("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,n)}}}else throw new ne("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,n)}function Ka(t,e,n){try{if(!Array.isArray(t))throw new ne("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Pr(ye(e),ye(t),n||!0);else{n=n||Lr;for(var r=0;r<t.length;r++)n(t[r],r,e,void 0)}}catch(o){if(o instanceof ne)return o;throw o}}function Fn(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(!Fn(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],!Fn(t[i],e[i]))return!1;return!0}return t!==t&&e!==e}var Xs={};Es(Xs,{compare:()=>wf,generate:()=>Vs,observe:()=>Sf,unobserve:()=>_f});var js=new WeakMap,yf=(function(){function t(e){this.observers=new Map,this.obj=e}return t})(),bf=(function(){function t(e,n){this.callback=e,this.observer=n}return t})();function xf(t){return js.get(t)}function Ef(t,e){return t.observers.get(e)}function Tf(t,e){t.observers.delete(e.callback)}function _f(t,e){e.unobserve()}function Sf(t,e){var n=[],r,o=xf(t);if(!o)o=new yf(t),js.set(t,o);else{var s=Ef(o,e);r=s&&s.observer}if(r)return r;if(r={},o.value=ye(t),e){r.callback=e,r.next=null;var i=function(){Vs(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(){Vs(r),clearTimeout(r.next),Tf(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 bf(e,r)),r}function Vs(t,e){e===void 0&&(e=!1);var n=js.get(t.object);Ws(n.value,t.object,t.patches,"",e),t.patches.length&&Pr(n.value,t.patches);var r=t.patches;return r.length>0&&(t.patches=[],t.callback&&t.callback(r)),r}function Ws(t,e,n,r,o){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=Rr(e),i=Rr(t),a=!1,l=!1,c=i.length-1;c>=0;c--){var p=i[c],m=t[p];if(Nr(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)?Ws(m,x,n,r+"/"+Qe(p),o):m!==x&&(a=!0,o&&n.push({op:"test",path:r+"/"+Qe(p),value:ye(m)}),n.push({op:"replace",path:r+"/"+Qe(p),value:ye(x)}))}else Array.isArray(t)===Array.isArray(e)?(o&&n.push({op:"test",path:r+"/"+Qe(p),value:ye(m)}),n.push({op:"remove",path:r+"/"+Qe(p)}),l=!0):(o&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:e}),a=!0)}if(!(!l&&s.length==i.length))for(var c=0;c<s.length;c++){var p=s[c];!Nr(t,p)&&e[p]!==void 0&&n.push({op:"add",path:r+"/"+Qe(p),value:ye(e[p])})}}}function wf(t,e,n){n===void 0&&(n=!1);var r=[];return Ws(t,e,r,"",n),r}var Dr=Object.assign({},Bs,Xs,{JsonPatchError:Hn,deepClone:ye,escapePathComponent:Qe,unescapePathComponent:Gn});var Zs=function(t,e){return Zs=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])},Zs(t,e)};function et(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Zs(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function Ya(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{c(r.next(p))}catch(m){i(m)}}function l(p){try{c(r.throw(p))}catch(m){i(m)}}function c(p){p.done?s(p.value):o(p.value).then(a,l)}c((r=r.apply(t,e||[])).next())})}function Ur(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(c){return function(p){return l([c,p])}}function l(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=e.call(t,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 ut(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 fn(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 hn(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 Ft(t){return this instanceof Ft?(this.v=t,this):new Ft(t)}function qa(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||l(f,g)})},h&&(o[f]=h(o[f])))}function l(f,h){try{c(r[f](h))}catch(g){x(s[0][3],g)}}function c(f){f.value instanceof Ft?Promise.resolve(f.value.v).then(p,m):x(s[0][2],f)}function p(f){l("next",f)}function m(f){l("throw",f)}function x(f,h){f(h),s.shift(),s.length&&l(s[0][0],s[0][1])}}function Ja(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 ut=="function"?ut(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,l){i=t[s](i),o(a,l,i.done,i.value)})}}function o(s,i,a,l){Promise.resolve(l).then(function(c){s({value:c,done:a})},i)}}function G(t){return typeof t=="function"}function mn(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 Gr=mn(function(t){return function(n){t(this),this.message=n?n.length+` errors occurred during unsubscription:
3
+ `+n.map(function(r,o){return o+1+") "+r.toString()}).join(`
4
+ `):"",this.name="UnsubscriptionError",this.errors=n}});function $n(t,e){if(t){var n=t.indexOf(e);0<=n&&t.splice(n,1)}}var gn=(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=ut(i),l=a.next();!l.done;l=a.next()){var c=l.value;c.remove(this)}}catch(g){e={error:g}}finally{try{l&&!l.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 Gr?g.errors:[g]}var m=this._finalizers;if(m){this._finalizers=null;try{for(var x=ut(m),f=x.next();!f.done;f=x.next()){var h=f.value;try{Qa(h)}catch(g){s=s??[],g instanceof Gr?s=hn(hn([],fn(s)),fn(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 Gr(s)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)Qa(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)&&$n(n,e)},t.prototype.remove=function(e){var n=this._finalizers;n&&$n(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})();var Ks=gn.EMPTY;function Hr(t){return t instanceof gn||t&&"closed"in t&&G(t.remove)&&G(t.add)&&G(t.unsubscribe)}function Qa(t){G(t)?t():t.unsubscribe()}var Fe={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var vn={setTimeout:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var o=vn.delegate;return o?.setTimeout?o.setTimeout.apply(o,hn([t,e],fn(n))):setTimeout.apply(void 0,hn([t,e],fn(n)))},clearTimeout:function(t){var e=vn.delegate;return(e?.clearTimeout||clearTimeout)(t)},delegate:void 0};function Fr(t){vn.setTimeout(function(){var e=Fe.onUnhandledError;if(e)e(t);else throw t})}function zn(){}var el=(function(){return Ys("C",void 0,void 0)})();function tl(t){return Ys("E",void 0,t)}function nl(t){return Ys("N",t,void 0)}function Ys(t,e,n){return{kind:t,value:e,error:n}}var $t=null;function yn(t){if(Fe.useDeprecatedSynchronousErrorHandling){var e=!$t;if(e&&($t={errorThrown:!1,error:null}),t(),e){var n=$t,r=n.errorThrown,o=n.error;if($t=null,r)throw o}}else t()}function rl(t){Fe.useDeprecatedSynchronousErrorHandling&&$t&&($t.errorThrown=!0,$t.error=t)}var Bn=(function(t){et(e,t);function e(n){var r=t.call(this)||this;return r.isStopped=!1,n?(r.destination=n,Hr(n)&&n.add(r)):r.destination=Cf,r}return e.create=function(n,r,o){return new zr(n,r,o)},e.prototype.next=function(n){this.isStopped?Js(nl(n),this):this._next(n)},e.prototype.error=function(n){this.isStopped?Js(tl(n),this):(this.isStopped=!0,this._error(n))},e.prototype.complete=function(){this.isStopped?Js(el,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})(gn);var Af=Function.prototype.bind;function qs(t,e){return Af.call(t,e)}var kf=(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){$r(r)}},t.prototype.error=function(e){var n=this.partialObserver;if(n.error)try{n.error(e)}catch(r){$r(r)}else $r(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(n){$r(n)}},t})(),zr=(function(t){et(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&&qs(n.next,a),error:n.error&&qs(n.error,a),complete:n.complete&&qs(n.complete,a)}):i=n}return s.destination=new kf(i),s}return e})(Bn);function $r(t){Fe.useDeprecatedSynchronousErrorHandling?rl(t):Fr(t)}function If(t){throw t}function Js(t,e){var n=Fe.onStoppedNotification;n&&vn.setTimeout(function(){return n(t,e)})}var Cf={closed:!0,next:zn,error:If,complete:zn};var bn=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function xn(t){return t}function Br(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return Qs(t)}function Qs(t){return t.length===0?xn: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=Rf(e)?e:new zr(e,n,r);return yn(function(){var i=o,a=i.operator,l=i.source;s.add(a?a.call(s,l):l?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=ol(n),new n(function(o,s){var i=new zr({next:function(a){try{e(a)}catch(l){s(l),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[bn]=function(){return this},t.prototype.pipe=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return Qs(e)(this)},t.prototype.toPromise=function(e){var n=this;return e=ol(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 ol(t){var e;return(e=t??Fe.Promise)!==null&&e!==void 0?e:Promise}function Nf(t){return t&&G(t.next)&&G(t.error)&&G(t.complete)}function Rf(t){return t&&t instanceof Bn||Nf(t)&&Hr(t)}function Of(t){return G(t?.lift)}function ce(t){return function(e){if(Of(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 Mf(t,e,n,r,o)}var Mf=(function(t){et(e,t);function e(n,r,o,s,i,a){var l=t.call(this,n)||this;return l.onFinalize=i,l.shouldUnsubscribe=a,l._next=r?function(c){try{r(c)}catch(p){n.error(p)}}:t.prototype._next,l._error=s?function(c){try{s(c)}catch(p){n.error(p)}finally{this.unsubscribe()}}:t.prototype._error,l._complete=o?function(){try{o()}catch(c){n.error(c)}finally{this.unsubscribe()}}:t.prototype._complete,l}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})(Bn);var sl=mn(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var tt=(function(t){et(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 il(this,this);return r.operator=n,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new sl},e.prototype.next=function(n){var r=this;yn(function(){var o,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var i=ut(r.currentObservers),a=i.next();!a.done;a=i.next()){var l=a.value;l.next(n)}}catch(c){o={error:c}}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;yn(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;yn(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?Ks:(this.currentObservers=null,a.push(n),new gn(function(){r.currentObservers=null,$n(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 il(n,r)},e})(J);var il=(function(t){et(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:Ks},e})(tt);var ei={now:function(){return(ei.delegate||Date).now()},delegate:void 0};var Vr=(function(t){et(e,t);function e(n,r,o){n===void 0&&(n=1/0),r===void 0&&(r=1/0),o===void 0&&(o=ei);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,l=r._windowTime;o||(s.push(n),!i&&s.push(a.now()+l)),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(),l=0;l<a.length&&!n.closed;l+=s?1:2)n.next(a[l]);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 l=o.now(),c=0,p=1;p<s.length&&s[p]<=l;p+=2)c=p;c&&s.splice(0,c+1)}},e})(tt);var jr=new J(function(t){return t.complete()});function al(t){return t&&G(t.schedule)}function Lf(t){return t[t.length-1]}function ll(t){return al(Lf(t))?t.pop():void 0}var Wr=(function(t){return t&&typeof t.length=="number"&&typeof t!="function"});function Xr(t){return G(t?.then)}function Zr(t){return G(t[bn])}function Kr(t){return Symbol.asyncIterator&&G(t?.[Symbol.asyncIterator])}function Yr(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 Pf(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var qr=Pf();function Jr(t){return G(t?.[qr])}function Qr(t){return qa(this,arguments,function(){var n,r,o,s;return Ur(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,Ft(n.read())];case 3:return r=i.sent(),o=r.value,s=r.done,s?[4,Ft(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,Ft(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 eo(t){return G(t?.getReader)}function me(t){if(t instanceof J)return t;if(t!=null){if(Zr(t))return Df(t);if(Wr(t))return Uf(t);if(Xr(t))return Gf(t);if(Kr(t))return cl(t);if(Jr(t))return Hf(t);if(eo(t))return Ff(t)}throw Yr(t)}function Df(t){return new J(function(e){var n=t[bn]();if(G(n.subscribe))return n.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Uf(t){return new J(function(e){for(var n=0;n<t.length&&!e.closed;n++)e.next(t[n]);e.complete()})}function Gf(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,Fr)})}function Hf(t){return new J(function(e){var n,r;try{for(var o=ut(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 cl(t){return new J(function(e){$f(t,e).catch(function(n){return e.error(n)})})}function Ff(t){return cl(Qr(t))}function $f(t,e){var n,r,o,s;return Ya(this,void 0,void 0,function(){var i,a;return Ur(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),n=Ja(t),l.label=1;case 1:return[4,n.next()];case 2:if(r=l.sent(),!!r.done)return[3,4];if(i=r.value,e.next(i),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=l.sent(),o={error:a},[3,11];case 6:return l.trys.push([6,,9,10]),r&&!r.done&&(s=n.return)?[4,s.call(n)]:[3,8];case 7:l.sent(),l.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 to(t,e){return e===void 0&&(e=0),ce(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 no(t,e){return e===void 0&&(e=0),ce(function(n,r){r.add(t.schedule(function(){return n.subscribe(r)},e))})}function ul(t,e){return me(t).pipe(no(e),to(e))}function dl(t,e){return me(t).pipe(no(e),to(e))}function pl(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 fl(t,e){return new J(function(n){var r;return Le(n,e,function(){r=t[qr](),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 ro(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 hl(t,e){return ro(Qr(t),e)}function ml(t,e){if(t!=null){if(Zr(t))return ul(t,e);if(Wr(t))return pl(t,e);if(Xr(t))return dl(t,e);if(Kr(t))return ro(t,e);if(Jr(t))return fl(t,e);if(eo(t))return hl(t,e)}throw Yr(t)}function zt(t,e){return e?ml(t,e):me(t)}function te(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=ll(t);return zt(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 gl=mn(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function oo(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 gl)}})})}function Bt(t,e){return ce(function(n,r){var o=0;n.subscribe(he(r,function(s){r.next(t.call(e,s,o++))}))})}function vl(t,e,n,r,o,s,i,a){var l=[],c=0,p=0,m=!1,x=function(){m&&!l.length&&!c&&e.complete()},f=function(g){return c<r?h(g):l.push(g)},h=function(g){s&&e.next(g),c++;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{c--;for(var S=function(){var b=l.shift();i?Le(e,i,function(){return h(b)}):h(b)};l.length&&c<r;)S();x()}catch(b){e.error(b)}}))};return t.subscribe(he(e,f,function(){m=!0,x()})),function(){a?.()}}function ke(t,e,n){return n===void 0&&(n=1/0),G(e)?ke(function(r,o){return Bt(function(s,i){return e(r,s,o,i)})(me(t(r,o)))},n):(typeof e=="number"&&(n=e),ce(function(r,o){return vl(r,o,t,n)}))}function ti(t){return t===void 0&&(t=1/0),ke(xn,t)}function so(t){return new J(function(e){me(t()).subscribe(e)})}function Vn(t){return ce(function(e,n){var r=null,o=!1,s;r=e.subscribe(he(n,void 0,void 0,function(i){s=me(t(i,Vn(t)(e))),r?(r.unsubscribe(),r=null,s.subscribe(n)):o=!0})),o&&(r.unsubscribe(),r=null,s.subscribe(n))})}function io(t,e){return G(e)?ke(t,e,1):ke(t,1)}function ni(t){return ce(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 Vt(t){return ce(function(e,n){try{e.subscribe(n)}finally{n.add(t)}})}function ri(t,e){return ce(function(n,r){var o=null,s=0,i=!1,a=function(){return i&&!o&&r.complete()};n.subscribe(he(r,function(l){o?.unsubscribe();var c=0,p=s++;me(t(l,p)).subscribe(o=he(r,function(m){return r.next(e?e(l,m,p,c++):m)},function(){o=null,a()}))},function(){i=!0,a()}))})}function ao(t){return ce(function(e,n){me(t).subscribe(he(n,function(){return n.complete()},zn)),!n.closed&&e.subscribe(n)})}function oi(t,e,n){var r=G(t)||e||n?{next:t,error:e,complete:n}:t;return r?ce(function(o,s){var i;(i=r.subscribe)===null||i===void 0||i.call(r);var a=!0;o.subscribe(he(s,function(l){var c;(c=r.next)===null||c===void 0||c.call(r,l),s.next(l)},function(){var l;a=!1,(l=r.complete)===null||l===void 0||l.call(r),s.complete()},function(l){var c;a=!1,(c=r.error)===null||c===void 0||c.call(r,l),s.error(l)},function(){var l,c;a&&((l=r.unsubscribe)===null||l===void 0||l.call(r)),(c=r.finalize)===null||c===void 0||c.call(r)}))}):xn}function yl(t){return` \r
5
+ `.indexOf(t)>=0}function lo(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},l=function(b){r==null&&(r=n,o=e.length,s=b)},c=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"\\":l("stringEscape"),i("stringEscaped");break}break;case"stringEscaped":h==="u"?i("stringUnicode"):(c("stringEscape"),p());break;case"stringUnicode":n-t.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():yl(h)||(c("collectionItem"),a("arrayNeedsComma"),x(h));break;case"arrayNeedsComma":h==="]"?p():h===","&&(l("collectionItem"),a("arrayNeedsValue"));break;case"objectNeedsKey":h==="}"?p():h==='"'&&(l("collectionItem"),a("objectNeedsColon"),i("string"));break;case"objectNeedsColon":h===":"&&a("objectNeedsValue");break;case"objectNeedsValue":yl(h)||(c("collectionItem"),a("objectNeedsComma"),x(h));break;case"objectNeedsComma":h==="}"?p():h===","&&(l("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 xl(){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 uo(t,e,n){for(let s=0;s<28;s=s+7){let i=t>>>s,a=!(!(i>>>7)&&e==0),l=(a?i|128:i)&255;if(n.push(l),!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),l=(a?i|128:i)&255;if(n.push(l),!a)return}n.push(e>>>31&1)}}var co=4294967296;function si(t){let e=t[0]==="-";e&&(t=t.slice(1));let n=1e6,r=0,o=0;function s(i,a){let l=Number(t.slice(i,a));o*=n,r=r*n+l,r>=co&&(o=o+(r/co|0),r=r%co)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?Tl(r,o):ai(r,o)}function El(t,e){let n=ai(t,e),r=n.hi&2147483648;r&&(n=Tl(n.lo,n.hi));let o=ii(n.lo,n.hi);return r?"-"+o:o}function ii(t,e){if({lo:t,hi:e}=zf(t,e),e<=2097151)return String(co*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,l=1e7;return s>=l&&(i+=Math.floor(s/l),s%=l),i>=l&&(a+=Math.floor(i/l),i%=l),a.toString()+bl(i)+bl(s)}function zf(t,e){return{lo:t>>>0,hi:e>>>0}}function ai(t,e){return{lo:t|0,hi:e|0}}function Tl(t,e){return e=~e,t?t=~t+1:e+=1,ai(t,e)}var bl=t=>{let e=String(t);return"0000000".slice(e.length)+e};function li(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 _l(){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=Bf();function Bf(){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()),Sl(n),n},uParse(n){return typeof n!="string"&&(n=n.toString()),wl(n),n},enc(n){return typeof n!="string"&&(n=n.toString()),Sl(n),si(n)},uEnc(n){return typeof n!="string"&&(n=n.toString()),wl(n),si(n)},dec(n,r){return El(n,r)},uDec(n,r){return ii(n,r)}}}function Sl(t){if(!/^-?[0-9]+$/.test(t))throw new Error("invalid int64: "+t)}function wl(t){if(!/^[0-9]+$/.test(t))throw new Error("invalid uint64: "+t)}var ci=Symbol.for("@bufbuild/protobuf/text-encoding");function ui(){if(globalThis[ci]==null){let t=new globalThis.TextEncoder,e=new globalThis.TextDecoder,n;globalThis[ci]={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[ci]}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 Vf=34028234663852886e22,jf=-34028234663852886e22,Wf=4294967295,Xf=2147483647,Zf=-2147483648,P=class{constructor(e=ui().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(Al(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return di(e),li(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){Kf(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){Al(e);let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e,!0),this.raw(n)}sfixed32(e){di(e);let n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,e,!0),this.raw(n)}sint32(e){return di(e),e=(e<<1^e>>31)>>>0,li(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 uo(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 uo(o,s,this.buf),this}uint64(e){let n=$e.uEnc(e);return uo(n.lo,n.hi,this.buf),this}},_=class{constructor(e,n=ui().decodeUtf8){this.decodeUtf8=n,this.varint64=xl,this.uint32=_l,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 di(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>Xf||t<Zf)throw new Error("invalid int32: "+t)}function Al(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>Wf||t<0)throw new Error("invalid uint32: "+t)}function Kf(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>Vf||t<jf))throw new Error("invalid float32: "+t)}var Yf=(function(t){return t[t.NULL_VALUE=0]="NULL_VALUE",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function pi(){return{fields:{}}}var jn={encode(t,e=new P){return Object.entries(t.fields).forEach(([n,r])=>{r!==void 0&&mi.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=pi();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:{if(s!==10)break;let i=mi.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 jn.fromPartial(t??{})},fromPartial(t){let e=pi();return e.fields=Object.entries(t.fields??{}).reduce((n,[r,o])=>(o!==void 0&&(n[r]=o),n),{}),e},wrap(t){let e=pi();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 kl(){return{key:"",value:void 0}}var mi={encode(t,e=new P){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=kl();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 mi.fromPartial(t??{})},fromPartial(t){let e=kl();return e.key=t.key??"",e.value=t.value??void 0,e}};function fi(){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 P){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&&jn.encode(jn.wrap(t.structValue),e.uint32(42).fork()).join(),t.listValue!==void 0&&Wn.encode(Wn.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=fi();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=jn.unwrap(jn.decode(n,n.uint32()));continue;case 6:if(s!==50)break;o.listValue=Wn.unwrap(Wn.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=fi();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=fi();if(t===null)e.nullValue=Yf.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 hi(){return{values:[]}}var Wn={encode(t,e=new P){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=hi();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 Wn.fromPartial(t??{})},fromPartial(t){let e=hi();return e.values=t.values?.map(n=>n)||[],e},wrap(t){let e=hi();return e.values=t??[],e},unwrap(t){return t?.hasOwnProperty("values")&&globalThis.Array.isArray(t.values)?t.values:t}},qf=(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 Il(){return{op:0,path:"",from:void 0,value:void 0}}var fo={encode(t,e=new P){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=Il();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 fo.fromPartial(t??{})},fromPartial(t){let e=Il();return e.op=t.op??0,e.path=t.path??"",e.from=t.from??void 0,e.value=t.value??void 0,e}};function Cl(){return{id:"",type:"",function:void 0}}var ho={encode(t,e=new P){return t.id!==""&&e.uint32(10).string(t.id),t.type!==""&&e.uint32(18).string(t.type),t.function!==void 0&&mo.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=Cl();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=mo.decode(n,n.uint32());continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return ho.fromPartial(t??{})},fromPartial(t){let e=Cl();return e.id=t.id??"",e.type=t.type??"",e.function=t.function!==void 0&&t.function!==null?mo.fromPartial(t.function):void 0,e}};function Nl(){return{name:"",arguments:""}}var mo={encode(t,e=new P){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=Nl();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 mo.fromPartial(t??{})},fromPartial(t){let e=Nl();return e.name=t.name??"",e.arguments=t.arguments??"",e}};function Rl(){return{value:"",mimeType:""}}var go={encode(t,e=new P){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=Rl();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 go.fromPartial(t??{})},fromPartial(t){let e=Rl();return e.value=t.value??"",e.mimeType=t.mimeType??"",e}};function Ol(){return{value:"",mimeType:void 0}}var vo={encode(t,e=new P){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=Ol();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 vo.fromPartial(t??{})},fromPartial(t){let e=Ol();return e.value=t.value??"",e.mimeType=t.mimeType??void 0,e}};function Ml(){return{data:void 0,url:void 0}}var Ie={encode(t,e=new P){return t.data!==void 0&&go.encode(t.data,e.uint32(10).fork()).join(),t.url!==void 0&&vo.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=Ml();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.data=go.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.url=vo.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=Ml();return e.data=t.data!==void 0&&t.data!==null?go.fromPartial(t.data):void 0,e.url=t.url!==void 0&&t.url!==null?vo.fromPartial(t.url):void 0,e}};function Ll(){return{text:""}}var yo={encode(t,e=new P){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=Ll();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 yo.fromPartial(t??{})},fromPartial(t){let e=Ll();return e.text=t.text??"",e}};function Pl(){return{source:void 0,metadata:void 0}}var bo={encode(t,e=new P){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=Pl();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 bo.fromPartial(t??{})},fromPartial(t){let e=Pl();return e.source=t.source!==void 0&&t.source!==null?Ie.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Dl(){return{source:void 0,metadata:void 0}}var xo={encode(t,e=new P){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=Dl();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 xo.fromPartial(t??{})},fromPartial(t){let e=Dl();return e.source=t.source!==void 0&&t.source!==null?Ie.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Ul(){return{source:void 0,metadata:void 0}}var Eo={encode(t,e=new P){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=Ul();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 Eo.fromPartial(t??{})},fromPartial(t){let e=Ul();return e.source=t.source!==void 0&&t.source!==null?Ie.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Gl(){return{source:void 0,metadata:void 0}}var To={encode(t,e=new P){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=Gl();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 To.fromPartial(t??{})},fromPartial(t){let e=Gl();return e.source=t.source!==void 0&&t.source!==null?Ie.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Hl(){return{text:void 0,image:void 0,audio:void 0,video:void 0,document:void 0}}var _o={encode(t,e=new P){return t.text!==void 0&&yo.encode(t.text,e.uint32(10).fork()).join(),t.image!==void 0&&bo.encode(t.image,e.uint32(18).fork()).join(),t.audio!==void 0&&xo.encode(t.audio,e.uint32(26).fork()).join(),t.video!==void 0&&Eo.encode(t.video,e.uint32(34).fork()).join(),t.document!==void 0&&To.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=Hl();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.text=yo.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.image=bo.decode(n,n.uint32());continue;case 3:if(s!==26)break;o.audio=xo.decode(n,n.uint32());continue;case 4:if(s!==34)break;o.video=Eo.decode(n,n.uint32());continue;case 5:if(s!==42)break;o.document=To.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=Hl();return e.text=t.text!==void 0&&t.text!==null?yo.fromPartial(t.text):void 0,e.image=t.image!==void 0&&t.image!==null?bo.fromPartial(t.image):void 0,e.audio=t.audio!==void 0&&t.audio!==null?xo.fromPartial(t.audio):void 0,e.video=t.video!==void 0&&t.video!==null?Eo.fromPartial(t.video):void 0,e.document=t.document!==void 0&&t.document!==null?To.fromPartial(t.document):void 0,e}};function Fl(){return{id:"",role:"",content:void 0,name:void 0,toolCalls:[],toolCallId:void 0,error:void 0,contentParts:[]}}var So={encode(t,e=new P){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)ho.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)_o.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=Fl();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(ho.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(_o.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return So.fromPartial(t??{})},fromPartial(t){let e=Fl();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=>ho.fromPartial(n))||[],e.toolCallId=t.toolCallId??void 0,e.error=t.error??void 0,e.contentParts=t.contentParts?.map(n=>_o.fromPartial(n))||[],e}};function $l(){return{id:"",reason:"",message:void 0,toolCallId:void 0,responseSchema:void 0,expiresAt:void 0,metadata:void 0}}var wo={encode(t,e=new P){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=$l();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 wo.fromPartial(t??{})},fromPartial(t){let e=$l();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}},Jf=(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 zl(){return{type:0,timestamp:void 0,rawEvent:void 0}}var R={encode(t,e=new P){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=zl();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=Qf(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=zl();return e.type=t.type??0,e.timestamp=t.timestamp??void 0,e.rawEvent=t.rawEvent??void 0,e}};function Bl(){return{baseEvent:void 0,messageId:"",role:void 0,name:void 0}}var Ao={encode(t,e=new P){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=Bl();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 Ao.fromPartial(t??{})},fromPartial(t){let e=Bl();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 Vl(){return{baseEvent:void 0,messageId:"",delta:""}}var ko={encode(t,e=new P){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=Vl();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 ko.fromPartial(t??{})},fromPartial(t){let e=Vl();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 jl(){return{baseEvent:void 0,messageId:""}}var Io={encode(t,e=new P){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=jl();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 Io.fromPartial(t??{})},fromPartial(t){let e=jl();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e}};function Wl(){return{baseEvent:void 0,toolCallId:"",toolCallName:"",parentMessageId:void 0}}var Co={encode(t,e=new P){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=Wl();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 Co.fromPartial(t??{})},fromPartial(t){let e=Wl();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 Xl(){return{baseEvent:void 0,toolCallId:"",delta:""}}var No={encode(t,e=new P){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=Xl();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 No.fromPartial(t??{})},fromPartial(t){let e=Xl();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 Zl(){return{baseEvent:void 0,toolCallId:""}}var Ro={encode(t,e=new P){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=Zl();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 Ro.fromPartial(t??{})},fromPartial(t){let e=Zl();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e}};function Kl(){return{baseEvent:void 0,snapshot:void 0}}var Oo={encode(t,e=new P){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=Kl();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 Oo.fromPartial(t??{})},fromPartial(t){let e=Kl();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.snapshot=t.snapshot??void 0,e}};function Yl(){return{baseEvent:void 0,delta:[]}}var Mo={encode(t,e=new P){t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.delta)fo.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=Yl();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(fo.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=Yl();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.delta=t.delta?.map(n=>fo.fromPartial(n))||[],e}};function ql(){return{baseEvent:void 0,messages:[]}}var Lo={encode(t,e=new P){t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.messages)So.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=ql();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(So.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Lo.fromPartial(t??{})},fromPartial(t){let e=ql();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.messages=t.messages?.map(n=>So.fromPartial(n))||[],e}};function Jl(){return{baseEvent:void 0,event:void 0,source:void 0}}var Po={encode(t,e=new P){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=Jl();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 Po.fromPartial(t??{})},fromPartial(t){let e=Jl();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 Ql(){return{baseEvent:void 0,name:"",value:void 0}}var Do={encode(t,e=new P){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=Ql();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 Do.fromPartial(t??{})},fromPartial(t){let e=Ql();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 ec(){return{baseEvent:void 0,threadId:"",runId:""}}var Uo={encode(t,e=new P){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=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.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 Uo.fromPartial(t??{})},fromPartial(t){let e=ec();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 tc(){return{baseEvent:void 0,threadId:"",runId:"",result:void 0,outcome:"",interrupts:[]}}var Go={encode(t,e=new P){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)wo.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=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.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(wo.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Go.fromPartial(t??{})},fromPartial(t){let e=tc();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=>wo.fromPartial(n))||[],e}};function nc(){return{baseEvent:void 0,code:void 0,message:""}}var Ho={encode(t,e=new P){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=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.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 Ho.fromPartial(t??{})},fromPartial(t){let e=nc();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 rc(){return{baseEvent:void 0,stepName:""}}var Fo={encode(t,e=new P){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=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.stepName=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Fo.fromPartial(t??{})},fromPartial(t){let e=rc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function oc(){return{baseEvent:void 0,stepName:""}}var $o={encode(t,e=new P){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=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.stepName=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=oc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function sc(){return{baseEvent:void 0,messageId:void 0,role:void 0,delta:void 0,name:void 0}}var zo={encode(t,e=new P){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=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.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 zo.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??void 0,e.role=t.role??void 0,e.delta=t.delta??void 0,e.name=t.name??void 0,e}};function ic(){return{baseEvent:void 0,toolCallId:void 0,toolCallName:void 0,parentMessageId:void 0,delta:void 0}}var Bo={encode(t,e=new P){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=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;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 Bo.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??void 0,e.toolCallName=t.toolCallName??void 0,e.parentMessageId=t.parentMessageId??void 0,e.delta=t.delta??void 0,e}};function ac(){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 lc={encode(t,e=new P){return t.textMessageStart!==void 0&&Ao.encode(t.textMessageStart,e.uint32(10).fork()).join(),t.textMessageContent!==void 0&&ko.encode(t.textMessageContent,e.uint32(18).fork()).join(),t.textMessageEnd!==void 0&&Io.encode(t.textMessageEnd,e.uint32(26).fork()).join(),t.toolCallStart!==void 0&&Co.encode(t.toolCallStart,e.uint32(34).fork()).join(),t.toolCallArgs!==void 0&&No.encode(t.toolCallArgs,e.uint32(42).fork()).join(),t.toolCallEnd!==void 0&&Ro.encode(t.toolCallEnd,e.uint32(50).fork()).join(),t.stateSnapshot!==void 0&&Oo.encode(t.stateSnapshot,e.uint32(58).fork()).join(),t.stateDelta!==void 0&&Mo.encode(t.stateDelta,e.uint32(66).fork()).join(),t.messagesSnapshot!==void 0&&Lo.encode(t.messagesSnapshot,e.uint32(74).fork()).join(),t.raw!==void 0&&Po.encode(t.raw,e.uint32(82).fork()).join(),t.custom!==void 0&&Do.encode(t.custom,e.uint32(90).fork()).join(),t.runStarted!==void 0&&Uo.encode(t.runStarted,e.uint32(98).fork()).join(),t.runFinished!==void 0&&Go.encode(t.runFinished,e.uint32(106).fork()).join(),t.runError!==void 0&&Ho.encode(t.runError,e.uint32(114).fork()).join(),t.stepStarted!==void 0&&Fo.encode(t.stepStarted,e.uint32(122).fork()).join(),t.stepFinished!==void 0&&$o.encode(t.stepFinished,e.uint32(130).fork()).join(),t.textMessageChunk!==void 0&&zo.encode(t.textMessageChunk,e.uint32(138).fork()).join(),t.toolCallChunk!==void 0&&Bo.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=ac();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.textMessageStart=Ao.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.textMessageContent=ko.decode(n,n.uint32());continue;case 3:if(s!==26)break;o.textMessageEnd=Io.decode(n,n.uint32());continue;case 4:if(s!==34)break;o.toolCallStart=Co.decode(n,n.uint32());continue;case 5:if(s!==42)break;o.toolCallArgs=No.decode(n,n.uint32());continue;case 6:if(s!==50)break;o.toolCallEnd=Ro.decode(n,n.uint32());continue;case 7:if(s!==58)break;o.stateSnapshot=Oo.decode(n,n.uint32());continue;case 8:if(s!==66)break;o.stateDelta=Mo.decode(n,n.uint32());continue;case 9:if(s!==74)break;o.messagesSnapshot=Lo.decode(n,n.uint32());continue;case 10:if(s!==82)break;o.raw=Po.decode(n,n.uint32());continue;case 11:if(s!==90)break;o.custom=Do.decode(n,n.uint32());continue;case 12:if(s!==98)break;o.runStarted=Uo.decode(n,n.uint32());continue;case 13:if(s!==106)break;o.runFinished=Go.decode(n,n.uint32());continue;case 14:if(s!==114)break;o.runError=Ho.decode(n,n.uint32());continue;case 15:if(s!==122)break;o.stepStarted=Fo.decode(n,n.uint32());continue;case 16:if(s!==130)break;o.stepFinished=$o.decode(n,n.uint32());continue;case 17:if(s!==138)break;o.textMessageChunk=zo.decode(n,n.uint32());continue;case 18:if(s!==146)break;o.toolCallChunk=Bo.decode(n,n.uint32());continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return lc.fromPartial(t??{})},fromPartial(t){let e=ac();return e.textMessageStart=t.textMessageStart!==void 0&&t.textMessageStart!==null?Ao.fromPartial(t.textMessageStart):void 0,e.textMessageContent=t.textMessageContent!==void 0&&t.textMessageContent!==null?ko.fromPartial(t.textMessageContent):void 0,e.textMessageEnd=t.textMessageEnd!==void 0&&t.textMessageEnd!==null?Io.fromPartial(t.textMessageEnd):void 0,e.toolCallStart=t.toolCallStart!==void 0&&t.toolCallStart!==null?Co.fromPartial(t.toolCallStart):void 0,e.toolCallArgs=t.toolCallArgs!==void 0&&t.toolCallArgs!==null?No.fromPartial(t.toolCallArgs):void 0,e.toolCallEnd=t.toolCallEnd!==void 0&&t.toolCallEnd!==null?Ro.fromPartial(t.toolCallEnd):void 0,e.stateSnapshot=t.stateSnapshot!==void 0&&t.stateSnapshot!==null?Oo.fromPartial(t.stateSnapshot):void 0,e.stateDelta=t.stateDelta!==void 0&&t.stateDelta!==null?Mo.fromPartial(t.stateDelta):void 0,e.messagesSnapshot=t.messagesSnapshot!==void 0&&t.messagesSnapshot!==null?Lo.fromPartial(t.messagesSnapshot):void 0,e.raw=t.raw!==void 0&&t.raw!==null?Po.fromPartial(t.raw):void 0,e.custom=t.custom!==void 0&&t.custom!==null?Do.fromPartial(t.custom):void 0,e.runStarted=t.runStarted!==void 0&&t.runStarted!==null?Uo.fromPartial(t.runStarted):void 0,e.runFinished=t.runFinished!==void 0&&t.runFinished!==null?Go.fromPartial(t.runFinished):void 0,e.runError=t.runError!==void 0&&t.runError!==null?Ho.fromPartial(t.runError):void 0,e.stepStarted=t.stepStarted!==void 0&&t.stepStarted!==null?Fo.fromPartial(t.stepStarted):void 0,e.stepFinished=t.stepFinished!==void 0&&t.stepFinished!==null?$o.fromPartial(t.stepFinished):void 0,e.textMessageChunk=t.textMessageChunk!==void 0&&t.textMessageChunk!==null?zo.fromPartial(t.textMessageChunk):void 0,e.toolCallChunk=t.toolCallChunk!==void 0&&t.toolCallChunk!==null?Bo.fromPartial(t.toolCallChunk):void 0,e}};function Qf(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 po=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}}},eh=t=>{if(!(!t||typeof t!="object")){if(t.text)return{type:"text",text:t.text.text};if(t.image)return{type:"image",source:po(t.image.source),metadata:t.image.metadata};if(t.audio)return{type:"audio",source:po(t.audio.source),metadata:t.audio.metadata};if(t.video)return{type:"video",source:po(t.video.source),metadata:t.video.metadata};if(t.document)return{type:"document",source:po(t.document.source),metadata:t.document.metadata}}};function cc(t){let e=lc.decode(t),n=Object.values(e).find(r=>r!==void 0);if(!n)throw new Error("Invalid event");if(n.type=Jf[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=>eh(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=qf[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]}),Ir.parse(n)}var gi="application/vnd.ag-ui.event+proto";var nh=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,vi=t=>{if(typeof t!="string")throw new TypeError("Invalid argument expected string");let e=t.match(nh);if(!e)throw new Error(`Invalid argument not valid semver ('${t}' received)`);return e.shift(),e},uc=t=>t==="*"||t==="x"||t==="X",dc=t=>{let e=parseInt(t,10);return isNaN(e)?t:e},rh=(t,e)=>typeof t!=typeof e?[String(t),String(e)]:[t,e],oh=(t,e)=>{if(uc(t)||uc(e))return 0;let[n,r]=rh(dc(t),dc(e));return n>r?1:n<r?-1:0},yi=(t,e)=>{for(let n=0;n<Math.max(t.length,e.length);n++){let r=oh(t[n]||"0",e[n]||"0");if(r!==0)return r}return 0};var Xn=(t,e)=>{let n=vi(t),r=vi(e),o=n.pop(),s=r.pop(),i=yi(n,r);return i!==0?i:o&&s?yi(o.split("."),s.split(".")):o||s?o?-1:1:0};var z=t=>{if(typeof structuredClone=="function")return structuredClone(t);try{return JSON.parse(JSON.stringify(t))}catch{return Array.isArray(t)?[...t]:{...t}}};function Ce(){return ht()}function Ei(t){if(Object.freeze(t),typeof t=="object"&&t)for(let e of Object.values(t))typeof e=="object"&&e&&!Object.isFrozen(e)&&Ei(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=z(e),l=z(n),c=a,p=l,m;for(let x of t)try{i&&(Ei(c),Ei(p));let f=await r(x,c,p);if(f===void 0)continue;if(f.messages!==void 0&&f.messages!==c&&(c=z(f.messages)),f.state!==void 0&&f.state!==p&&(p=z(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)?z(c):c},...p===l?{}:{state:i&&Object.isFrozen(p)?z(p):p},...m===void 0?{}:{stopPropagation:m}}}function Vo(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 Zn(t){if(t instanceof Ti)return t;if(t===!0)return new Ti(Vo(!0))}var Ti=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 bi(t){return t.enabled?new Ti(t):void 0}function sh(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 vc=(t,e,n,r,o)=>{let s=Zn(o),i=z(n.messages),a=z(t.state),l={},c=m=>{m.messages!==void 0&&(i=m.messages,l.messages=m.messages),m.state!==void 0&&(a=m.state,l.state=m.state)},p=()=>{let m=z(l);return l={},m.messages!==void 0||m.state!==void 0?te(m):jr};return e.pipe(io(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(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,T)=>h.onTextMessageStartEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(c(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),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 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 c(T),T.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,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(c(f),f.stopPropagation!==!0){let{toolCallId:h,toolCallName:g,parentMessageId:T}=m,S=sh(i,T,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(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,dt={};try{dt=lo(ae)}catch{}return b.onToolCallArgsEvent?.({event:m,messages:H,state:X,agent:n,input:t,toolCallBuffer:ae,toolCallName:ee,partialToolCallArgs:dt})});return c(S),S.stopPropagation!==!0&&(T.function.arguments+=h,c({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?(c(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(c(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})})),c({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(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,T)=>h.onStateDeltaEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{delta:h}=m;try{a=Dr.applyPatch(a,h,!0,!1).newDocument,c({state:a})}catch(g){let T=g instanceof Error?g.message:String(g);console.warn(`Failed to apply state patch:
6
+ Current state: ${JSON.stringify(a,null,2)}
7
+ Patch operations: ${JSON.stringify(h,null,2)}
8
+ 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(c(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);c({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(c(b),b.stopPropagation!==!0){let H={id:f.messageId,role:"activity",activityType:f.activityType,content:z(f.content)},X;h===-1?(i.push(H),X=H):T?S&&(i[h]={...T,activityType:f.activityType,content:z(f.content)}):S&&(i[h]=H,X=H),c({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(c(S),S.stopPropagation!==!0)try{let b=z(T.content??{}),H=Dr.applyPatch(b,f.patch??[],!0,!1).newDocument;i[h]={...T,content:z(H),activityType:f.activityType},c({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 c(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 c(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(c(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);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,(T,S,b)=>T.onRunFinishedEvent?.({...h,messages:S,state:b,agent:n,input:t}));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:t}))),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:t}))),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: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 c(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(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 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 c(T),T.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,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 c(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(c(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&&(l.messages=i)}return p()}}return m.type,p()}),ti(),r.length>0?ni({}):m=>m)},xi=t=>e=>{let n=Zn(t),r=new Map,o=new Map,s=!1,i=!1,a=!1,l=new Map,c=!1,p=!1,m=!1,x=()=>{r.clear(),o.clear(),l.clear(),c=!1,p=!1,s=!1,i=!1,m=!0};return e.pipe(ke(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 l.has(g)?Q(()=>new q(`Step "${g}" is already active for 'STEP_STARTED'`)):(l.set(g,!0),te(f))}case v.STEP_FINISHED:{let g=f.stepName;return l.has(g)?(l.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(l.size>0){let g=Array.from(l.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)}}))},jt=(function(t){return t.HEADERS="headers",t.DATA="data",t})({}),ih=t=>so(()=>zt(t())).pipe(ri(e=>{if(!e.ok){let o=e.headers.get("content-type")||"";return zt(e.text()).pipe(ke(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:jt.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:jt.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"))})),ah=(t,e)=>{let n=Zn(e),r=new tt,o=new TextDecoder("utf-8",{fatal:!1}),s="";t.subscribe({next:a=>{if(a.type!==jt.HEADERS&&a.type===jt.DATA&&a.data){let l=o.decode(a.data,{stream:!0});s+=l;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 l=a.split(`
9
+ `),c=[];for(let p of l)p.startsWith("data:")&&c.push(p.slice(5).replace(/^ /,""));if(c.length>0)try{let p=c.join(`
10
+ `),m=JSON.parse(p);n?.event("SSE","Event received:",m,{type:m.type}),r.next(m)}catch(p){r.error(p)}}return r.asObservable()},lh=t=>{let e=new tt,n=new Uint8Array;t.subscribe({next:o=>{if(o.type!==jt.HEADERS&&o.type===jt.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=cc(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()},ch=(t,e)=>{let n=Zn(e),r=new tt,o=new Vr,s=!1;return t.subscribe({next:i=>{if(o.next(i),i.type===jt.HEADERS&&!s){s=!0;let a=i.headers.get("content-type");n?.lifecycle("HTTP","Stream format detected:",{contentType:a,parser:a===gi?"protobuf":"sse"}),a===gi?lh(o).subscribe({next:l=>r.next(l),error:l=>r.error(l),complete:()=>r.complete()}):ah(o,n).subscribe({next:l=>{try{let c=Ir.parse(l);n?.event("HTTP","Event validated:",c,{type:c.type,valid:!0}),r.next(c)}catch(c){n?.event("HTTP","Event invalid:",{json:l,error:String(c)}),r.error(c)}},error:l=>{if(l?.name==="AbortError"){r.next({type:v.RUN_ERROR,message:l.message||"Request aborted",code:"abort",rawEvent:l}),r.complete();return}return r.error(l)},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=u.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),uh=u.enum(["LangGraphInterruptEvent","PredictState","Exit"]),dh=u.object({type:u.literal(K.enum.TextMessageStart),messageId:u.string(),parentMessageId:u.string().optional(),role:u.string().optional()}),ph=u.object({type:u.literal(K.enum.TextMessageContent),messageId:u.string(),content:u.string()}),fh=u.object({type:u.literal(K.enum.TextMessageEnd),messageId:u.string()}),hh=u.object({type:u.literal(K.enum.ActionExecutionStart),actionExecutionId:u.string(),actionName:u.string(),parentMessageId:u.string().optional()}),mh=u.object({type:u.literal(K.enum.ActionExecutionArgs),actionExecutionId:u.string(),args:u.string()}),gh=u.object({type:u.literal(K.enum.ActionExecutionEnd),actionExecutionId:u.string()}),vh=u.object({type:u.literal(K.enum.ActionExecutionResult),actionName:u.string(),actionExecutionId:u.string(),result:u.string()}),yh=u.object({type:u.literal(K.enum.AgentStateMessage),threadId:u.string(),agentName:u.string(),nodeName:u.string(),runId:u.string(),active:u.boolean(),role:u.string(),state:u.string(),running:u.boolean()}),bh=u.object({type:u.literal(K.enum.MetaEvent),name:uh,value:u.any()}),xh=u.object({type:u.literal(K.enum.RunError),message:u.string(),code:u.string().optional()});u.discriminatedUnion("type",[dh,ph,fh,hh,mh,gh,vh,yh,bh,xh]),u.object({id:u.string(),role:u.string(),content:u.string(),parentMessageId:u.string().optional()}),u.object({id:u.string(),name:u.string(),arguments:u.any(),parentMessageId:u.string().optional()}),u.object({id:u.string(),result:u.any(),actionExecutionId:u.string(),actionName:u.string()});var Eh=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(`
11
+ `)},Th=(t,e,n)=>r=>{let o={},s=!0,i=!0,a="",l=null,c=null,p=[],m={},x=f=>{typeof f=="object"&&f&&("messages"in f&&delete f.messages,o=f)};return r.pipe(ke(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(c){let S=c.find(b=>b.tool==g.function.name);if(S)try{let b=JSON.parse(lo(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":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: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=Dr.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 l=f.messages,[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:s,role:"assistant",state:JSON.stringify({...o,...l?{messages:l}:{}}),active:!0}];case v.RUN_STARTED:return[];case v.RUN_FINISHED:return l&&(o.messages=l),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,...l?{messages:_h(l)}:{}}),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:t,agentName:n,nodeName:a,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:!0}];case v.STEP_FINISHED:return p=[],c=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 _h(t){let e=[];for(let n of t)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let r=Eh(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 jo=t=>e=>{let n=Zn(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},l=()=>{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"?[l()]:i==="reasoning"?[c()]:[];return e.pipe(ke(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,[]}),Vt(()=>{p()}))};function Sh(t,e=new Date){return t.expiresAt===void 0?!1:new Date(t.expiresAt)<=e}var Wo=class{runNext(t,e){return e.run(t).pipe(jo(!1))}runNextWithState(t,e){let n=z(t.messages||[]),r=z(t.state||{}),o=new Vr;return vc(t,o,e,[]).subscribe(s=>{s.messages!==void 0&&(n=s.messages),s.state!==void 0&&(r=s.state)}),this.runNext(t,e).pipe(io(async s=>(o.next(s),await new Promise(i=>setTimeout(i,0)),{event:s,messages:z(n),state:z(r)})))}},wh=class extends Wo{constructor(t){super(),this.fn=t}run(t,e){return this.fn(t,e)}};function Ah(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 kh=class extends Wo{run(t,e){let{parentRunId:n,...r}=t,o={...r,messages:r.messages.map(Ah)};return this.runNext(o,e)}},pc="THINKING_START",fc="THINKING_END",hc="THINKING_TEXT_MESSAGE_START",mc="THINKING_TEXT_MESSAGE_CONTENT",gc="THINKING_TEXT_MESSAGE_END",Ih=class extends Wo{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(Bt(n=>this.transformEvent(n)))}transformEvent(t){switch(t.type){case pc:{this.currentReasoningId=Ce();let{title:e,...n}=t;return this.warnAboutTransformation(pc,v.REASONING_START),{...n,type:v.REASONING_START,messageId:this.currentReasoningId}}case hc:return this.currentMessageId=Ce(),this.warnAboutTransformation(hc,v.REASONING_MESSAGE_START),{...t,type:v.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:"assistant"};case mc:{let{delta:e,...n}=t;return this.warnAboutTransformation(mc,v.REASONING_MESSAGE_CONTENT),{...n,type:v.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??Ce(),delta:e}}case gc:{let e=this.currentMessageId??Ce();return this.warnAboutTransformation(gc,v.REASONING_MESSAGE_END),{...t,type:v.REASONING_MESSAGE_END,messageId:e}}case fc:{let e=this.currentReasoningId??Ce();return this.warnAboutTransformation(fc,v.REASONING_END),{...t,type:v.REASONING_END,messageId:e}}default:return t}}};function Ch(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"document"}function Nh(t){return typeof t=="object"&&!!t&&"type"in t&&t.type==="binary"&&"mimeType"in t&&typeof t.mimeType=="string"}function Rh(t){let e=Ch(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 Oh(t){let e=t.content;if(!Array.isArray(e))return t;let n=e.map(r=>Nh(r)?Rh(r):r);return{...t,content:n}}var Mh=class extends Wo{run(t,e){let n={...t,messages:t.messages.map(Oh)};return this.runNext(n,e)}},Lh="0.0.54",Ph=class{get maxVersion(){return Lh}get debug(){return this._debug}set debug(t){this._debug=Vo(t),this._debugLogger=bi(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(t){typeof t=="boolean"?this._debugLogger=t?bi(Vo(!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=z(r??[]),this.state=z(o??{}),this._debug=Vo(s),this._debugLogger=bi(this._debug),Xn(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new kh),Xn(this.maxVersion,"0.0.45")<=0&&this.middlewares.unshift(new Ih),Xn(this.maxVersion,"0.0.47")<=0&&this.middlewares.unshift(new Mh)}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 wh(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(l=>l.id)),s=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,s),this.activeRunDetach$=new tt;let i;this.activeRunCompletionPromise=new Promise(l=>{i=l}),await oo(Br(()=>this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((l,c)=>({run:p=>c.run(p,l),get messages(){return l.messages},get state(){return l.state}}),this).run(n),jo(this.debugLogger),xi(this.debugLogger),l=>l.pipe(ao(this.activeRunDetach$)),l=>this.apply(n,l,s),l=>this.processApplyEvents(n,l,s),Vn(l=>(this.debugLogger?.lifecycle("LIFECYCLE","Run errored:",{agentId:this.agentId,error:l instanceof Error?l.message:String(l)}),this.isRunning=!1,this.onError(n,l,s))),Vt(()=>{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=z(this.messages).filter(l=>!o.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}connect(t){throw new zs}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(l=>l.id)),s=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,s),this.activeRunDetach$=new tt;let i;this.activeRunCompletionPromise=new Promise(l=>{i=l}),await oo(Br(()=>so(()=>this.connect(n)),jo(this.debugLogger),xi(this.debugLogger),l=>l.pipe(ao(this.activeRunDetach$)),l=>this.apply(n,l,s),l=>this.processApplyEvents(n,l,s),Vn(l=>(this.isRunning=!1,l instanceof zs?jr:this.onError(n,l,s))),Vt(()=>{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=z(this.messages).filter(l=>!o.has(l.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 vc(t,e,this,n,this.debugLogger)}processApplyEvents(t,e,n){return e.pipe(oi(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=z(this.messages).filter(n=>n.role!=="activity");return{threadId:this.threadId,runId:t?.runId||ht(),tools:z(t?.tools??[]),context:z(t?.context??[]),forwardedProps:z(t?.forwardedProps??{}),state:z(this.state),messages:e,...t?.resume===void 0?{}:{resume:z(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(Sh(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 zt(W(n,this.messages,this.state,(r,o,s)=>r.onRunFailed?.({error:e,messages:o,state:s,agent:this,input:t}))).pipe(Bt(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=z(this.messages),t.state=z(this.state),t._debug=this._debug,t._debugLogger=this._debugLogger,t.isRunning=this.isRunning,t.subscribers=[...this.subscribers],t.middlewares=[...this.middlewares],t.pendingInterrupts=z(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=z(t),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(t){this.state=z(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(jo(this.debugLogger),xi(this.debugLogger),Th(this.threadId,e.runId,this.agentId),n=>n.pipe(Bt(r=>(this.debugLogger?.event("LEGACY","Event:",r,{type:r.type}),r))))}},yc=class extends Ph{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=z(t.headers??{}),this.fetch=t.fetch??fetch}run(t){return ch(ih(()=>this.fetch(this.url,this.requestInit(t))),this.debugLogger)}clone(){let t=super.clone();t.url=this.url,t.headers=z(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 Xo=class{element;#e;#t=[];constructor(e){this.#e=e,this.element=document.createElement("div"),this.element.className="attachment-tray",this.element.hidden=!0}add(e){let n={localId:Ce(),file:e,status:Ge.UPLOADING,progress:0,ref:null,error:""};this.#t.push(n);let r=this.#o(e);if(r!==null){n.status=Ge.ERROR,n.error=r,this.#r(),this.#e.onChange?.();return}this.#r(),this.#e.onChange?.(),this.#i(n)}readyRefs(){let e=[];for(let n of this.#t)n.ref!==null&&e.push(n.ref);return e}hasPending(){return this.#t.some(e=>e.status===Ge.UPLOADING)}isEmpty(){return this.#t.length===0}clearReady(){this.#t=this.#t.filter(e=>e.status===Ge.UPLOADING),this.#r()}clear(){this.#t=[],this.#r()}#o(e){return this.#e.maxBytes>0&&e.size>this.#e.maxBytes?`Too large (max ${xr(this.#e.maxBytes)})`:Dh(this.#e.accept,e)?null:"File type not allowed"}#i(e){e.status=Ge.UPLOADING,e.progress=0,e.error="",this.#r(),this.#e.upload(e.file,n=>{e.progress=n,this.#r()}).then(n=>{e.status=Ge.READY,e.ref=n}).catch(n=>{e.status=Ge.ERROR,e.error=n instanceof Error?n.message:"upload failed"}).finally(()=>{this.#r(),this.#e.onChange?.()})}#a(e){this.#t=this.#t.filter(n=>n!==e),this.#r(),this.#e.onChange?.()}#r(){this.element.replaceChildren(),this.element.hidden=this.#t.length===0;for(let e of this.#t)this.element.appendChild(this.#n(e))}#n(e){let n=document.createElement("div");n.className=`attachment-chip attachment-chip--${e.status}`;let r=document.createElement("span");r.className="attachment-chip-icon",r.textContent=Ps(e.file.type),r.setAttribute("aria-hidden","true");let o=document.createElement("span");o.className="attachment-chip-name",o.textContent=e.file.name,o.title=e.file.name;let s=document.createElement("span");if(s.className="attachment-chip-size",s.textContent=e.status===Ge.ERROR?e.error:xr(e.file.size),n.append(r,o,s),e.status===Ge.UPLOADING){let a=document.createElement("div");a.className="attachment-chip-bar";let l=document.createElement("div");l.className="attachment-chip-bar-fill",l.style.width=`${Math.round(e.progress*100)}%`,a.appendChild(l),n.appendChild(a)}if(e.status===Ge.ERROR){let a=document.createElement("button");a.type="button",a.className="attachment-chip-retry",a.title="Retry",a.setAttribute("aria-label","Retry upload"),a.textContent="\u21BB",a.addEventListener("click",()=>this.#i(e)),n.appendChild(a)}let i=document.createElement("button");return i.type="button",i.className="attachment-chip-remove",i.title="Remove",i.setAttribute("aria-label","Remove attachment"),i.textContent="\u2715",i.addEventListener("click",()=>this.#a(e)),n.appendChild(i),n}};function Dh(t,e){let n=t.split(",").map(s=>s.trim().toLowerCase()).filter(s=>s!=="");if(n.length===0)return!0;let r=e.type.toLowerCase(),o=e.name.toLowerCase();return n.some(s=>s.startsWith(".")?o.endsWith(s):s.endsWith("/*")?r.startsWith(s.slice(0,-1)):r===s)}function bc(t,e){let n=document.createElement("button");return n.type="button",n.className=`confirm-btn confirm-btn--${t}`,n.textContent=e,n}function _i(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 l=bc("cancel","Cancel"),c=bc("confirm","Confirm"),p=!1,m=x=>{p||(p=!0,l.disabled=!0,c.disabled=!0,o.setAttribute("data-resolved",x?"confirmed":"declined"),r(x))};if(l.addEventListener("click",()=>m(!1)),c.addEventListener("click",()=>m(!0)),n.signal?.addEventListener("abort",()=>m(!1),{once:!0}),a.append(l,c),o.append(s,i,a),t.appendChild(o),n.signal?.aborted===!0){m(!1);return}c.focus()})}function Si(t){let e=t.replace(/[._-]+/g," ").trim();return e===""?t:e.charAt(0).toUpperCase()+e.slice(1)}function xc(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 Uh(t){if(Array.isArray(t))return t}function Gh(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r,o,s,i,a=[],l=!0,c=!1;try{if(s=(n=n.call(t)).next,e!==0)for(;!(l=(r=s.call(n)).done)&&(a.push(r.value),a.length!==e);l=!0);}catch(p){c=!0,o=p}finally{try{if(!l&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(c)throw o}}return a}}function Hh(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
12
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Fh(t,e){return Uh(t)||Gh(t,e)||$h(t,e)||Hh()}function $h(t,e){if(t){if(typeof t=="string")return xc(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)?xc(t,e):void 0}}var Mc=Object.entries,Ec=Object.setPrototypeOf,zh=Object.isFrozen,Bh=Object.getPrototypeOf,Vh=Object.getOwnPropertyDescriptor,Se=Object.freeze,Pe=Object.seal,Sn=Object.create,Lc=typeof Reflect<"u"&&Reflect,Ni=Lc.apply,Ri=Lc.construct;Se||(Se=function(e){return e});Pe||(Pe=function(e){return e});Ni||(Ni=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)});Ri||(Ri=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 En=ue(Array.prototype.forEach),jh=ue(Array.prototype.lastIndexOf),Tc=ue(Array.prototype.pop),Tn=ue(Array.prototype.push),Wh=ue(Array.prototype.splice),_e=Array.isArray,qn=ue(String.prototype.toLowerCase),wi=ue(String.prototype.toString),_c=ue(String.prototype.match),_n=ue(String.prototype.replace),Sc=ue(String.prototype.indexOf),Xh=ue(String.prototype.trim),Zh=ue(Number.prototype.toString),Kh=ue(Boolean.prototype.toString),wc=typeof BigInt>"u"?null:ue(BigInt.prototype.toString),Ac=typeof Symbol>"u"?null:ue(Symbol.prototype.toString),re=ue(Object.prototype.hasOwnProperty),Kn=ue(Object.prototype.toString),be=ue(RegExp.prototype.test),Yn=Yh(TypeError);function ue(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 Ni(t,e,r)}}function Yh(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return Ri(t,n)}}function D(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:qn;if(Ec&&Ec(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&&(zh(e)||(e[r]=s),o=s)}t[o]=!0}return t}function qh(t){for(let e=0;e<t.length;e++)re(t,e)||(t[e]=null);return t}function Ee(t){let e=Sn(null);for(let r of Mc(t)){var n=Fh(r,2);let o=n[0],s=n[1];re(t,o)&&(_e(s)?e[o]=qh(s):s&&typeof s=="object"&&s.constructor===Object?e[o]=Ee(s):e[o]=s)}return e}function Jh(t){switch(typeof t){case"string":return t;case"number":return Zh(t);case"boolean":return Kh(t);case"bigint":return wc?wc(t):"0";case"symbol":return Ac?Ac(t):"Symbol()";case"undefined":return Kn(t);case"function":case"object":{if(t===null)return Kn(t);let e=t,n=rt(e,"toString");if(typeof n=="function"){let r=n(e);return typeof r=="string"?r:Kn(r)}return Kn(t)}default:return Kn(t)}}function rt(t,e){for(;t!==null;){let r=Vh(t,e);if(r){if(r.get)return ue(r.get);if(typeof r.value=="function")return ue(r.value)}t=Bh(t)}function n(){return null}return n}function Qh(t){try{return be(t,""),!0}catch{return!1}}var kc=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"]),Ai=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"]),ki=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"]),em=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"]),Ii=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"]),tm=Se(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Ic=Se(["#text"]),Cc=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"]),Ci=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"]),Nc=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"]),Zo=Se(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),nm=Pe(/{{[\w\W]*|^[\w\W]*}}/g),rm=Pe(/<%[\w\W]*|^[\w\W]*%>/g),om=Pe(/\${[\w\W]*/g),sm=Pe(/^data-[\-\w.\u00B7-\uFFFF]+$/),im=Pe(/^aria-[\-\w]+$/),Rc=Pe(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),am=Pe(/^(?:\w+script|data):/i),lm=Pe(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),cm=Pe(/^html$/i),um=Pe(/^[a-z][.\w]*(-[.\w]+)+$/i),nt={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},dm=function(){return typeof window>"u"?null:window},pm=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}},Oc=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Pc(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:dm(),e=C=>Pc(C);if(e.version="3.4.7",e.removed=[],!t||!t.document||t.document.nodeType!==nt.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,l=t.NodeFilter,c=t.NamedNodeMap;c===void 0&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;let p=t.DOMParser,m=t.trustedTypes,x=a.prototype,f=rt(x,"cloneNode"),h=rt(x,"remove"),g=rt(x,"nextSibling"),T=rt(x,"childNodes"),S=rt(x,"parentNode"),b=rt(x,"shadowRoot"),H=rt(x,"attributes"),X=i&&i.prototype?rt(i.prototype,"nodeType"):null,ae=i&&i.prototype?rt(i.prototype,"nodeName"):null;if(typeof s=="function"){let C=n.createElement("template");C.content&&C.content.ownerDocument&&(n=C.content.ownerDocument)}let ee,dt="",ar=n,is=ar.implementation,oa=ar.createNodeIterator,hu=ar.createDocumentFragment,mu=ar.getElementsByTagName,gu=r.importNode,pe=Oc();e.isSupported=typeof Mc=="function"&&typeof S=="function"&&is&&is.createHTMLDocument!==void 0;let lr=nm,cr=rm,ur=om,vu=sm,yu=im,bu=am,sa=lm,xu=um,ia=Rc,oe=null,as=D({},[...kc,...Ai,...ki,...Ii,...Ic]),le=null,ls=D({},[...Cc,...Ci,...Nc,...Zo]),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,dr=null,pt=Object.seal(Sn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),aa=!0,cs=!0,la=!1,ca=!0,ft=!1,In=!0,Et=!1,us=!1,ds=!1,Jt=!1,pr=!1,fr=!1,ua=!0,da=!1,pa="user-content-",ps=!0,Cn=!1,Qt={},Ve=null,fs=D({},["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"]),fa=null,ha=D({},["audio","video","img","source","image","track"]),hs=null,ma=D({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),hr="http://www.w3.org/1998/Math/MathML",mr="http://www.w3.org/2000/svg",je="http://www.w3.org/1999/xhtml",en=je,ms=!1,gs=null,Eu=D({},[hr,mr,je],wi),vs=D({},["mi","mo","mn","ms","mtext"]),ys=D({},["annotation-xml"]),Tu=D({},["title","style","font","a","script"]),Nn=null,_u=["application/xhtml+xml","text/html"],Su="text/html",ie=null,tn=null,wu=n.createElement("form"),ga=function(d){return d instanceof RegExp||d instanceof Function},bs=function(){let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(tn&&tn===d)return;(!d||typeof d!="object")&&(d={}),d=Ee(d),Nn=_u.indexOf(d.PARSER_MEDIA_TYPE)===-1?Su:d.PARSER_MEDIA_TYPE,ie=Nn==="application/xhtml+xml"?wi:qn,oe=re(d,"ALLOWED_TAGS")&&_e(d.ALLOWED_TAGS)?D({},d.ALLOWED_TAGS,ie):as,le=re(d,"ALLOWED_ATTR")&&_e(d.ALLOWED_ATTR)?D({},d.ALLOWED_ATTR,ie):ls,gs=re(d,"ALLOWED_NAMESPACES")&&_e(d.ALLOWED_NAMESPACES)?D({},d.ALLOWED_NAMESPACES,wi):Eu,hs=re(d,"ADD_URI_SAFE_ATTR")&&_e(d.ADD_URI_SAFE_ATTR)?D(Ee(ma),d.ADD_URI_SAFE_ATTR,ie):ma,fa=re(d,"ADD_DATA_URI_TAGS")&&_e(d.ADD_DATA_URI_TAGS)?D(Ee(ha),d.ADD_DATA_URI_TAGS,ie):ha,Ve=re(d,"FORBID_CONTENTS")&&_e(d.FORBID_CONTENTS)?D({},d.FORBID_CONTENTS,ie):fs,kn=re(d,"FORBID_TAGS")&&_e(d.FORBID_TAGS)?D({},d.FORBID_TAGS,ie):Ee({}),dr=re(d,"FORBID_ATTR")&&_e(d.FORBID_ATTR)?D({},d.FORBID_ATTR,ie):Ee({}),Qt=re(d,"USE_PROFILES")?d.USE_PROFILES&&typeof d.USE_PROFILES=="object"?Ee(d.USE_PROFILES):d.USE_PROFILES:!1,aa=d.ALLOW_ARIA_ATTR!==!1,cs=d.ALLOW_DATA_ATTR!==!1,la=d.ALLOW_UNKNOWN_PROTOCOLS||!1,ca=d.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ft=d.SAFE_FOR_TEMPLATES||!1,In=d.SAFE_FOR_XML!==!1,Et=d.WHOLE_DOCUMENT||!1,Jt=d.RETURN_DOM||!1,pr=d.RETURN_DOM_FRAGMENT||!1,fr=d.RETURN_TRUSTED_TYPE||!1,ds=d.FORCE_BODY||!1,ua=d.SANITIZE_DOM!==!1,da=d.SANITIZE_NAMED_PROPS||!1,ps=d.KEEP_CONTENT!==!1,Cn=d.IN_PLACE||!1,ia=Qh(d.ALLOWED_URI_REGEXP)?d.ALLOWED_URI_REGEXP:Rc,en=typeof d.NAMESPACE=="string"?d.NAMESPACE:je,vs=re(d,"MATHML_TEXT_INTEGRATION_POINTS")&&d.MATHML_TEXT_INTEGRATION_POINTS&&typeof d.MATHML_TEXT_INTEGRATION_POINTS=="object"?Ee(d.MATHML_TEXT_INTEGRATION_POINTS):D({},["mi","mo","mn","ms","mtext"]),ys=re(d,"HTML_INTEGRATION_POINTS")&&d.HTML_INTEGRATION_POINTS&&typeof d.HTML_INTEGRATION_POINTS=="object"?Ee(d.HTML_INTEGRATION_POINTS):D({},["annotation-xml"]);let y=re(d,"CUSTOM_ELEMENT_HANDLING")&&d.CUSTOM_ELEMENT_HANDLING&&typeof d.CUSTOM_ELEMENT_HANDLING=="object"?Ee(d.CUSTOM_ELEMENT_HANDLING):Sn(null);if(se=Sn(null),re(y,"tagNameCheck")&&ga(y.tagNameCheck)&&(se.tagNameCheck=y.tagNameCheck),re(y,"attributeNameCheck")&&ga(y.attributeNameCheck)&&(se.attributeNameCheck=y.attributeNameCheck),re(y,"allowCustomizedBuiltInElements")&&typeof y.allowCustomizedBuiltInElements=="boolean"&&(se.allowCustomizedBuiltInElements=y.allowCustomizedBuiltInElements),ft&&(cs=!1),pr&&(Jt=!0),Qt&&(oe=D({},Ic),le=Sn(null),Qt.html===!0&&(D(oe,kc),D(le,Cc)),Qt.svg===!0&&(D(oe,Ai),D(le,Ci),D(le,Zo)),Qt.svgFilters===!0&&(D(oe,ki),D(le,Ci),D(le,Zo)),Qt.mathMl===!0&&(D(oe,Ii),D(le,Nc),D(le,Zo))),pt.tagCheck=null,pt.attributeCheck=null,re(d,"ADD_TAGS")&&(typeof d.ADD_TAGS=="function"?pt.tagCheck=d.ADD_TAGS:_e(d.ADD_TAGS)&&(oe===as&&(oe=Ee(oe)),D(oe,d.ADD_TAGS,ie))),re(d,"ADD_ATTR")&&(typeof d.ADD_ATTR=="function"?pt.attributeCheck=d.ADD_ATTR:_e(d.ADD_ATTR)&&(le===ls&&(le=Ee(le)),D(le,d.ADD_ATTR,ie))),re(d,"ADD_URI_SAFE_ATTR")&&_e(d.ADD_URI_SAFE_ATTR)&&D(hs,d.ADD_URI_SAFE_ATTR,ie),re(d,"FORBID_CONTENTS")&&_e(d.FORBID_CONTENTS)&&(Ve===fs&&(Ve=Ee(Ve)),D(Ve,d.FORBID_CONTENTS,ie)),re(d,"ADD_FORBID_CONTENTS")&&_e(d.ADD_FORBID_CONTENTS)&&(Ve===fs&&(Ve=Ee(Ve)),D(Ve,d.ADD_FORBID_CONTENTS,ie)),ps&&(oe["#text"]=!0),Et&&D(oe,["html","head","body"]),oe.table&&(D(oe,["tbody"]),delete kn.tbody),d.TRUSTED_TYPES_POLICY){if(typeof d.TRUSTED_TYPES_POLICY.createHTML!="function")throw Yn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof d.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Yn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');ee=d.TRUSTED_TYPES_POLICY,dt=ee.createHTML("")}else ee===void 0&&(ee=pm(m,o)),ee!==null&&typeof dt=="string"&&(dt=ee.createHTML(""));(pe.uponSanitizeElement.length>0||pe.uponSanitizeAttribute.length>0)&&oe===as&&(oe=Ee(oe)),pe.uponSanitizeAttribute.length>0&&le===ls&&(le=Ee(le)),Se&&Se(d),tn=d},va=D({},[...Ai,...ki,...em]),ya=D({},[...Ii,...tm]),Au=function(d){let y=S(d);(!y||!y.tagName)&&(y={namespaceURI:en,tagName:"template"});let A=qn(d.tagName),j=qn(y.tagName);return gs[d.namespaceURI]?d.namespaceURI===mr?y.namespaceURI===je?A==="svg":y.namespaceURI===hr?A==="svg"&&(j==="annotation-xml"||vs[j]):!!va[A]:d.namespaceURI===hr?y.namespaceURI===je?A==="math":y.namespaceURI===mr?A==="math"&&ys[j]:!!ya[A]:d.namespaceURI===je?y.namespaceURI===mr&&!ys[j]||y.namespaceURI===hr&&!vs[j]?!1:!ya[A]&&(Tu[A]||!va[A]):!!(Nn==="application/xhtml+xml"&&gs[d.namespaceURI]):!1},De=function(d){Tn(e.removed,{element:d});try{S(d).removeChild(d)}catch{h(d)}},Tt=function(d,y){try{Tn(e.removed,{attribute:y.getAttributeNode(d),from:y})}catch{Tn(e.removed,{attribute:null,from:y})}if(y.removeAttribute(d),d==="is")if(Jt||pr)try{De(y)}catch{}else try{y.setAttribute(d,"")}catch{}},ba=function(d){let y=null,A=null;if(ds)d="<remove></remove>"+d;else{let Y=_c(d,/^[\r\n\t ]+/);A=Y&&Y[0]}Nn==="application/xhtml+xml"&&en===je&&(d='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+d+"</body></html>");let j=ee?ee.createHTML(d):d;if(en===je)try{y=new p().parseFromString(j,Nn)}catch{}if(!y||!y.documentElement){y=is.createDocument(en,"template",null);try{y.documentElement.innerHTML=ms?dt:j}catch{}}let $=y.body||y.documentElement;return d&&A&&$.insertBefore(n.createTextNode(A),$.childNodes[0]||null),en===je?mu.call(y,Et?"html":"body")[0]:Et?y.documentElement:$},xa=function(d){return oa.call(d.ownerDocument||d,d,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Ea=function(d){d.normalize();let y=oa.call(d.ownerDocument||d,d,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),A=y.nextNode();for(;A;){let j=A.data;En([lr,cr,ur],$=>{j=_n(j,$," ")}),A.data=j,A=y.nextNode()}},gr=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)},Rn=function(d){if(!X||typeof d!="object"||d===null)return!1;try{return X(d)===nt.documentFragment}catch{return!1}},vr=function(d){if(!X||typeof d!="object"||d===null)return!1;try{return typeof X(d)=="number"}catch{return!1}};function st(C,d,y){En(C,A=>{A.call(e,d,y,tn)})}let Ta=function(d){let y=null;if(st(pe.beforeSanitizeElements,d,null),gr(d))return De(d),!0;let A=ie(d.nodeName);if(st(pe.uponSanitizeElement,d,{tagName:A,allowedTags:oe}),In&&d.hasChildNodes()&&!vr(d.firstElementChild)&&be(/<[/\w!]/g,d.innerHTML)&&be(/<[/\w!]/g,d.textContent)||In&&d.namespaceURI===je&&A==="style"&&vr(d.firstElementChild)||d.nodeType===nt.progressingInstruction||In&&d.nodeType===nt.comment&&be(/<[/\w]/g,d.data))return De(d),!0;if(kn[A]||!(pt.tagCheck instanceof Function&&pt.tagCheck(A))&&!oe[A]){if(!kn[A]&&Sa(A)&&(se.tagNameCheck instanceof RegExp&&be(se.tagNameCheck,A)||se.tagNameCheck instanceof Function&&se.tagNameCheck(A)))return!1;if(ps&&!Ve[A]){let $=S(d),Y=T(d);if(Y&&$){let Ne=Y.length;for(let We=Ne-1;We>=0;--We){let Ue=f(Y[We],!0);$.insertBefore(Ue,g(d))}}}return De(d),!0}return(X?X(d):d.nodeType)===nt.element&&!Au(d)||(A==="noscript"||A==="noembed"||A==="noframes")&&be(/<\/no(script|embed|frames)/i,d.innerHTML)?(De(d),!0):(ft&&d.nodeType===nt.text&&(y=d.textContent,En([lr,cr,ur],$=>{y=_n(y,$," ")}),d.textContent!==y&&(Tn(e.removed,{element:d.cloneNode()}),d.textContent=y)),st(pe.afterSanitizeElements,d,null),!1)},_a=function(d,y,A){if(dr[y]||ua&&(y==="id"||y==="name")&&(A in n||A in wu))return!1;let j=le[y]||pt.attributeCheck instanceof Function&&pt.attributeCheck(y,d);if(!(cs&&!dr[y]&&be(vu,y))){if(!(aa&&be(yu,y))){if(!j||dr[y]){if(!(Sa(d)&&(se.tagNameCheck instanceof RegExp&&be(se.tagNameCheck,d)||se.tagNameCheck instanceof Function&&se.tagNameCheck(d))&&(se.attributeNameCheck instanceof RegExp&&be(se.attributeNameCheck,y)||se.attributeNameCheck instanceof Function&&se.attributeNameCheck(y,d))||y==="is"&&se.allowCustomizedBuiltInElements&&(se.tagNameCheck instanceof RegExp&&be(se.tagNameCheck,A)||se.tagNameCheck instanceof Function&&se.tagNameCheck(A))))return!1}else if(!hs[y]){if(!be(ia,_n(A,sa,""))){if(!((y==="src"||y==="xlink:href"||y==="href")&&d!=="script"&&Sc(A,"data:")===0&&fa[d])){if(!(la&&!be(bu,_n(A,sa,"")))){if(A)return!1}}}}}}return!0},ku=D({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Sa=function(d){return!ku[qn(d)]&&be(xu,d)},wa=function(d){st(pe.beforeSanitizeAttributes,d,null);let y=d.attributes;if(!y||gr(d))return;let A={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:le,forceKeepAttr:void 0},j=y.length;for(;j--;){let $=y[j],Y=$.name,Ne=$.namespaceURI,We=$.value,Ue=ie(Y),xs=We,fe=Y==="value"?xs:Xh(xs);if(A.attrName=Ue,A.attrValue=fe,A.keepAttr=!0,A.forceKeepAttr=void 0,st(pe.uponSanitizeAttribute,d,A),fe=A.attrValue,da&&(Ue==="id"||Ue==="name")&&Sc(fe,pa)!==0&&(Tt(Y,d),fe=pa+fe),In&&be(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,fe)){Tt(Y,d);continue}if(Ue==="attributename"&&_c(fe,"href")){Tt(Y,d);continue}if(A.forceKeepAttr)continue;if(!A.keepAttr){Tt(Y,d);continue}if(!ca&&be(/\/>/i,fe)){Tt(Y,d);continue}ft&&En([lr,cr,ur],ka=>{fe=_n(fe,ka," ")});let Aa=ie(d.nodeName);if(!_a(Aa,Ue,fe)){Tt(Y,d);continue}if(ee&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!Ne)switch(m.getAttributeType(Aa,Ue)){case"TrustedHTML":{fe=ee.createHTML(fe);break}case"TrustedScriptURL":{fe=ee.createScriptURL(fe);break}}if(fe!==xs)try{Ne?d.setAttributeNS(Ne,Y,fe):d.setAttribute(Y,fe),gr(d)?De(d):Tc(e.removed)}catch{Tt(Y,d)}}st(pe.afterSanitizeAttributes,d,null)},yr=function(d){let y=null,A=xa(d);for(st(pe.beforeSanitizeShadowDOM,d,null);y=A.nextNode();)if(st(pe.uponSanitizeShadowNode,y,null),Ta(y),wa(y),Rn(y.content)&&yr(y.content),(X?X(y):y.nodeType)===nt.element){let $=b?b(y):y.shadowRoot;Rn($)&&(nn($),yr($))}st(pe.afterSanitizeShadowDOM,d,null)},nn=function(d){let y=X?X(d):d.nodeType;if(y===nt.element){let $=b?b(d):d.shadowRoot;Rn($)&&(nn($),yr($))}let A=T?T(d):d.childNodes;if(!A)return;let j=[];En(A,$=>{Tn(j,$)});for(let $ of j)nn($);if(y===nt.element){let $=ae?ae(d):null;if(typeof $=="string"&&ie($)==="template"){let Y=d.content;Rn(Y)&&nn(Y)}}};return e.sanitize=function(C){let d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},y=null,A=null,j=null,$=null;if(ms=!C,ms&&(C="<!-->"),typeof C!="string"&&!vr(C)&&(C=Jh(C),typeof C!="string"))throw Yn("dirty is not a string, aborting");if(!e.isSupported)return C;if(us||bs(d),e.removed=[],typeof C=="string"&&(Cn=!1),Cn){let We=ae?ae(C):C.nodeName;if(typeof We=="string"){let Ue=ie(We);if(!oe[Ue]||kn[Ue])throw Yn("root node is forbidden and cannot be sanitized in-place")}if(gr(C))throw Yn("root node is clobbered and cannot be sanitized in-place");nn(C)}else if(vr(C))y=ba("<!---->"),A=y.ownerDocument.importNode(C,!0),A.nodeType===nt.element&&A.nodeName==="BODY"||A.nodeName==="HTML"?y=A:y.appendChild(A),nn(A);else{if(!Jt&&!ft&&!Et&&C.indexOf("<")===-1)return ee&&fr?ee.createHTML(C):C;if(y=ba(C),!y)return Jt?null:fr?dt:""}y&&ds&&De(y.firstChild);let Y=xa(Cn?C:y);for(;j=Y.nextNode();)Ta(j),wa(j),Rn(j.content)&&yr(j.content);if(Cn)return ft&&Ea(C),C;if(Jt){if(ft&&Ea(y),pr)for($=hu.call(y.ownerDocument);y.firstChild;)$.appendChild(y.firstChild);else $=y;return(le.shadowroot||le.shadowrootmode)&&($=gu.call(r,$,!0)),$}let Ne=Et?y.outerHTML:y.innerHTML;return Et&&oe["!doctype"]&&y.ownerDocument&&y.ownerDocument.doctype&&y.ownerDocument.doctype.name&&be(cm,y.ownerDocument.doctype.name)&&(Ne="<!DOCTYPE "+y.ownerDocument.doctype.name+`>
13
+ `+Ne),ft&&En([lr,cr,ur],We=>{Ne=_n(Ne,We," ")}),ee&&fr?ee.createHTML(Ne):Ne},e.setConfig=function(){let C=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};bs(C),us=!0},e.clearConfig=function(){tn=null,us=!1},e.isValidAttribute=function(C,d,y){tn||bs({});let A=ie(C),j=ie(d);return _a(A,j,y)},e.addHook=function(C,d){typeof d=="function"&&Tn(pe[C],d)},e.removeHook=function(C,d){if(d!==void 0){let y=jh(pe[C],d);return y===-1?void 0:Wh(pe[C],y,1)[0]}return Tc(pe[C])},e.removeHooks=function(C){pe[C]=[]},e.removeAllHooks=function(){pe=Oc()},e}var Dc=Pc();function Pi(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Zt=Pi();function Vc(t){Zt=t}var Wt={exec:()=>null};function wn(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 B(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(Te.caret,"$1"),n=n.replace(o,i),r},getRegex:()=>new RegExp(n,e)};return r}var fm=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),Te={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:wn(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:wn(t=>new RegExp(`^ {0,${t}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:wn(t=>new RegExp(`^ {0,${t}}(?:\`\`\`|~~~)`)),headingBeginRegex:wn(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:wn(t=>new RegExp(`^ {0,${t}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:wn(t=>new RegExp(`^ {0,${t}}>`))},hm=/^(?:[ \t]*(?:\n|$))+/,mm=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,gm=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,er=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,vm=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Di=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,jc=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Wc=B(jc).replace(/bull/g,Di).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(),ym=B(jc).replace(/bull/g,Di).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(),Ui=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,bm=/^[^\n]+/,Gi=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,xm=B(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Gi).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Em=B(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Di).getRegex(),Qo="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",Hi=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Tm=B("^ {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",Hi).replace("tag",Qo).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Xc=B(Ui).replace("hr",er).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",Qo).getRegex(),_m=B(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Xc).getRegex(),Fi={blockquote:_m,code:mm,def:xm,fences:gm,heading:vm,hr:er,html:Tm,lheading:Wc,list:Em,newline:hm,paragraph:Xc,table:Wt,text:bm},Uc=B("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",er).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",Qo).getRegex(),Sm={...Fi,lheading:ym,table:Uc,paragraph:B(Ui).replace("hr",er).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Uc).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",Qo).getRegex()},wm={...Fi,html:B(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Hi).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:Wt,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:B(Ui).replace("hr",er).replace("heading",` *#{1,6} *[^
14
+ ]`).replace("lheading",Wc).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Am=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,km=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Zc=/^( {2,}|\\)\n(?!\s*$)/,Im=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,An=/[\p{P}\p{S}]/u,es=/[\s\p{P}\p{S}]/u,$i=/[^\s\p{P}\p{S}]/u,Cm=B(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,es).getRegex(),Kc=/(?!~)[\p{P}\p{S}]/u,Nm=/(?!~)[\s\p{P}\p{S}]/u,Rm=/(?:[^\s\p{P}\p{S}]|~)/u,Om=B(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",fm?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Yc=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Mm=B(Yc,"u").replace(/punct/g,An).getRegex(),Lm=B(Yc,"u").replace(/punct/g,Kc).getRegex(),qc="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Pm=B(qc,"gu").replace(/notPunctSpace/g,$i).replace(/punctSpace/g,es).replace(/punct/g,An).getRegex(),Dm=B(qc,"gu").replace(/notPunctSpace/g,Rm).replace(/punctSpace/g,Nm).replace(/punct/g,Kc).getRegex(),Um=B("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,$i).replace(/punctSpace/g,es).replace(/punct/g,An).getRegex(),Gm=B(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,An).getRegex(),Hm="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Fm=B(Hm,"gu").replace(/notPunctSpace/g,$i).replace(/punctSpace/g,es).replace(/punct/g,An).getRegex(),$m=B(/\\(punct)/,"gu").replace(/punct/g,An).getRegex(),zm=B(/^<(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(),Bm=B(Hi).replace("(?:-->|$)","-->").getRegex(),Vm=B("^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",Bm).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Yo=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,jm=B(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Yo).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Jc=B(/^!?\[(label)\]\[(ref)\]/).replace("label",Yo).replace("ref",Gi).getRegex(),Qc=B(/^!?\[(ref)\](?:\[\])?/).replace("ref",Gi).getRegex(),Wm=B("reflink|nolink(?!\\()","g").replace("reflink",Jc).replace("nolink",Qc).getRegex(),Gc=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,zi={_backpedal:Wt,anyPunctuation:$m,autolink:zm,blockSkip:Om,br:Zc,code:km,del:Wt,delLDelim:Wt,delRDelim:Wt,emStrongLDelim:Mm,emStrongRDelimAst:Pm,emStrongRDelimUnd:Um,escape:Am,link:jm,nolink:Qc,punctuation:Cm,reflink:Jc,reflinkSearch:Wm,tag:Vm,text:Im,url:Wt},Xm={...zi,link:B(/^!?\[(label)\]\((.*?)\)/).replace("label",Yo).getRegex(),reflink:B(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Yo).getRegex()},Oi={...zi,emStrongRDelimAst:Dm,emStrongLDelim:Lm,delLDelim:Gm,delRDelim:Fm,url:B(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Gc).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:B(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Gc).getRegex()},Zm={...Oi,br:B(Zc).replace("{2,}","*").getRegex(),text:B(Oi.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Ko={normal:Fi,gfm:Sm,pedantic:wm},Jn={normal:zi,gfm:Oi,breaks:Zm,pedantic:Xm},Km={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Hc=t=>Km[t];function ot(t,e){if(e){if(Te.escapeTest.test(t))return t.replace(Te.escapeReplace,Hc)}else if(Te.escapeTestNoEncode.test(t))return t.replace(Te.escapeReplaceNoEncode,Hc);return t}function Fc(t){try{t=encodeURI(t).replace(Te.percentDecode,"%")}catch{return null}return t}function $c(t,e){let n=t.replace(Te.findPipe,(s,i,a)=>{let l=!1,c=i;for(;--c>=0&&a[c]==="\\";)l=!l;return l?"|":" |"}),r=n.split(Te.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(Te.slashPipe,"|");return r}function xt(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 zc(t){let e=t.split(`
15
+ `),n=e.length-1;for(;n>=0&&Te.blankLine.test(e[n]);)n--;return e.length-n<=2?t:e.slice(0,n+1).join(`
16
+ `)}function Ym(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 qm(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 Bc(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 l={type:t[0].charAt(0)==="!"?"image":"link",raw:n,href:s,title:i,text:a,tokens:r.inlineTokens(a)};return r.state.inLink=!1,l}function Jm(t,e,n){let r=t.match(n.other.indentCodeCompensation);if(r===null)return e;let o=r[1];return e.split(`
7
17
  `).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],`
18
+ `)}var qo=class{options;rules;lexer;constructor(t){this.options=t||Zt}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]:zc(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=Jm(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=xt(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:xt(e[0],`
19
+ `),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:xt(e[0],`
20
+ `)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=xt(e[0],`
11
21
  `).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(`
22
+ `),r="",o="",s=[];for(;n.length>0;){let i=!1,a=[],l;for(l=0;l<n.length;l++)if(this.rules.other.blockquoteStart.test(n[l]))a.push(n[l]),i=!0;else if(!i)a.push(n[l]);else break;n=n.slice(l);let c=a.join(`
13
23
  `),p=c.replace(this.rules.other.blockquoteSetextReplace,`
14
24
  $1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
15
25
  ${c}`:c,o=o?`${o}
@@ -18,52 +28,52 @@ ${p}`:p;let m=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
18
28
  `),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
29
  `+n.join(`
20
30
  `),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+=`
31
+ `);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 l=!1,c="",p="";if(!(e=s.exec(t))||this.rules.block.hr.test(t))break;c=e[0],t=t.substring(c.length);let m=qm(e[2].split(`
32
+ `,1)[0],e[1].length),x=t.split(`
33
+ `,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)&&(c+=x+`
34
+ `,t=t.substring(x.length+1),l=!0),!l){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(`
35
+ `,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+=`
36
+ `+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
37
  `+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(`
38
+ `,t=t.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 l of o.items){this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]);let c=l.tokens[0];if(l.task&&(c?.type==="text"||c?.type==="paragraph")){l.text=l.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(l.raw);if(p){let m={type:"checkbox",raw:p[0]+" ",checked:p[0]!=="[ ]"};l.checked=m.checked,o.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=m.raw+l.tokens[0].raw,l.tokens[0].text=m.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(m)):l.tokens.unshift({type:"paragraph",raw:m.raw,text:m.raw,tokens:[m]}):l.tokens.unshift(m)}}else l.task&&(l.task=!1);if(!o.loose){let p=l.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 l of o.items){l.loose=!0;for(let c of l.tokens)c.type==="text"&&(c.type="paragraph")}return o}}html(t){let e=this.rules.block.html.exec(t);if(e){let n=zc(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:xt(e[0],`
39
+ `),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=$c(e[1]),r=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
40
+ `):[],s={type:"table",raw:xt(e[0],`
41
+ `),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($c(i,s.header.length).map((a,l)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:s.align[l]})));return s}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let n=e[1].trim();return{type:"heading",raw:xt(e[0],`
42
+ `),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)===`
43
+ `?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=xt(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=Ym(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)),Bc(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 Bc(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,l=0,c=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,e=e.slice(-1*t.length+o);(r=c.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)){l+=i;continue}if(a-=i,a>0)continue;i=Math.min(i,i+a+l);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,l=this.rules.inline.delRDelim;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||(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=t.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(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}}}},ze=class Mi{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Zt,this.options.tokenizer=this.options.tokenizer||new qo,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:Te,block:Ko.normal,inline:Jn.normal};this.options.pedantic?(n.block=Ko.pedantic,n.inline=Jn.pedantic):this.options.gfm&&(n.block=Ko.gfm,this.options.breaks?n.inline=Jn.breaks:n.inline=Jn.gfm),this.tokenizer.rules=n}static get rules(){return{block:Ko,inline:Jn}}static lex(e,n){return new Mi(n).lex(e)}static lexInline(e,n){return new Mi(n).inlineTokens(e)}lex(e){e=e.replace(Te.carriageReturn,`
44
+ `),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(Te.tabCharGlobal," ").replace(Te.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+=`
45
+ `: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
46
  `)?"":`
37
47
  `)+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(`
48
+ `+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
49
  `)?"":`
40
50
  `)+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(`
51
+ `+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,l=e.slice(1),c;this.options.extensions.startBlock.forEach(p=>{c=p.call({lexer:this},l),typeof c=="number"&&c>=0&&(a=Math.min(a,c))}),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
52
  `)?"":`
43
53
  `)+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(`
54
+ `+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
55
  `)?"":`
46
56
  `)+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,"")+`
48
- `;return r?'<pre><code class="language-'+qe(r)+'">'+(n?o:qe(o,!0))+`</code></pre>
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+`>
57
+ `+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 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="",l=1/0;for(;e;){if(e.length<l)l=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}i||(a=""),i=!1;let c;if(this.options.extensions?.inline?.some(m=>(c=m.call({lexer:this},e,n))?(e=e.substring(c.raw.length),n.push(c),!0):!1))continue;if(c=this.tokenizer.escape(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.tag(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.link(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.reflink(e,this.tokens.links)){e=e.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(e,r,a)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.codespan(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.br(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.del(e,r,a)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.autolink(e)){e=e.substring(c.raw.length),n.push(c);continue}if(!this.state.inLink&&(c=this.tokenizer.url(e))){e=e.substring(c.raw.length),n.push(c);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(c=this.tokenizer.inlineText(p)){e=e.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(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)}},Jo=class{options;parser;constructor(t){this.options=t||Zt}space(t){return""}code({text:t,lang:e,escaped:n}){let r=(e||"").match(Te.notSpaceStart)?.[0],o=t.replace(Te.endingNewline,"")+`
58
+ `;return r?'<pre><code class="language-'+ot(r)+'">'+(n?o:ot(o,!0))+`</code></pre>
59
+ `:"<pre><code>"+(n?o:ot(o,!0))+`</code></pre>
60
+ `}blockquote({tokens:t}){return`<blockquote>
61
+ ${this.parser.parse(t)}</blockquote>
62
+ `}html({text:t}){return t}def(t){return""}heading({tokens:t,depth:e}){return`<h${e}>${this.parser.parseInline(t)}</h${e}>
63
+ `}hr(t){return`<hr>
64
+ `}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
65
  `+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>
66
+ `}listitem(t){return`<li>${this.parser.parse(t.tokens)}</li>
67
+ `}checkbox({checked:t}){return"<input "+(t?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:t}){return`<p>${this.parser.parseInline(t)}</p>
68
+ `}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
69
  <thead>
60
- `+t+`</thead>
70
+ `+e+`</thead>
61
71
  `+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 yg=Z.options,bg=Z.setOptions,xg=Z.use,Eg=Z.walkTokens,_g=Z.parseInline;var Tg=Ge.parse,Sg=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;#d=!1;#l=[];#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.#p()}enableChips(t){this.#i=t,this.#p()}enableSlash(t){this.#d=t}isOpen(){return!this.palette.hidden}onInput(t){this.#d&&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.#l.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.#l=r,this.#o=0,this.#a(),this.palette.hidden=!1}#r(t){let n=this.#l.length;this.#o=(this.#o+t+n)%n,this.#a()}#s(t){this.close(),this.#e(t)}#p(){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)}}#a(){this.palette.replaceChildren(),this.#l.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=`
72
+ `}tablerow({text:t}){return`<tr>
73
+ ${t}</tr>
74
+ `}tablecell(t){let e=this.parser.parseInline(t.tokens),n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>
75
+ `}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>${ot(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=Fc(t);if(o===null)return r;t=o;let s='<a href="'+t+'"';return e&&(s+=' title="'+ot(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=Fc(t);if(o===null)return ot(n);t=o;let s=`<img src="${t}" alt="${ot(n)}"`;return e&&(s+=` title="${ot(e)}"`),s+=">",s}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:ot(t.text)}},Bi=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}},Be=class Li{options;renderer;textRenderer;constructor(e){this.options=e||Zt,this.options.renderer=this.options.renderer||new Jo,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Bi}static parse(e,n){return new Li(n).parse(e)}static parseInline(e,n){return new Li(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}},Qn=class{options;block;constructor(t){this.options=t||Zt}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?ze.lex:ze.lexInline}provideParser(t=this.block){return t?Be.parse:Be.parseInline}},Vi=class{defaults=Pi();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Be;Renderer=Jo;TextRenderer=Bi;Lexer=ze;Tokenizer=qo;Hooks=Qn;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 Jo(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],l=o[i];o[i]=(...c)=>{let p=a.apply(o,c);return p===!1&&(p=l.apply(o,c)),p||""}}r.renderer=o}if(n.tokenizer){let o=this.defaults.tokenizer||new qo(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],l=o[i];o[i]=(...c)=>{let p=a.apply(o,c);return p===!1&&(p=l.apply(o,c)),p}}r.tokenizer=o}if(n.hooks){let o=this.defaults.hooks||new Qn;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],l=o[i];Qn.passThroughHooks.has(s)?o[i]=c=>{if(this.defaults.async&&Qn.passThroughHooksRespectAsync.has(s))return(async()=>{let m=await a.call(o,c);return l.call(o,m)})();let p=a.call(o,c);return l.call(o,p)}:o[i]=(...c)=>{if(this.defaults.async)return(async()=>{let m=await a.apply(o,c);return m===!1&&(m=await l.apply(o,c)),m})();let p=a.apply(o,c);return p===!1&&(p=l.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(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return ze.lex(t,e??this.defaults)}parser(t,e){return Be.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?ze.lex:ze.lexInline)(i,o),l=o.hooks?await o.hooks.processAllTokens(a):a;o.walkTokens&&await Promise.all(this.walkTokens(l,o.walkTokens));let c=await(o.hooks?await o.hooks.provideParser(t):t?Be.parse:Be.parseInline)(l,o);return o.hooks?await o.hooks.postprocess(c):c})().catch(s);try{o.hooks&&(e=o.hooks.preprocess(e));let i=(o.hooks?o.hooks.provideLexer(t):t?ze.lex:ze.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?Be.parse:Be.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+=`
76
+ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+ot(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},Xt=new Vi;function Z(t,e){return Xt.parse(t,e)}Z.options=Z.setOptions=function(t){return Xt.setOptions(t),Z.defaults=Xt.defaults,Vc(Z.defaults),Z};Z.getDefaults=Pi;Z.defaults=Zt;Z.use=function(...t){return Xt.use(...t),Z.defaults=Xt.defaults,Vc(Z.defaults),Z};Z.walkTokens=function(t,e){return Xt.walkTokens(t,e)};Z.parseInline=Xt.parseInline;Z.Parser=Be;Z.parser=Be.parse;Z.Renderer=Jo;Z.TextRenderer=Bi;Z.Lexer=ze;Z.lexer=ze.lex;Z.Tokenizer=qo;Z.Hooks=Qn;Z.parse=Z;var NT=Z.options,RT=Z.setOptions,OT=Z.use,MT=Z.walkTokens,LT=Z.parseInline;var PT=Be.parse,DT=ze.lex;var Qm=new Vi({gfm:!0,breaks:!0}),eu=["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"],tu=["href","title","class"],eg=[...eu,"img"],tg=[...tu,"src","alt","width","height"];function ts(t,e){let n=e?.allowImages===!0,r=Qm.parse(t,{async:!1}),o=Dc.sanitize(r,{ALLOWED_TAGS:n?eg:eu,ALLOWED_ATTR:n?tg:tu}),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 nu(t,e){for(let n of Array.from(t.childNodes))n.nodeType===Node.TEXT_NODE?e.push({node:n,parent:t}):nu(n,e)}function ru(t){let e=[];nu(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 ns=class{chips;palette;#e;#t=[];#o=!1;#i=!1;#a=[];#r=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.#t=e,this.#h()}enableChips(e){this.#o=e,this.#h()}enableSlash(e){this.#i=e}isOpen(){return!this.palette.hidden}onInput(e){this.#i&&e.startsWith("/")?this.#n(e.slice(1)):this.close()}onKeydown(e){return this.isOpen()?e.key==="ArrowDown"?(this.#s(1),!0):e.key==="ArrowUp"?(this.#s(-1),!0):e.key==="Escape"?(this.close(),!0):e.key==="Enter"?(this.#a.slice(this.#r,this.#r+1).forEach(n=>{this.#l(n)}),!0):!1:!1}close(){this.palette.hidden=!0,this.palette.replaceChildren()}#n(e){let n=e.trim().toLowerCase(),r=this.#t.filter(o=>o.name.toLowerCase().includes(n)||o.title.toLowerCase().includes(n));if(r.length===0){this.close();return}this.#a=r,this.#r=0,this.#u(),this.palette.hidden=!1}#s(e){let n=this.#a.length;this.#r=(this.#r+e+n)%n,this.#u()}#l(e){this.close(),this.#e(e)}#h(){this.chips.replaceChildren();let e=this.#o?this.#t.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.#l(n)),this.chips.appendChild(r)}}#u(){this.palette.replaceChildren(),this.#a.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.#r?"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.#l(e)),this.palette.appendChild(r)})}};var ou=`
67
77
  :host {
68
78
  /* Colors */
69
79
  --ag-ui-bg: #ffffff;
@@ -567,6 +577,116 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
567
577
  background: var(--ag-ui-muted);
568
578
  }
569
579
 
580
+ /* \u2500\u2500 File attachments \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
581
+ /* The \u{1F4CE} picker button sits left of the input; hidden until data-attachments-url. */
582
+ .attach-btn {
583
+ border: 1px solid var(--ag-ui-border);
584
+ border-radius: 8px;
585
+ padding: 0 10px;
586
+ background: var(--ag-ui-input-bg);
587
+ color: inherit;
588
+ font: inherit;
589
+ cursor: pointer;
590
+ }
591
+
592
+ .attach-btn:hover {
593
+ border-color: var(--ag-ui-accent);
594
+ }
595
+
596
+ .attach-input {
597
+ display: none;
598
+ }
599
+
600
+ /* Pending-attachments tray, above the input row; collapses (hidden) when empty. */
601
+ .attachment-slot {
602
+ display: contents;
603
+ }
604
+
605
+ .attachment-tray {
606
+ display: flex;
607
+ flex-wrap: wrap;
608
+ gap: 6px;
609
+ padding: 8px 12px 0;
610
+ }
611
+
612
+ .attachment-chips {
613
+ display: flex;
614
+ flex-wrap: wrap;
615
+ gap: 6px;
616
+ margin-top: 6px;
617
+ }
618
+
619
+ .attachment-chip {
620
+ display: inline-flex;
621
+ align-items: center;
622
+ gap: 6px;
623
+ max-width: 100%;
624
+ padding: 4px 8px;
625
+ border: 1px solid var(--ag-ui-border);
626
+ border-radius: 999px;
627
+ background: var(--ag-ui-assistant-bg);
628
+ font-size: 0.85em;
629
+ position: relative;
630
+ }
631
+
632
+ .attachment-chip--error {
633
+ border-color: var(--ag-ui-danger);
634
+ color: var(--ag-ui-danger);
635
+ }
636
+
637
+ .attachment-chip-name {
638
+ overflow: hidden;
639
+ text-overflow: ellipsis;
640
+ white-space: nowrap;
641
+ max-width: 14ch;
642
+ }
643
+
644
+ .attachment-chip-size {
645
+ color: var(--ag-ui-muted);
646
+ white-space: nowrap;
647
+ }
648
+
649
+ .attachment-chip--error .attachment-chip-size {
650
+ color: var(--ag-ui-danger);
651
+ }
652
+
653
+ /* The progress bar fills as the file uploads. */
654
+ .attachment-chip-bar {
655
+ flex-basis: 100%;
656
+ height: 3px;
657
+ border-radius: 2px;
658
+ background: var(--ag-ui-border);
659
+ overflow: hidden;
660
+ }
661
+
662
+ .attachment-chip-bar-fill {
663
+ height: 100%;
664
+ background: var(--ag-ui-accent);
665
+ transition: width 0.15s ease;
666
+ }
667
+
668
+ .attachment-chip-remove,
669
+ .attachment-chip-retry {
670
+ border: none;
671
+ background: none;
672
+ color: inherit;
673
+ cursor: pointer;
674
+ padding: 0;
675
+ line-height: 1;
676
+ opacity: 0.7;
677
+ }
678
+
679
+ .attachment-chip-remove:hover,
680
+ .attachment-chip-retry:hover {
681
+ opacity: 1;
682
+ }
683
+
684
+ /* A subtle outline while a file is dragged over the shell. */
685
+ .chat--dragover {
686
+ outline: 2px dashed var(--ag-ui-accent);
687
+ outline-offset: -4px;
688
+ }
689
+
570
690
  /* Muted "\u23F9 Stopped" line after a cancelled run \u2014 a note, not an error bubble. */
571
691
  .stopped-note {
572
692
  align-self: flex-start;
@@ -705,23 +825,196 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
705
825
  font-size: 0.85em;
706
826
  color: var(--ag-ui-danger);
707
827
  }
708
- `;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)}
709
828
 
710
- ${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"]})},Ev=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]),_v=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()}),Tv=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(`
711
- `)}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:
712
- `+n.map(function(r,o){return o+1+") "+r.toString()}).join(`
713
- `):"",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
714
- `.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:
715
- Current state: ${JSON.stringify(a,null,2)}
716
- Patch operations: ${JSON.stringify(h,null,2)}
717
- 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(`
718
- `),c=[];for(let p of u)p.startsWith("data:")&&c.push(p.slice(5).replace(/^ /,""));if(c.length>0)try{let p=c.join(`
719
- `),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(`
720
- `)},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;#d;#l;#o;#t=!1;constructor(t){this.#e=t.agent,this.#n=t.handlers,this.#i=t.getTools??(()=>[]),this.#d=t.getContext??(()=>[]),this.#l=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.#r()}async resume(){await this.#r()}addToolResult(t,n){this.#e.addMessage({id:ze(),role:"tool",content:n,toolCallId:t}),this.#o(this.#e.messages)}cancel(){this.#t=!0,this.#e.abortRun()}async#r(){this.#t=!1;try{await this.#p(),this.#t&&this.#s()}catch(t){this.#t||Hm(t)?this.#s():this.#n.onError(t instanceof Error?t.message:String(t))}finally{this.#n.onSettled()}}#s(){this.#o(this.#e.messages),this.#n.onCancelled()}async#p(){for(let t=0;t<bs;t+=1){if(this.#t)return;let n=[];if(await this.#e.runAgent({tools:this.#i(),context:this.#d()},this.#a(n)),this.#o(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.#o(this.#e.messages),r=!0}}if(!r)return}}#a(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()}}}};function Hm(e){return e instanceof Error&&e.name==="AbortError"}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.#N().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;#d=new Set;#l;#o;#t;#r;#s;#p;#a;#f;#m=null;#b=!1;#g=null;#c=null;#x=0;#v=null;#u="";#E=[];#A=[];#I=[];#C=[];constructor(){super(),this.#l=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.#p=document.createElement("span"),this.#f=document.createElement("div"),this.#a=new wr(t=>this.#$(t))}static get observedAttributes(){return["title-text"]}attributeChangedCallback(t,n,r){this.#p.textContent=r??"Assistant"}registerTool(t){this.#n.register(t)}registerStateHook(t){for(let n of ks(t))this.#n.register(n)}#P(){return this.routeMap.length===0?[]:ws(()=>this.routeMap,()=>this.navigate)}#D(){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()}]}#N(){return[...this.#P(),...this.#D()]}#R(t){let n=this.#N().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.#W(),sessionStorage.getItem(Kc)==="1"&&this.setAttribute("collapsed",""),this.#G(),this.#U(),this.#u=this.conversationStore.threadId(),this.#z()}async#U(){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.#C=t,this.#_()}#G(){this.#a.enableChips(this.getAttribute("data-prompt-chips")==="true"),this.#a.enableSlash(this.getAttribute("data-slash-commands")==="true"),this.#I=this.#F(),this.#_(),this.#H()}#F(){let t=this.getAttribute("data-skills");if(t===null)return[];try{return xs(JSON.parse(t))}catch{return[]}}async#H(){let t=this.getAttribute("data-skills-url");if(t!==null)try{let n=await fetch(t,{headers:this.headers});this.#A=xs(await n.json()),this.#_()}catch{}}#_(){let t=new Map;for(let n of[...this.#A,...this.#I,...this.#C])t.set(n.name,n);this.#a.setSkills([...t.values()])}#$(t){let{text:n,missing:r}=va(t.prompt,this.skillContext());if(r.length>0){this.#f.textContent=`\u201C${t.title}\u201D needs: ${r.join(", ")}`,this.#f.hidden=!1;return}this.#f.hidden=!0,this.#r.value=n,t.sendImmediately===!0?this.#w():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.#T(),this.conversationStore.clear(this.#u),this.#m=null,this.#c=null,this.#h(),this.#i.clear(),this.#d.clear(),this.#E=[],this.#t.replaceChildren(),this.#u=this.conversationStore.threadId(),this.#S(!1)}async#z(){let t=await this.conversationStore.loadMessages(this.#u);if(t!==null){this.#E=t;for(let r of t)this.#B(r)}let n=this.conversationStore.loadCheckpoint(this.#u);n!==null&&await this.#j(n)}#B(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.#k({id:o.id,name:o.function.name,args:this.#V(o.function.arguments)});return}if(t.role==="tool"){let r=this.#i.get(t.toolCallId);r!==void 0&&r.settle(de.DONE,t.content)}}#V(t){try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#O(t){this.getAttribute("data-text-animation")==="word"&&rl(t)}async#j(t){this.conversationStore.saveCheckpoint(this.#u,null);let n=this.#M();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}#W(){let t=document.createElement("style");t.textContent=ol,this.#o.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--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.#Z(u)),this.#r.addEventListener("input",()=>this.#X()),this.#s.className="send",this.#s.type="button",this.#s.textContent="Send",this.#s.setAttribute("aria-label","Send"),this.#s.dataset.state="idle",this.#s.addEventListener("click",()=>{if(this.#b){this.#T();return}this.#w()}),this.#f.className="skill-hint",this.#f.hidden=!0,a.append(this.#r,this.#s),this.#o.append(n,this.#t,this.#a.palette,this.#a.chips,this.#f,a),this.#l.append(t,this.#o)}#X(){this.#a.onInput(this.#r.value),this.#f.hidden=!0}#Z(t){if(this.#a.onKeydown(t)){t.preventDefault();return}if(t.key==="Escape"&&this.#b){t.preventDefault(),this.#T();return}t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),this.#w())}#T(){this.#g?.abort(),this.#m?.cancel()}#S(t){this.#b=t;let n=t?"Stop":"Send";this.#s.textContent=n,this.#s.setAttribute("aria-label",n),this.#s.dataset.state=t?"running":"idle"}async#w(){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.#K(t))}async#K(t){this.endpoint!==""&&await this.#M().send(t)}#M(){if(this.#m===null){let t=this.agentFactory({endpoint:this.endpoint,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#u,initialMessages:this.#E});this.#m=new er({agent:t,handlers:this.#J(),getTools:()=>this.getTools(),getContext:()=>this.getContext(),executeTool:n=>this.#q(n),onPersist:n=>this.conversationStore.saveMessages(this.#u,n)})}return this.#m}async#Y(t,n){return this.autoConfirm?!1:this.confirmPredicate!==null?await this.confirmPredicate(t.name,t.args)===!0:Es(n.parameters)}async#q(t){let n=this.#k(t);this.#i.delete(t.id);let r=this.#R(t.name);if(r===null)return this.#d.has(t.id)||n.settle(de.DONE,"No result returned."),null;if(await this.#Y(t,r)){let s={toolName:t.name,args:t.args},i=r.parameters[ys];typeof i=="string"&&(s.message=i),this.#g=new AbortController;let a=As(this.#t,s,{signal:this.#g.signal});this.#t.scrollTop=this.#t.scrollHeight;let u=await a;if(this.#g=null,!u){let c="User declined the action.";return n.settle(de.DECLINED,c),this.#y(),{content:c}}}let o=_s(r.parameters)&&this.navigate===null;o&&this.conversationStore.saveCheckpoint(this.#u,{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.#y(),{content:i}}catch(s){o&&this.conversationStore.saveCheckpoint(this.#u,null);let i=s instanceof Error?s.message:String(s);return n.settle(de.ERROR,i),this.#y(),{content:`Error: ${i}`,error:i}}}#J(){return{onRunStart:()=>{this.#S(!0),this.#y()},onTextDelta:t=>{this.#h(),this.#L(t),this.#x+=1},onTextEnd:t=>{let n=this.#L(t);this.#x<=1&&this.#O(n),this.#c=null},onToolCall:t=>{this.#h(),this.#k(t)},onToolResult:(t,n)=>{let r=this.#i.get(t);r!==void 0&&(r.settle(de.DONE,n),this.#d.add(t))},onRunEnd:()=>{this.#h(),this.#c=null},onError:t=>{this.#h(),this.#O(this.appendMessage(We.ASSISTANT,`\u26A0\uFE0F ${t}`)),this.#c=null},onCancelled:()=>{this.#h(),this.#Q(),this.#c=null},onSettled:()=>{this.#h(),this.#S(!1),this.#c=null}}}#Q(){let t=document.createElement("div");t.className="stopped-note",t.setAttribute("role","status"),t.textContent="\u23F9 Stopped",this.#t.appendChild(t),this.#t.scrollTop=this.#t.scrollHeight}#y(){if(this.#v!==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.#v=t,this.#t.appendChild(t),this.#t.scrollTop=this.#t.scrollHeight}#h(){this.#v?.remove(),this.#v=null}#L(t){return this.#c===null&&(this.#c=this.appendMessage(We.ASSISTANT,""),this.#x=0),this.#c.innerHTML=Sr(t,{allowImages:this.allowImages}),this.#t.scrollTop=this.#t.scrollHeight,this.#c}#k(t){let n=this.#i.get(t.id);if(n!==void 0)return n;let r=this.#R(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 $m(){customElements.get(gr)===void 0&&customElements.define(gr,nr)}function Jo(e,t){return Object.getOwnPropertyDescriptor(e,t).set}var zm=Jo(HTMLInputElement.prototype,"value"),Bm=Jo(HTMLTextAreaElement.prototype,"value"),Vm=Jo(HTMLSelectElement.prototype,"value"),jm=Jo(HTMLInputElement.prototype,"checked");function Zt(e,t){e instanceof HTMLTextAreaElement?Bm.call(e,t):e instanceof HTMLSelectElement?Vm.call(e,t):zm.call(e,t)}function rr(e,t){jm.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 Wm(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=Wm(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 Xm(e,t,n={}){Kt(e),await zi(e,{flashMs:n.flashMs??0}),await Hi(e,t,n)}async function Zm(e,t={}){Kt(e),await $i(e,t)}async function Km(e,t={}){Kt(e),await Vi(e,t)}async function Ym(e,t,n={}){Kt(e),await ji(e,t,n)}async function qm(e,t,n={}){Kt(e),await Wi(e,t,n)}function Jm(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 Qm="0.4.0";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,Qm as VERSION,ys as X_CONFIRM_KEY,Nn as X_DESTRUCTIVE_KEY,Rn as X_NAVIGATES_KEY,Xe as X_SUMMARY_KEY,Zm as clickElement,Fi as createHttpAgent,Ts as createPageMapContext,ws as createRouteTools,ks as createStateHookTools,$m as defineAgUiChat,Xm as fillField,zi as focusWithFlash,$i as highlightThenClick,Es as isDestructive,_s as isNavigates,Ss as parseToolCatalog,Jc as prefersReducedMotion,Km as pressButton,Vi as pressThenClick,Is as prettifyToolName,Sr as renderMarkdown,As as requestConfirmation,Kt as scrollIntoCenterView,Ym as selectControl,ji as selectOption,Jm as setControlValue,rr as setNativeChecked,Zt as setNativeValue,qm as toggleCheckbox,Wi as toggleControl,Hi as typeInto};
721
- /*! Bundled license information:
829
+ /* Chat-history drawer \u2014 a slide-over within the chat panel. */
830
+ .drawer {
831
+ position: absolute;
832
+ inset: 0;
833
+ z-index: 5;
834
+ display: flex;
835
+ }
722
836
 
723
- dompurify/dist/purify.es.mjs:
724
- (*! @license DOMPurify 3.4.7 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.7/LICENSE *)
837
+ .drawer[hidden] {
838
+ display: none;
839
+ }
840
+
841
+ .drawer-backdrop {
842
+ position: absolute;
843
+ inset: 0;
844
+ background: rgba(20, 20, 50, 0.32);
845
+ }
846
+
847
+ .drawer-panel {
848
+ position: relative;
849
+ display: flex;
850
+ flex-direction: column;
851
+ width: min(300px, 85%);
852
+ height: 100%;
853
+ background: var(--ag-ui-bg);
854
+ border-right: 1px solid var(--ag-ui-border);
855
+ box-shadow: var(--ag-ui-shadow);
856
+ overflow: hidden;
857
+ }
858
+
859
+ .drawer-header {
860
+ display: flex;
861
+ align-items: center;
862
+ justify-content: space-between;
863
+ gap: var(--ag-ui-space);
864
+ padding: var(--ag-ui-pad);
865
+ border-bottom: 1px solid var(--ag-ui-border);
866
+ }
867
+
868
+ .drawer-title {
869
+ font-weight: 600;
870
+ }
871
+
872
+ .drawer-new {
873
+ border: 1px solid var(--ag-ui-border);
874
+ border-radius: var(--ag-ui-radius);
875
+ background: var(--ag-ui-bg);
876
+ color: var(--ag-ui-accent);
877
+ padding: 4px 10px;
878
+ font: inherit;
879
+ font-size: 0.85em;
880
+ cursor: pointer;
881
+ }
882
+
883
+ .drawer-list {
884
+ flex: 1;
885
+ min-height: 0;
886
+ overflow-y: auto;
887
+ }
888
+
889
+ .drawer-empty {
890
+ padding: var(--ag-ui-pad);
891
+ font-size: 0.9em;
892
+ color: var(--ag-ui-muted);
893
+ }
894
+
895
+ .drawer-row {
896
+ display: flex;
897
+ align-items: stretch;
898
+ border-bottom: 1px solid var(--ag-ui-border);
899
+ }
900
+
901
+ .drawer-row--active {
902
+ background: var(--ag-ui-assistant-bg);
903
+ }
904
+
905
+ .drawer-row-select {
906
+ flex: 1;
907
+ min-width: 0;
908
+ display: flex;
909
+ flex-direction: column;
910
+ gap: 2px;
911
+ padding: 8px 12px;
912
+ border: none;
913
+ background: none;
914
+ color: inherit;
915
+ font: inherit;
916
+ text-align: left;
917
+ cursor: pointer;
918
+ }
919
+
920
+ .drawer-row-title {
921
+ font-weight: 600;
922
+ overflow: hidden;
923
+ white-space: nowrap;
924
+ text-overflow: ellipsis;
925
+ }
926
+
927
+ .drawer-row-time {
928
+ font-size: 0.72em;
929
+ color: var(--ag-ui-muted);
930
+ }
931
+
932
+ .drawer-row-preview {
933
+ font-size: 0.8em;
934
+ color: var(--ag-ui-muted);
935
+ overflow: hidden;
936
+ white-space: nowrap;
937
+ text-overflow: ellipsis;
938
+ }
939
+
940
+ .drawer-row-actions {
941
+ display: flex;
942
+ align-items: center;
943
+ gap: 2px;
944
+ padding: 0 6px;
945
+ }
946
+
947
+ .drawer-row-rename,
948
+ .drawer-row-delete {
949
+ border: none;
950
+ background: none;
951
+ color: var(--ag-ui-muted);
952
+ font-size: 0.9em;
953
+ padding: 4px;
954
+ cursor: pointer;
955
+ }
956
+
957
+ .drawer-rename-input {
958
+ flex: 1;
959
+ min-width: 0;
960
+ margin: 6px 10px;
961
+ padding: 4px 8px;
962
+ border: 1px solid var(--ag-ui-accent);
963
+ border-radius: 6px;
964
+ background: var(--ag-ui-input-bg);
965
+ color: var(--ag-ui-fg);
966
+ font: inherit;
967
+ }
968
+
969
+ .drawer-confirm {
970
+ display: flex;
971
+ align-items: center;
972
+ gap: 8px;
973
+ padding: 8px 12px;
974
+ font-size: 0.85em;
975
+ }
976
+
977
+ .drawer-confirm-label {
978
+ color: var(--ag-ui-danger);
979
+ }
980
+
981
+ .drawer-confirm-yes {
982
+ border: none;
983
+ border-radius: 6px;
984
+ background: var(--ag-ui-danger);
985
+ color: #ffffff;
986
+ padding: 3px 10px;
987
+ font: inherit;
988
+ cursor: pointer;
989
+ }
990
+
991
+ .drawer-confirm-no {
992
+ border: 1px solid var(--ag-ui-border);
993
+ border-radius: 6px;
994
+ background: none;
995
+ color: inherit;
996
+ padding: 3px 10px;
997
+ font: inherit;
998
+ cursor: pointer;
999
+ }
1000
+
1001
+ /* Embedded placement: an inline, flush side panel rather than a dimmed,
1002
+ floating slide-over. */
1003
+ :host([placement="embedded"]) .drawer-backdrop {
1004
+ background: none;
1005
+ }
1006
+
1007
+ :host([placement="embedded"]) .drawer-panel {
1008
+ width: 100%;
1009
+ border-right: none;
1010
+ box-shadow: none;
1011
+ }
1012
+ `;function su(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 rs=class{element;#e;#t;#o=[];#i="";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.#t=document.createElement("div"),this.#t.className="drawer-list",r.append(o,this.#t),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.#o=e,this.#i=n,this.#a()}#a(){if(this.#t.replaceChildren(),this.#o.length===0){let e=document.createElement("div");e.className="drawer-empty",e.textContent="No conversations yet.",this.#t.appendChild(e);return}for(let e of this.#o)this.#t.appendChild(this.#r(e))}#r(e){let n=document.createElement("div");n.className="drawer-row",e.threadId===this.#i&&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=su(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.#n(n,e));let l=document.createElement("button");l.type="button",l.className="drawer-row-delete",l.title="Delete",l.setAttribute("aria-label","Delete conversation"),l.textContent="\u{1F5D1}",l.addEventListener("click",()=>this.#s(n,e));let c=document.createElement("div");return c.className="drawer-row-actions",c.append(a,l),n.append(r,c),n}#n(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.#a():this.#e.onRename(n.threadId,s)}else o.key==="Escape"&&this.#a()}),e.replaceChildren(r),r.focus(),r.select()}#s(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.#a()),r.append(o,s,i),e.replaceChildren(r)}};var iu={[de.PENDING]:"running\u2026",[de.DONE]:"\u2713 done",[de.ERROR]:"\u26A0 error",[de.DECLINED]:"\u2298 declined"},ng={[de.DONE]:"Result",[de.ERROR]:"Error",[de.DECLINED]:"Declined"},tr=class{element;#e;#t;#o;constructor(e,n,r=Ke.FULL,o){this.#t=r,this.#o=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=iu[de.PENDING],s.append(i,this.#e),this.element.append(s),r===Ke.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=iu[e],this.#t===Ke.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.#t===Ke.COMPACT?(r.textContent="Details",o.textContent=`args: ${JSON.stringify(this.#o)}
1013
+
1014
+ ${n}`):(r.textContent=ng[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 nr=class{#e;#t;#o;#i;#a;#r;#n=!1;constructor(e){this.#e=e.agent,this.#t=e.handlers,this.#o=e.getTools??(()=>[]),this.#i=e.getContext??(()=>[]),this.#a=e.executeTool??null,this.#r=e.onPersist??(()=>{})}get running(){return this.#e.isRunning}get messages(){return this.#e.messages}async send(e,n=[]){let r={id:Ce(),role:"user",content:e};n.length>0&&(r.attachments=n),this.#e.addMessage(r),this.#r(this.#e.messages),await this.#s()}async resume(){await this.#s()}addToolResult(e,n){this.#e.addMessage({id:Ce(),role:"tool",content:n,toolCallId:e}),this.#r(this.#e.messages)}cancel(){this.#n=!0,this.#e.abortRun()}async#s(){this.#n=!1;try{await this.#h(),this.#n&&this.#l()}catch(e){this.#n||rg(e)?this.#l():this.#t.onError(e instanceof Error?e.message:String(e))}finally{this.#t.onSettled()}}#l(){this.#r(this.#e.messages),this.#t.onCancelled()}async#h(){for(let e=0;e<ws;e+=1){if(this.#n)return;let n=[];if(await this.#e.runAgent({tools:this.#o(),context:this.#i()},this.#u(n)),this.#r(this.#e.messages),this.#n||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:Ce(),role:"tool",content:s.content,toolCallId:o.id}),this.#r(this.#e.messages),r=!0}}if(!r)return}}#u(e){let n=this.#t;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 rg(t){return t instanceof Error&&t.name==="AbortError"}function ji(t){let e=t.attachments;return Array.isArray(e)?e:[]}var rr="ag-ui-chat:thread",Wi="ag-ui-chat:threads",Xi="ag-ui-chat:messages:",Zi="ag-ui-chat:checkpoint:",og=60,sg=100,ig="New conversation",Kt=class{threadId(){let e=sessionStorage.getItem(rr);if(e!==null)return e;let n=Ce();return sessionStorage.setItem(rr,n),n}loadMessages(e){return Promise.resolve(this.#i(Xi+e))}saveMessages(e,n){sessionStorage.setItem(Xi+e,JSON.stringify(n)),this.#e(e,n)}loadCheckpoint(e){return this.#i(Zi+e)}saveCheckpoint(e,n){let r=Zi+e;if(n===null){sessionStorage.removeItem(r);return}sessionStorage.setItem(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(Xi+e),sessionStorage.removeItem(Zi+e),this.#o(this.#t().filter(n=>n.threadId!==e)),sessionStorage.getItem(rr)===e&&sessionStorage.removeItem(rr)}listThreads(){let e=this.#t().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(rr,e)}renameThread(e,n){let r=this.#t(),o=r.find(s=>s.threadId===e);o!==void 0&&(o.title=n,o.titleCustom=!0,this.#o(r))}#e(e,n){let r=this.#t(),o=r.find(a=>a.threadId===e),s=ag(n),i=Date.now();o===void 0?r.push({threadId:e,title:au(n),titleCustom:!1,preview:s,updatedAt:i}):(o.preview=s,o.updatedAt=i,o.titleCustom||(o.title=au(n))),this.#o(r)}#t(){return this.#i(Wi)??[]}#o(e){if(e.length===0){sessionStorage.removeItem(Wi);return}sessionStorage.setItem(Wi,JSON.stringify(e))}#i(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function au(t){for(let e of t)if(e.role==="user"){let n=lu(e.content);if(n!=="")return cu(n,og)}return ig}function ag(t){for(let e of[...t].reverse()){let n=lu(e.content);if(n!=="")return cu(n,sg)}return""}function lu(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function cu(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function Ki(t){return new yc({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 or=class{#e;#t;#o;#i=new Set;#a=new Map;constructor(e,n=()=>({}),r=new Kt){this.#e=e.endsWith("/")?e:`${e}/`,this.#t=n,this.#o=r}threadId(){return this.#o.threadId()}setActiveThread(e){this.#o.setActiveThread(e)}saveMessages(e,n){this.#o.saveMessages(e,n)}loadCheckpoint(e){return this.#o.loadCheckpoint(e)}saveCheckpoint(e,n){this.#o.saveCheckpoint(e,n)}renameThread(e,n){this.#o.renameThread(e,n),this.#a.set(e,n),this.#l(e,"PATCH",{title:n})}clear(e){this.#o.clear(e),this.#i.add(e),this.#l(e,"DELETE")}async listThreads(){let e=await this.#r();return e===null?this.#o.listThreads():e.filter(n=>!this.#i.has(n.thread_id)).map(n=>this.#n(n))}async loadMessages(e){let n=await this.#s(this.#e+encodeURIComponent(e)+"/");return n===null||!n.ok?this.#o.loadMessages(e):(await n.json()).messages??null}async#r(){let e=await this.#s(this.#e);return e===null||!e.ok?null:(await e.json()).threads??[]}#n(e){return{threadId:e.thread_id,title:this.#a.get(e.thread_id)??e.title,updatedAt:e.updated_at===null?0:Date.parse(e.updated_at),preview:e.preview}}async#s(e){try{return await fetch(e,{headers:this.#t()})}catch{return null}}async#l(e,n,r){let o=this.#t();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{}}};function Yi(t,e){return new Promise((n,r)=>{let o=new FormData;o.append("file",t);let s=new XMLHttpRequest;s.open("POST",e.url);for(let[l,c]of Object.entries(e.headers??{}))s.setRequestHeader(l,c);let i=e.onProgress;i!==void 0&&s.upload.addEventListener("progress",l=>{l.lengthComputable&&i(l.total===0?0:l.loaded/l.total)}),s.addEventListener("load",()=>{if(s.status>=200&&s.status<300)try{n(lg(JSON.parse(s.responseText)))}catch{r(new Error("upload returned an unreadable response"))}else r(new Error(cg(s)))}),s.addEventListener("error",()=>r(new Error("upload failed"))),s.addEventListener("abort",()=>r(new Error("upload cancelled")));let a=e.signal;a!==void 0&&a.addEventListener("abort",()=>s.abort()),s.send(o)})}function lg(t){if(typeof t!="object"||t===null)throw new Error("not an object");let e=t,n=e.id,r=e.name,o=e.mime,s=e.size,i=e.url;if(typeof n!="string"||typeof r!="string"||typeof o!="string"||typeof s!="number")throw new Error("missing fields");return typeof i=="string"?{id:n,name:r,mime:o,size:s,url:i}:{id:n,name:r,mime:o,size:s}}function cg(t){try{let e=JSON.parse(t.responseText);if(typeof e.error=="string")return e.error}catch{}return`upload failed (${t.status})`}var uu="ag-ui-chat:collapsed",sr=class extends HTMLElement{agentFactory=Ki;headers={};allowImages=!1;autoConfirm=!1;confirmPredicate=null;getTools=()=>[...this.#G().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#t.tools()];getContext=()=>[...Ns(this.getPageMap,this.autoInjectPageMap),...this.#q()];routeMap=[];navigate=null;getPageMap=null;autoInjectPageMap=!0;conversationStore=new Kt;uploadHandler=null;navigationResult=()=>({navigated:!0,url:window.location.href});skillContext=()=>({});toolSummaries={};#e={};#t=new Ln;#o=new Map;#i=new Set;#a;#r;#n;#s;#l;#h;#u;#T;#m;#p;#d;#_;#g=null;#y=[];#b=null;#I=!1;#S=null;#f=null;#C=0;#w=null;#c="";#N=[];#P=[];#D=[];#U=[];constructor(){super(),this.#a=this.attachShadow({mode:"open"}),this.#r=document.createElement("div"),this.#n=document.createElement("div"),this.#s=document.createElement("textarea"),this.#l=document.createElement("button"),this.#h=document.createElement("span"),this.#m=document.createElement("div"),this.#p=document.createElement("button"),this.#d=document.createElement("input"),this.#_=document.createElement("div"),this.#u=new ns(e=>this.#re(e)),this.#T=new rs({onSelect:e=>{this.#oe(e)},onNew:()=>{this.newChat(),this.#A()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#A()},onDelete:e=>{this.#se(e)}})}static get observedAttributes(){return["title-text"]}attributeChangedCallback(e,n,r){this.#h.textContent=r??"Assistant"}registerTool(e){this.#t.register(e)}registerStateHook(e){for(let n of Ms(e))this.#t.register(n)}#V(){return this.routeMap.length===0?[]:Os(()=>this.routeMap,()=>this.navigate)}#j(){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:[],[Ze]:"Read the page"},handler:()=>e()}]}#G(){return[...this.#V(),...this.#j()]}#H(e){let n=this.#G().find(r=>r.name===e);return n!==void 0?n:this.#t.has(e)?this.#t.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===Ke.MINIMAL||e===Ke.COMPACT?e:Ke.FULL}set toolDisplay(e){this.setAttribute("data-tool-display",e)}connectedCallback(){this.#ce(),sessionStorage.getItem(uu)==="1"&&this.setAttribute("collapsed",""),this.#ee(),this.#Q(),this.#J(),this.#W(),this.#c=this.conversationStore.threadId(),this.#F()}#W(){let e=this.getAttribute("data-attachments-url"),n=this.uploadHandler??this.#X(e);if(n===null)return;let r=this.getAttribute("data-attachment-accept")??"";this.#g=new Xo({upload:n,maxBytes:this.#Z(),accept:r}),this.#_.appendChild(this.#g.element),this.#d.accept=r,this.#p.hidden=!1,this.#Y()}#X(e){return e===null?null:(n,r)=>Yi(n,{url:e,headers:this.headers,onProgress:r})}#Z(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return As;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:As}#K(){let e=this.#d.files;if(e!==null)for(let n of Array.from(e))this.#g?.add(n);this.#d.value=""}#Y(){this.#r.addEventListener("dragover",e=>{e.preventDefault(),this.#r.classList.add("chat--dragover")}),this.#r.addEventListener("dragleave",()=>{this.#r.classList.remove("chat--dragover")}),this.#r.addEventListener("drop",e=>{e.preventDefault(),this.#r.classList.remove("chat--dragover");let n=e.dataTransfer?.files;if(n!==void 0)for(let r of Array.from(n))this.#g?.add(r)})}#q(){return this.#y.length===0?[]:[{description:"Files the user attached to this message",value:`${this.#y.map(n=>`- ${n.name} (id: ${n.id}, ${n.mime||"unknown type"}, ${n.size} bytes)`).join(`
1015
+ `)}
1016
+ Use the read_attachment tool with an id to read a file's contents.`}]}#J(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new or(e,()=>this.headers,this.conversationStore))}async#Q(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#e=Rs(await n.json())}catch{}}setSkills(e){this.#U=e,this.#R()}#ee(){this.#u.enableChips(this.getAttribute("data-prompt-chips")==="true"),this.#u.enableSlash(this.getAttribute("data-slash-commands")==="true"),this.#D=this.#te(),this.#R(),this.#ne()}#te(){let e=this.getAttribute("data-skills");if(e===null)return[];try{return ks(JSON.parse(e))}catch{return[]}}async#ne(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#P=ks(await n.json()),this.#R()}catch{}}#R(){let e=new Map;for(let n of[...this.#P,...this.#D,...this.#U])e.set(n.name,n);this.#u.setSkills([...e.values()])}#re(e){let{text:n,missing:r}=Ia(e.prompt,this.skillContext());if(r.length>0){this.#m.textContent=`\u201C${e.title}\u201D needs: ${r.join(", ")}`,this.#m.hidden=!1;return}this.#m.hidden=!0,this.#s.value=n,e.sendImmediately===!0?this.#M():this.#s.focus()}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(e){this.setCollapsed(e)}setCollapsed(e){e?this.setAttribute("collapsed",""):this.removeAttribute("collapsed"),sessionStorage.setItem(uu,e?"1":"0"),this.dispatchEvent(new CustomEvent(_s,{detail:{collapsed:e},bubbles:!0,composed:!0}))}toggleCollapsed(){this.setCollapsed(!this.collapsed)}newChat(){this.#x(),this.conversationStore.clear(this.#c),this.#O(),this.#c=this.conversationStore.threadId(),this.#E(!1)}#O(){this.#b=null,this.#f=null,this.#v(),this.#o.clear(),this.#i.clear(),this.#N=[],this.#y=[],this.#g?.clear(),this.#n.replaceChildren()}async#oe(e){e!==this.#c&&(this.#x(),this.#O(),this.conversationStore.setActiveThread(e),this.#c=e,this.#E(!1),await this.#F())}#se(e){let n=e===this.#c;n&&this.#x(),this.conversationStore.clear(e),n&&(this.#O(),this.#c=this.conversationStore.threadId(),this.#E(!1)),this.#A()}async#A(){this.#T.setThreads(await this.conversationStore.listThreads(),this.#c)}async#F(){let e=await this.conversationStore.loadMessages(this.#c);if(e!==null){this.#N=e;for(let r of e)this.#ie(r)}let n=this.conversationStore.loadCheckpoint(this.#c);n!==null&&await this.#le(n)}#ie(e){let n=typeof e.content=="string"?e.content:"";if(e.role===Xe.USER){let r=ji(e);if(n!==""||r.length>0){let o=this.appendMessage(Xe.USER,n);r.length>0&&o.appendChild(Ls(r))}return}if(e.role===Xe.ASSISTANT){n!==""&&this.appendMessage(Xe.ASSISTANT,n).classList.add("message--restored");let r=e.toolCalls;if(r!==void 0)for(let o of r)this.#L({id:o.id,name:o.function.name,args:this.#ae(o.function.arguments)});return}if(e.role==="tool"){let r=this.#o.get(e.toolCallId);r!==void 0&&r.settle(de.DONE,e.content)}}#ae(e){try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#$(e){this.getAttribute("data-text-animation")==="word"&&ru(e)}async#le(e){this.conversationStore.saveCheckpoint(this.#c,null);let n=this.#z();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===Xe.ASSISTANT?r.innerHTML=ts(n,{allowImages:this.allowImages}):r.textContent=n,this.#n.appendChild(r),this.#n.scrollTop=this.#n.scrollHeight,r}#ce(){let e=document.createElement("style");e.textContent=ou,this.#r.className="chat";let n=document.createElement("div");n.className="header";let r=this.#h;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.#A(),this.#T.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.#n.className="messages",this.#n.setAttribute("role","log"),this.#n.setAttribute("aria-live","polite"),this.#n.setAttribute("aria-label","Conversation");let l=document.createElement("div");l.className="input-row",this.#s.className="input",this.#s.setAttribute("aria-label","Message"),this.#s.rows=2,this.#s.placeholder="Ask anything\u2026",this.#s.addEventListener("keydown",c=>this.#de(c)),this.#s.addEventListener("input",()=>this.#ue()),this.#l.className="send",this.#l.type="button",this.#l.textContent="Send",this.#l.setAttribute("aria-label","Send"),this.#l.dataset.state="idle",this.#l.addEventListener("click",()=>{if(this.#I){this.#x();return}this.#M()}),this.#m.className="skill-hint",this.#m.hidden=!0,this.#p.className="attach-btn",this.#p.type="button",this.#p.textContent="\u{1F4CE}",this.#p.title="Attach files",this.#p.setAttribute("aria-label","Attach files"),this.#p.hidden=!0,this.#p.addEventListener("click",()=>this.#d.click()),this.#d.className="attach-input",this.#d.type="file",this.#d.multiple=!0,this.#d.hidden=!0,this.#d.addEventListener("change",()=>this.#K()),this.#_.className="attachment-slot",l.append(this.#p,this.#s,this.#l,this.#d),this.#r.append(n,this.#n,this.#u.palette,this.#u.chips,this.#m,this.#_,l,this.#T.element),this.#a.append(e,this.#r)}#ue(){this.#u.onInput(this.#s.value),this.#m.hidden=!0}#de(e){if(this.#u.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#I){e.preventDefault(),this.#x();return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this.#M())}#x(){this.#S?.abort(),this.#b?.cancel()}#E(e){this.#I=e;let n=e?"Stop":"Send";this.#l.textContent=n,this.#l.setAttribute("aria-label",n),this.#l.dataset.state=e?"running":"idle"}async#M(){let e=this.#s.value.trim(),n=this.#g?.readyRefs()??[];if(e===""&&n.length===0)return;let r=this.appendMessage(Xe.USER,e);n.length>0&&r.appendChild(Ls(n)),this.#s.value="",this.#g?.clearReady(),this.#y=n,this.dispatchEvent(new CustomEvent(Ts,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#pe(e,n)}async#pe(e,n){this.endpoint!==""&&await this.#z().send(e,n)}#z(){if(this.#b===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#c,initialMessages:this.#N});this.#b=new nr({agent:e,handlers:this.#me(),getTools:()=>this.getTools(),getContext:()=>this.getContext(),executeTool:n=>this.#he(n),onPersist:n=>this.conversationStore.saveMessages(this.#c,n)})}return this.#b}async#fe(e,n){return this.autoConfirm?!1:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0:Is(n.parameters)}async#he(e){let n=this.#L(e);this.#o.delete(e.id);let r=this.#H(e.name);if(r===null)return this.#i.has(e.id)||n.settle(de.DONE,"No result returned."),null;if(await this.#fe(e,r)){let s={toolName:e.name,args:e.args},i=r.parameters[Ss];typeof i=="string"&&(s.message=i),this.#S=new AbortController;let a=_i(this.#n,s,{signal:this.#S.signal});this.#n.scrollTop=this.#n.scrollHeight;let l=await a;if(this.#S=null,!l){let c="User declined the action.";return n.settle(de.DECLINED,c),this.#k(),{content:c}}}let o=Cs(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.#k(),{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.#k(),{content:`Error: ${i}`,error:i}}}#me(){return{onRunStart:()=>{this.#E(!0),this.#k()},onTextDelta:e=>{this.#v(),this.#B(e),this.#C+=1},onTextEnd:e=>{let n=this.#B(e);this.#C<=1&&this.#$(n),this.#f=null},onToolCall:e=>{this.#v(),this.#L(e)},onToolResult:(e,n)=>{let r=this.#o.get(e);r!==void 0&&(r.settle(de.DONE,n),this.#i.add(e))},onRunEnd:()=>{this.#v(),this.#f=null},onError:e=>{this.#v(),this.#$(this.appendMessage(Xe.ASSISTANT,`\u26A0\uFE0F ${e}`)),this.#f=null},onCancelled:()=>{this.#v(),this.#ge(),this.#f=null},onSettled:()=>{this.#v(),this.#E(!1),this.#f=null,this.#y=[]}}}#ge(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("role","status"),e.textContent="\u23F9 Stopped",this.#n.appendChild(e),this.#n.scrollTop=this.#n.scrollHeight}#k(){if(this.#w!==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.#w=e,this.#n.appendChild(e),this.#n.scrollTop=this.#n.scrollHeight}#v(){this.#w?.remove(),this.#w=null}#B(e){return this.#f===null&&(this.#f=this.appendMessage(Xe.ASSISTANT,""),this.#C=0),this.#f.innerHTML=ts(e,{allowImages:this.allowImages}),this.#n.scrollTop=this.#n.scrollHeight,this.#f}#L(e){let n=this.#o.get(e.id);if(n!==void 0)return n;let r=this.#H(e.name)?.parameters[Ze],o=typeof r=="string"?r:this.toolSummaries[e.name]??this.#e[e.name]??Si(e.name),s=new tr(e.name,e.args,this.toolDisplay,o);return this.#o.set(e.id,s),this.#n.appendChild(s.element),this.#n.scrollTop=this.#n.scrollHeight,s}};function ug(){customElements.get(br)===void 0&&customElements.define(br,sr)}function os(t,e){return Object.getOwnPropertyDescriptor(t,e).set}var dg=os(HTMLInputElement.prototype,"value"),pg=os(HTMLTextAreaElement.prototype,"value"),fg=os(HTMLSelectElement.prototype,"value"),hg=os(HTMLInputElement.prototype,"checked");function Yt(t,e){t instanceof HTMLTextAreaElement?pg.call(t,e):t instanceof HTMLSelectElement?fg.call(t,e):dg.call(t,e)}function ir(t,e){hg.call(t,e)}var du="#4f46e5";function ss(t){return new Promise(e=>{setTimeout(e,t)})}async function qi(t,e,n={}){let r=n.charDelayMs??35;Yt(t,""),t.dispatchEvent(new Event("input",{bubbles:!0}));for(let o of e)Yt(t,t.value+o),t.dispatchEvent(new Event("input",{bubbles:!0})),r>0&&await ss(r);t.dispatchEvent(new Event("change",{bubbles:!0}))}async function Ji(t,e={}){let n=e.highlightMs??280,r=t.style.outline,o=t.style.outlineOffset;t.style.outline=`2px solid ${du}`,t.style.outlineOffset="2px",await ss(n),t.style.outline=r,t.style.outlineOffset=o,t.click()}function qt(t){t.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}async function Qi(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 ss(n),t.style.boxShadow=r}var pu="0 0 0 3px rgba(79, 70, 229, 0.4)";function fu(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}function ea(t){return t<=0||fu()?Promise.resolve():ss(t)}async function ta(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=pu,await ea(n),t.style.transform=r,t.style.transition=o,t.style.boxShadow=s,t.click()}function mg(t,e){for(let n of Array.from(t.options))if(n.value===e||n.text===e)return n;return null}async function na(t,e,n={}){let r=mg(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 ${du}`,t.style.outlineOffset="2px",await ea(o),Yt(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 ra(t,e,n={}){let r=n.flashMs??200,o=t.style.boxShadow;t.style.boxShadow=pu,await ea(r),ir(t,e),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.boxShadow=o}async function gg(t,e,n={}){qt(t),await Qi(t,{flashMs:n.flashMs??0}),await qi(t,e,n)}async function vg(t,e={}){qt(t),await Ji(t,e)}async function yg(t,e={}){qt(t),await ta(t,e)}async function bg(t,e,n={}){qt(t),await na(t,e,n)}async function xg(t,e,n={}){qt(t),await ra(t,e,n)}function Eg(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?ir(t,!!e):Yt(t,String(e)),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}var Tg="0.6.0";export{sr as AgUiChat,nr as AgUiClient,Ln as ClientToolRegistry,br as ELEMENT_TAG,ws as MAX_TOOL_ROUNDS,Xe as MESSAGE_ROLE,or as RemoteConversationStore,Ts as SUBMIT_EVENT,Kt as SessionStorageStore,_s as TOGGLE_EVENT,de as TOOL_CALL_STATUS,Ke as TOOL_DISPLAY,tr as ToolCallCard,Tg as VERSION,Ss as X_CONFIRM_KEY,On as X_DESTRUCTIVE_KEY,Mn as X_NAVIGATES_KEY,Ze as X_SUMMARY_KEY,vg as clickElement,Ki as createHttpAgent,Ns as createPageMapContext,Os as createRouteTools,Ms as createStateHookTools,ug as defineAgUiChat,gg as fillField,Qi as focusWithFlash,Ji as highlightThenClick,Is as isDestructive,Cs as isNavigates,ji as messageAttachments,Rs as parseToolCatalog,fu as prefersReducedMotion,yg as pressButton,ta as pressThenClick,Si as prettifyToolName,ts as renderMarkdown,_i as requestConfirmation,qt as scrollIntoCenterView,bg as selectControl,na as selectOption,Eg as setControlValue,ir as setNativeChecked,Yt as setNativeValue,xg as toggleCheckbox,ra as toggleControl,qi as typeInto,Yi as uploadAttachment};
1017
+ /*! Bundled license information:
725
1018
 
726
1019
  fast-json-patch/module/helpers.mjs:
727
1020
  (*!
@@ -736,5 +1029,8 @@ fast-json-patch/module/duplex.mjs:
736
1029
  * (c) 2017-2021 Joachim Wester
737
1030
  * MIT license
738
1031
  *)
1032
+
1033
+ dompurify/dist/purify.es.mjs:
1034
+ (*! @license DOMPurify 3.4.7 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.7/LICENSE *)
739
1035
  */
740
1036
  //# sourceMappingURL=ag-ui-web-component.bundle.js.map