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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- var fu=Object.defineProperty;var ms=(e,t)=>{for(var n in t)fu(e,n,{get:t[n],enumerable:!0})};var gr="ag-ui-chat",gs="ag-ui-submit",vs="ag-ui-toggle",We={USER:"user",ASSISTANT:"assistant"},Nn="x-destructive",ys="x-confirm",Xe="x-summary",Rn="x-navigates",bs=10,de={PENDING:"pending",DONE:"done",ERROR:"error",DECLINED:"declined"},Ze={MINIMAL:"minimal",COMPACT:"compact",FULL:"full"};var hu=/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;function va(e,t){let n=[];return{text:e.replace(hu,(o,s)=>{let i=t[s];return i==null||i===""?(n.includes(s)||n.push(s),o):String(i)}),missing:n}}function mu(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.name=="string"&&typeof t.title=="string"&&typeof t.prompt=="string"}function xs(e){return Array.isArray(e)?e.filter(mu):[]}var On=class{#e=new Map;register(t){this.#e.set(t.name,t)}has(t){return this.#e.has(t)}get(t){let n=this.#e.get(t);if(n===void 0)throw new Error(`tool "${t}" is not registered`);return n}tools(){return[...this.#e.values()].map(t=>({name:t.name,description:t.description,parameters:t.parameters}))}};function Es(e){return e[Nn]===!0}function _s(e){return e[Rn]===!0}function Ts(e,t){return!t||e===null?[]:[{description:"page_map",value:JSON.stringify(e())}]}function Ss(e){let t={};if(!Array.isArray(e))return t;for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=r.name,s=r.summary;typeof o=="string"&&typeof s=="string"&&(t[o]=s)}return t}var ya=/:([A-Za-z_][A-Za-z0-9_]*)/g;function gu(e){let t=[];for(let n of e.matchAll(ya)){let r=n[1];r!==void 0&&t.push(r)}return t}function vu(e,t,n){let r={...n};return{path:t.replace(ya,(s,i)=>{let a=n[i];if(a==null||String(a)==="")throw new Error(`route "${e}" requires path param "${i}"`);return delete r[i],encodeURIComponent(String(a))}),leftover:r}}function yu(e,t){let n=new URLSearchParams;for(let[o,s]of Object.entries(t))n.set(o,String(s));let r=n.toString();return r===""?e:`${e}?${r}`}function ws(e,t){return[{name:"list_routes",description:"List the routes the app can navigate to. Each route's `pathParams` names the dynamic segments to pass as `params` to `navigate_to_route`.",parameters:{type:"object",properties:{},required:[],[Xe]:"List pages"},handler:()=>e().map(n=>({...n,pathParams:gu(n.path)}))},{name:"navigate_to_route",description:"Navigate to one of the app's routes by its id, filling any dynamic `:name` path segments (and extra query params) from `params`.",parameters:{type:"object",properties:{route_id:{type:"string"},params:{type:"object"}},required:["route_id"],[Rn]:!0,[Xe]:"Navigate"},handler:n=>{let r=n.route_id,o=e().find(p=>p.id===r);if(o===void 0)throw new Error(`unknown route "${String(r)}"`);let s=n.params??{},{path:i,leftover:a}=vu(o.id,o.path,s),u=yu(i,a),c=t();return c!==null?c(u):window.location.assign(u),{navigated:!0,path:u}}}]}function ks(e){let t=[{name:`read_${e.name}`,description:`Read the "${e.name}" state.`,parameters:{type:"object",properties:{},required:[],[Xe]:`Read ${e.name}`},handler:()=>e.read()}],n=e.write;return n!==void 0&&t.push({name:`set_${e.name}`,description:`Update the "${e.name}" state.`,parameters:{...e.schema??{type:"object"},[Nn]:!0,[Xe]:`Update ${e.name}`},handler:r=>n(r)}),t}function ba(e,t){let n=document.createElement("button");return n.type="button",n.className=`confirm-btn confirm-btn--${e}`,n.textContent=t,n}function As(e,t){return new Promise(n=>{let r=document.createElement("div");r.className="confirm",r.setAttribute("data-tool-name",t.toolName),r.setAttribute("role","group"),r.setAttribute("aria-label","Confirm action");let o=document.createElement("div");o.className="confirm-body",o.textContent=t.message??`Run \u201C${t.toolName}\u201D?`;let s=document.createElement("pre");s.className="confirm-args",s.textContent=JSON.stringify(t.args,null,2);let i=document.createElement("div");i.className="confirm-actions";let a=ba("cancel","Cancel"),u=ba("confirm","Confirm"),c=p=>{a.disabled=!0,u.disabled=!0,r.setAttribute("data-resolved",p?"confirmed":"declined"),n(p)};a.addEventListener("click",()=>c(!1)),u.addEventListener("click",()=>c(!0)),i.append(a,u),r.append(o,s,i),e.appendChild(r),u.focus()})}function Is(e){let t=e.replace(/[._-]+/g," ").trim();return t===""?e:t.charAt(0).toUpperCase()+t.slice(1)}function xa(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function bu(e){if(Array.isArray(e))return e}function xu(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,o,s,i,a=[],u=!0,c=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(u=(r=s.call(n)).done)&&(a.push(r.value),a.length!==t);u=!0);}catch(p){c=!0,o=p}finally{try{if(!u&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(c)throw o}}return a}}function Eu(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
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
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
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
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(`
@@ -63,7 +63,7 @@ ${this.parser.parse(e)}</blockquote>
63
63
  ${e}</tr>
64
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
65
  `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${qe(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),o=Ha(e);if(o===null)return r;e=o;let s='<a href="'+e+'"';return t&&(s+=' title="'+qe(t)+'"'),s+=">"+r+"</a>",s}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let o=Ha(e);if(o===null)return qe(n);e=o;let s=`<img src="${e}" alt="${qe(n)}"`;return t&&(s+=` title="${qe(t)}"`),s+=">",s}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:qe(e.text)}},Xs=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Ge=class Gs{options;renderer;textRenderer;constructor(t){this.options=t||St,this.options.renderer=this.options.renderer||new Er,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Xs}static parse(t,n){return new Gs(n).parse(t)}static parseInline(t,n){return new Gs(n).parseInline(t)}parse(t){this.renderer.parser=this;let n="";for(let r=0;r<t.length;r++){let o=t[r];if(this.options.extensions?.renderers?.[o.type]){let i=o,a=this.options.extensions.renderers[i.type].call({parser:this},i);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(i.type)){n+=a||"";continue}}let s=o;switch(s.type){case"space":{n+=this.renderer.space(s);break}case"hr":{n+=this.renderer.hr(s);break}case"heading":{n+=this.renderer.heading(s);break}case"code":{n+=this.renderer.code(s);break}case"table":{n+=this.renderer.table(s);break}case"blockquote":{n+=this.renderer.blockquote(s);break}case"list":{n+=this.renderer.list(s);break}case"checkbox":{n+=this.renderer.checkbox(s);break}case"html":{n+=this.renderer.html(s);break}case"def":{n+=this.renderer.def(s);break}case"paragraph":{n+=this.renderer.paragraph(s);break}case"text":{n+=this.renderer.text(s);break}default:{let i='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(i),"";throw new Error(i)}}}return n}parseInline(t,n=this.renderer){this.renderer.parser=this;let r="";for(let o=0;o<t.length;o++){let s=t[o];if(this.options.extensions?.renderers?.[s.type]){let a=this.options.extensions.renderers[s.type].call({parser:this},s);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)){r+=a||"";continue}}let i=s;switch(i.type){case"escape":{r+=n.text(i);break}case"html":{r+=n.html(i);break}case"link":{r+=n.link(i);break}case"image":{r+=n.image(i);break}case"checkbox":{r+=n.checkbox(i);break}case"strong":{r+=n.strong(i);break}case"em":{r+=n.em(i);break}case"codespan":{r+=n.codespan(i);break}case"br":{r+=n.br(i);break}case"del":{r+=n.del(i);break}case"text":{r+=n.text(i);break}default:{let a='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return r}},Un=class{options;block;constructor(e){this.options=e||St}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Ue.lex:Ue.lexInline}provideParser(e=this.block){return e?Ge.parse:Ge.parseInline}},Zs=class{defaults=Fs();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Ge;Renderer=Er;TextRenderer=Xs;Lexer=Ue;Tokenizer=xr;Hooks=Un;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case"table":{let o=r;for(let s of o.header)n=n.concat(this.walkTokens(s.tokens,t));for(let s of o.rows)for(let i of s)n=n.concat(this.walkTokens(i.tokens,t));break}case"list":{let o=r;n=n.concat(this.walkTokens(o.items,t));break}default:{let o=r;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(s=>{let i=o[s].flat(1/0);n=n.concat(this.walkTokens(i,t))}):o.tokens&&(n=n.concat(this.walkTokens(o.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let s=t.renderers[o.name];s?t.renderers[o.name]=function(...i){let a=o.renderer.apply(this,i);return a===!1&&(a=s.apply(this,i)),a}:t.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let s=t[o.level];s?s.unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),r.extensions=t),n.renderer){let o=this.defaults.renderer||new Er(this.defaults);for(let s in n.renderer){if(!(s in o))throw new Error(`renderer '${s}' does not exist`);if(["options","parser"].includes(s))continue;let i=s,a=n.renderer[i],u=o[i];o[i]=(...c)=>{let p=a.apply(o,c);return p===!1&&(p=u.apply(o,c)),p||""}}r.renderer=o}if(n.tokenizer){let o=this.defaults.tokenizer||new xr(this.defaults);for(let s in n.tokenizer){if(!(s in o))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let i=s,a=n.tokenizer[i],u=o[i];o[i]=(...c)=>{let p=a.apply(o,c);return p===!1&&(p=u.apply(o,c)),p}}r.tokenizer=o}if(n.hooks){let o=this.defaults.hooks||new Un;for(let s in n.hooks){if(!(s in o))throw new Error(`hook '${s}' does not exist`);if(["options","block"].includes(s))continue;let i=s,a=n.hooks[i],u=o[i];Un.passThroughHooks.has(s)?o[i]=c=>{if(this.defaults.async&&Un.passThroughHooksRespectAsync.has(s))return(async()=>{let m=await a.call(o,c);return u.call(o,m)})();let p=a.call(o,c);return u.call(o,p)}:o[i]=(...c)=>{if(this.defaults.async)return(async()=>{let m=await a.apply(o,c);return m===!1&&(m=await u.apply(o,c)),m})();let p=a.apply(o,c);return p===!1&&(p=u.apply(o,c)),p}}r.hooks=o}if(n.walkTokens){let o=this.defaults.walkTokens,s=n.walkTokens;r.walkTokens=function(i){let a=[];return a.push(s.call(this,i)),o&&(a=a.concat(o.call(this,i))),a}}this.defaults={...this.defaults,...r}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Ue.lex(e,t??this.defaults)}parser(e,t){return Ge.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},o={...this.defaults,...r},s=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&r.async===!1)return s(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return s(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return s(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=e),o.async)return(async()=>{let i=o.hooks?await o.hooks.preprocess(t):t,a=await(o.hooks?await o.hooks.provideLexer(e):e?Ue.lex:Ue.lexInline)(i,o),u=o.hooks?await o.hooks.processAllTokens(a):a;o.walkTokens&&await Promise.all(this.walkTokens(u,o.walkTokens));let c=await(o.hooks?await o.hooks.provideParser(e):e?Ge.parse:Ge.parseInline)(u,o);return o.hooks?await o.hooks.postprocess(c):c})().catch(s);try{o.hooks&&(t=o.hooks.preprocess(t));let i=(o.hooks?o.hooks.provideLexer(e):e?Ue.lex:Ue.lexInline)(t,o);o.hooks&&(i=o.hooks.processAllTokens(i)),o.walkTokens&&this.walkTokens(i,o.walkTokens);let a=(o.hooks?o.hooks.provideParser(e):e?Ge.parse:Ge.parseInline)(i,o);return o.hooks&&(a=o.hooks.postprocess(a)),a}catch(i){return s(i)}}}onError(e,t){return n=>{if(n.message+=`
66
- Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error occurred:</p><pre>"+qe(n.message+"",!0)+"</pre>";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}},Tt=new Zs;function Z(e,t){return Tt.parse(e,t)}Z.options=Z.setOptions=function(e){return Tt.setOptions(e),Z.defaults=Tt.defaults,Va(Z.defaults),Z};Z.getDefaults=Fs;Z.defaults=St;Z.use=function(...e){return Tt.use(...e),Z.defaults=Tt.defaults,Va(Z.defaults),Z};Z.walkTokens=function(e,t){return Tt.walkTokens(e,t)};Z.parseInline=Tt.parseInline;Z.Parser=Ge;Z.parser=Ge.parse;Z.Renderer=Er;Z.TextRenderer=Xs;Z.Lexer=Ue;Z.lexer=Ue.lex;Z.Tokenizer=xr;Z.Hooks=Un;Z.parse=Z;var vg=Z.options,yg=Z.setOptions,bg=Z.use,xg=Z.walkTokens,Eg=Z.parseInline;var _g=Ge.parse,Tg=Ue.lex;var Pd=new Zs({gfm:!0,breaks:!0}),el=["a","p","br","strong","em","b","i","u","s","del","code","pre","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","hr","span","table","thead","tbody","tr","th","td"],tl=["href","title","class"],Dd=[...el,"img"],Ud=[...tl,"src","alt","width","height"];function Sr(e,t){let n=t?.allowImages===!0,r=Pd.parse(e,{async:!1}),o=Da.sanitize(r,{ALLOWED_TAGS:n?Dd:el,ALLOWED_ATTR:n?Ud:tl}),s=document.createElement("template");s.innerHTML=o;for(let i of s.content.querySelectorAll("a[href]"))i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer");return s.innerHTML.trim()}function nl(e,t){for(let n of Array.from(e.childNodes))n.nodeType===Node.TEXT_NODE?t.push({node:n,parent:e}):nl(n,t)}function rl(e){let t=[];nl(e,t);let n=0;for(let{node:r,parent:o}of t){let s=document.createDocumentFragment();for(let i of r.data.split(/(\s+)/)){if(i==="")continue;if(/\s/.test(i)){s.appendChild(document.createTextNode(i));continue}let a=document.createElement("span");a.className="word",a.style.setProperty("--ag-ui-word-index",String(n)),a.textContent=i,s.appendChild(a),n+=1}o.replaceChild(s,r)}}var wr=class{chips;palette;#e;#n=[];#i=!1;#u=!1;#a=[];#o=0;constructor(t){this.#e=t,this.chips=document.createElement("div"),this.chips.className="skill-chips",this.chips.hidden=!0,this.palette=document.createElement("div"),this.palette.className="skill-palette",this.palette.setAttribute("role","listbox"),this.palette.hidden=!0}setSkills(t){this.#n=t,this.#f()}enableChips(t){this.#i=t,this.#f()}enableSlash(t){this.#u=t}isOpen(){return!this.palette.hidden}onInput(t){this.#u&&t.startsWith("/")?this.#t(t.slice(1)):this.close()}onKeydown(t){return this.isOpen()?t.key==="ArrowDown"?(this.#r(1),!0):t.key==="ArrowUp"?(this.#r(-1),!0):t.key==="Escape"?(this.close(),!0):t.key==="Enter"?(this.#a.slice(this.#o,this.#o+1).forEach(n=>{this.#s(n)}),!0):!1:!1}close(){this.palette.hidden=!0,this.palette.replaceChildren()}#t(t){let n=t.trim().toLowerCase(),r=this.#n.filter(o=>o.name.toLowerCase().includes(n)||o.title.toLowerCase().includes(n));if(r.length===0){this.close();return}this.#a=r,this.#o=0,this.#l(),this.palette.hidden=!1}#r(t){let n=this.#a.length;this.#o=(this.#o+t+n)%n,this.#l()}#s(t){this.close(),this.#e(t)}#f(){this.chips.replaceChildren();let t=this.#i?this.#n.filter(n=>n.chip===!0):[];this.chips.hidden=t.length===0;for(let n of t){let r=document.createElement("button");r.type="button",r.className="skill-chip",r.textContent=n.title,r.addEventListener("click",()=>this.#s(n)),this.chips.appendChild(r)}}#l(){this.palette.replaceChildren(),this.#a.forEach((t,n)=>{let r=document.createElement("button");r.type="button",r.className="skill-item",r.setAttribute("role","option"),r.setAttribute("aria-selected",n===this.#o?"true":"false");let o=document.createElement("span");if(o.className="skill-item-title",o.textContent=t.title,r.appendChild(o),t.description!==void 0){let s=document.createElement("span");s.className="skill-item-desc",s.textContent=t.description,r.appendChild(s)}r.addEventListener("click",()=>this.#s(t)),this.palette.appendChild(r)})}};var ol=`
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=`
67
67
  :host {
68
68
  /* Colors */
69
69
  --ag-ui-bg: #ffffff;
@@ -562,6 +562,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
562
562
  cursor: default;
563
563
  }
564
564
 
565
+ /* The composer button doubles as the Stop control while a run is in flight. */
566
+ .send[data-state="running"] {
567
+ background: var(--ag-ui-muted);
568
+ }
569
+
570
+ /* Muted "\u23F9 Stopped" line after a cancelled run \u2014 a note, not an error bubble. */
571
+ .stopped-note {
572
+ align-self: flex-start;
573
+ color: var(--ag-ui-muted);
574
+ font-size: 12px;
575
+ padding: 2px 4px;
576
+ }
577
+
565
578
  /* Inline confirmation card \u2014 lives in the transcript, no focus-stealing overlay. */
566
579
  .confirm {
567
580
  align-self: stretch;
@@ -694,7 +707,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
694
707
  }
695
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)}
696
709
 
697
- ${n}`):(r.textContent=Gd[t],o.textContent=n),r.addEventListener("click",()=>{let s=o.hidden;o.hidden=!s,r.setAttribute("aria-expanded",String(s))}),this.element.append(r,o)}};var ve=[];for(let e=0;e<256;++e)ve.push((e+256).toString(16).slice(1));function il(e,t=0){return(ve[e[t+0]]+ve[e[t+1]]+ve[e[t+2]]+ve[e[t+3]]+"-"+ve[e[t+4]]+ve[e[t+5]]+"-"+ve[e[t+6]]+ve[e[t+7]]+"-"+ve[e[t+8]]+ve[e[t+9]]+"-"+ve[e[t+10]]+ve[e[t+11]]+ve[e[t+12]]+ve[e[t+13]]+ve[e[t+14]]+ve[e[t+15]]).toLowerCase()}var Ks,Fd=new Uint8Array(16);function Ys(){if(!Ks){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Ks=crypto.getRandomValues.bind(crypto)}return Ks(Fd)}var Hd=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),qs={randomUUID:Hd};function $d(e,t,n){if(qs.randomUUID&&!t&&!e)return qs.randomUUID();e=e||{};let r=e.random??e.rng?.()??Ys();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n=n||0,n<0||n+16>t.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)t[n+o]=r[o];return t}return il(r)}var ht=$d;var l={};ms(l,{BRAND:()=>fp,DIRTY:()=>wt,EMPTY_PATH:()=>jd,INVALID:()=>O,NEVER:()=>qp,OK:()=>_e,ParseStatus:()=>ye,Schema:()=>U,ZodAny:()=>vt,ZodArray:()=>lt,ZodBigInt:()=>At,ZodBoolean:()=>It,ZodBranded:()=>$n,ZodCatch:()=>Ft,ZodDate:()=>Ct,ZodDefault:()=>Gt,ZodDiscriminatedUnion:()=>Ir,ZodEffects:()=>Me,ZodEnum:()=>Dt,ZodError:()=>we,ZodFirstPartyTypeKind:()=>M,ZodFunction:()=>Nr,ZodIntersection:()=>Mt,ZodIssueCode:()=>E,ZodLazy:()=>Lt,ZodLiteral:()=>Pt,ZodMap:()=>fn,ZodNaN:()=>mn,ZodNativeEnum:()=>Ut,ZodNever:()=>Fe,ZodNull:()=>Rt,ZodNullable:()=>et,ZodNumber:()=>kt,ZodObject:()=>ke,ZodOptional:()=>Re,ZodParsedType:()=>A,ZodPipeline:()=>zn,ZodPromise:()=>yt,ZodReadonly:()=>Ht,ZodRecord:()=>Cr,ZodSchema:()=>U,ZodSet:()=>hn,ZodString:()=>gt,ZodSymbol:()=>dn,ZodTransformer:()=>Me,ZodTuple:()=>Qe,ZodType:()=>U,ZodUndefined:()=>Nt,ZodUnion:()=>Ot,ZodUnknown:()=>at,ZodVoid:()=>pn,addIssueToContext:()=>w,any:()=>_p,array:()=>kp,bigint:()=>vp,boolean:()=>vl,coerce:()=>Yp,custom:()=>hl,date:()=>yp,datetimeRegex:()=>pl,defaultErrorMap:()=>st,discriminatedUnion:()=>Np,effect:()=>zp,enum:()=>Fp,function:()=>Dp,getErrorMap:()=>ln,getParsedType:()=>Je,instanceof:()=>mp,intersection:()=>Rp,isAborted:()=>kr,isAsync:()=>cn,isDirty:()=>Ar,isValid:()=>mt,late:()=>hp,lazy:()=>Up,literal:()=>Gp,makeIssue:()=>Hn,map:()=>Lp,nan:()=>gp,nativeEnum:()=>Hp,never:()=>Sp,null:()=>Ep,nullable:()=>Vp,number:()=>gl,object:()=>Ap,objectUtil:()=>Js,oboolean:()=>Kp,onumber:()=>Zp,optional:()=>Bp,ostring:()=>Xp,pipeline:()=>Wp,preprocess:()=>jp,promise:()=>$p,quotelessJson:()=>zd,record:()=>Mp,set:()=>Pp,setErrorMap:()=>Vd,strictObject:()=>Ip,string:()=>ml,symbol:()=>bp,transformer:()=>zp,tuple:()=>Op,undefined:()=>xp,union:()=>Cp,unknown:()=>Tp,util:()=>H,void:()=>wp});var H;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},e.getValidEnumValues=o=>{let s=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return e.objectValues(i)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},e.find=(o,s)=>{for(let i of o)if(s(i))return i},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(H||(H={}));var Js;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Js||(Js={}));var A=H.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Je=e=>{switch(typeof e){case"undefined":return A.undefined;case"string":return A.string;case"number":return Number.isNaN(e)?A.nan:A.number;case"boolean":return A.boolean;case"function":return A.function;case"bigint":return A.bigint;case"symbol":return A.symbol;case"object":return Array.isArray(e)?A.array:e===null?A.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?A.promise:typeof Map<"u"&&e instanceof Map?A.map:typeof Set<"u"&&e instanceof Set?A.set:typeof Date<"u"&&e instanceof Date?A.date:A.object;default:return A.unknown}};var E=H.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),zd=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),we=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,u=0;for(;u<i.path.length;){let c=i.path[u];u===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(i))):a[c]=a[c]||{_errors:[]},a=a[c],u++}}};return o(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,H.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};we.create=e=>new we(e);var Bd=(e,t)=>{let n;switch(e.code){case E.invalid_type:e.received===A.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case E.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,H.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:n=`Unrecognized key(s) in object: ${H.joinValues(e.keys,", ")}`;break;case E.invalid_union:n="Invalid input";break;case E.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${H.joinValues(e.options)}`;break;case E.invalid_enum_value:n=`Invalid enum value. Expected ${H.joinValues(e.options)}, received '${e.received}'`;break;case E.invalid_arguments:n="Invalid function arguments";break;case E.invalid_return_type:n="Invalid function return type";break;case E.invalid_date:n="Invalid date";break;case E.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:H.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case E.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case E.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case E.custom:n="Invalid input";break;case E.invalid_intersection_types:n="Intersection results could not be merged";break;case E.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case E.not_finite:n="Number must be finite";break;default:n=t.defaultError,H.assertNever(e)}return{message:n}},st=Bd;var al=st;function Vd(e){al=e}function ln(){return al}var Hn=e=>{let{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",u=r.filter(c=>!!c).slice().reverse();for(let c of u)a=c(i,{data:t,defaultError:a}).message;return{...o,path:s,message:a}},jd=[];function w(e,t){let n=ln(),r=Hn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===st?void 0:st].filter(o=>!!o)});e.common.issues.push(r)}var ye=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let o of n){if(o.status==="aborted")return O;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return O;s.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:t.value,value:r}}},O=Object.freeze({status:"aborted"}),wt=e=>({status:"dirty",value:e}),_e=e=>({status:"valid",value:e}),kr=e=>e.status==="aborted",Ar=e=>e.status==="dirty",mt=e=>e.status==="valid",cn=e=>typeof Promise<"u"&&e instanceof Promise;var I;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(I||(I={}));var Oe=class{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ll=(e,t)=>{if(mt(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new we(e.common.issues);return this._error=n,this._error}}};function L(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(i,a)=>{let{message:u}=e;return i.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:u??n??a.defaultError}},description:o}}var U=class{get description(){return this._def.description}_getType(t){return Je(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Je(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ye,ctx:{common:t.parent.common,data:t.data,parsedType:Je(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(cn(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Je(t)},o=this._parseSync({data:t,path:r.path,parent:r});return ll(r,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Je(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return mt(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>mt(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){let r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Je(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(cn(o)?o:Promise.resolve(o));return ll(r,s)}refine(t,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=t(o),a=()=>s.addIssue({code:E.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(u=>u?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Me({schema:this,typeName:M.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Re.create(this,this._def)}nullable(){return et.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return lt.create(this)}promise(){return yt.create(this,this._def)}or(t){return Ot.create([this,t],this._def)}and(t){return Mt.create(this,t,this._def)}transform(t){return new Me({...L(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new Gt({...L(this._def),innerType:this,defaultValue:n,typeName:M.ZodDefault})}brand(){return new $n({typeName:M.ZodBranded,type:this,...L(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new Ft({...L(this._def),innerType:this,catchValue:n,typeName:M.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return zn.create(this,t)}readonly(){return Ht.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Wd=/^c[^\s-]{8,}$/i,Xd=/^[0-9a-z]+$/,Zd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Kd=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Yd=/^[a-z0-9_-]{21}$/i,qd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Jd=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Qd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ep="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Qs,tp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,np=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,rp=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,op=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,sp=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ip=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ul="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",ap=new RegExp(`^${ul}$`);function dl(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function lp(e){return new RegExp(`^${dl(e)}$`)}function pl(e){let t=`${ul}T${dl(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function cp(e,t){return!!((t==="v4"||!t)&&tp.test(e)||(t==="v6"||!t)&&rp.test(e))}function up(e,t){if(!qd.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function dp(e,t){return!!((t==="v4"||!t)&&np.test(e)||(t==="v6"||!t)&&op.test(e))}var gt=class e extends U{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==A.string){let s=this._getOrReturnCtx(t);return w(s,{code:E.invalid_type,expected:A.string,received:s.parsedType}),O}let r=new ye,o;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),w(o,{code:E.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),w(o,{code:E.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let i=t.data.length>s.value,a=t.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(t,o),i?w(o,{code:E.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&w(o,{code:E.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Qd.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"email",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Qs||(Qs=new RegExp(ep,"u")),Qs.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"emoji",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")Kd.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"uuid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")Yd.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"nanoid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Wd.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"cuid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")Xd.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"cuid2",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Zd.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"ulid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),w(o,{validation:"url",code:E.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"regex",code:E.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),w(o,{code:E.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),w(o,{code:E.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),w(o,{code:E.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?pl(s).test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{code:E.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?ap.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{code:E.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?lp(s).test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{code:E.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?Jd.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"duration",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?cp(t.data,s.version)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"ip",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?up(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"jwt",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?dp(t.data,s.version)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"cidr",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?sp.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"base64",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?ip.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"base64url",code:E.invalid_string,message:s.message}),r.dirty()):H.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:E.invalid_string,...I.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...I.errToObj(t)})}url(t){return this._addCheck({kind:"url",...I.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...I.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...I.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...I.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...I.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...I.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...I.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...I.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...I.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...I.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...I.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...I.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...I.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...I.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...I.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...I.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...I.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...I.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...I.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...I.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...I.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...I.errToObj(n)})}nonempty(t){return this.min(1,I.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};gt.create=e=>new gt({checks:[],typeName:M.ZodString,coerce:e?.coerce??!1,...L(e)});function pp(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}var kt=class e extends U{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==A.number){let s=this._getOrReturnCtx(t);return w(s,{code:E.invalid_type,expected:A.number,received:s.parsedType}),O}let r,o=new ye;for(let s of this._def.checks)s.kind==="int"?H.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),w(r,{code:E.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),w(r,{code:E.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),w(r,{code:E.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?pp(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),w(r,{code:E.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),w(r,{code:E.not_finite,message:s.message}),o.dirty()):H.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,I.toString(n))}gt(t,n){return this.setLimit("min",t,!1,I.toString(n))}lte(t,n){return this.setLimit("max",t,!0,I.toString(n))}lt(t,n){return this.setLimit("max",t,!1,I.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:I.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:I.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:I.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:I.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:I.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:I.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:I.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:I.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:I.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&H.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};kt.create=e=>new kt({checks:[],typeName:M.ZodNumber,coerce:e?.coerce||!1,...L(e)});var At=class e extends U{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==A.bigint)return this._getInvalidInput(t);let r,o=new ye;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),w(r,{code:E.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),w(r,{code:E.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),w(r,{code:E.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):H.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return w(n,{code:E.invalid_type,expected:A.bigint,received:n.parsedType}),O}gte(t,n){return this.setLimit("min",t,!0,I.toString(n))}gt(t,n){return this.setLimit("min",t,!1,I.toString(n))}lte(t,n){return this.setLimit("max",t,!0,I.toString(n))}lt(t,n){return this.setLimit("max",t,!1,I.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:I.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:I.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:I.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:I.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:I.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};At.create=e=>new At({checks:[],typeName:M.ZodBigInt,coerce:e?.coerce??!1,...L(e)});var It=class extends U{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==A.boolean){let r=this._getOrReturnCtx(t);return w(r,{code:E.invalid_type,expected:A.boolean,received:r.parsedType}),O}return _e(t.data)}};It.create=e=>new It({typeName:M.ZodBoolean,coerce:e?.coerce||!1,...L(e)});var Ct=class e extends U{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==A.date){let s=this._getOrReturnCtx(t);return w(s,{code:E.invalid_type,expected:A.date,received:s.parsedType}),O}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return w(s,{code:E.invalid_date}),O}let r=new ye,o;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),w(o,{code:E.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),w(o,{code:E.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):H.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:I.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:I.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};Ct.create=e=>new Ct({checks:[],coerce:e?.coerce||!1,typeName:M.ZodDate,...L(e)});var dn=class extends U{_parse(t){if(this._getType(t)!==A.symbol){let r=this._getOrReturnCtx(t);return w(r,{code:E.invalid_type,expected:A.symbol,received:r.parsedType}),O}return _e(t.data)}};dn.create=e=>new dn({typeName:M.ZodSymbol,...L(e)});var Nt=class extends U{_parse(t){if(this._getType(t)!==A.undefined){let r=this._getOrReturnCtx(t);return w(r,{code:E.invalid_type,expected:A.undefined,received:r.parsedType}),O}return _e(t.data)}};Nt.create=e=>new Nt({typeName:M.ZodUndefined,...L(e)});var Rt=class extends U{_parse(t){if(this._getType(t)!==A.null){let r=this._getOrReturnCtx(t);return w(r,{code:E.invalid_type,expected:A.null,received:r.parsedType}),O}return _e(t.data)}};Rt.create=e=>new Rt({typeName:M.ZodNull,...L(e)});var vt=class extends U{constructor(){super(...arguments),this._any=!0}_parse(t){return _e(t.data)}};vt.create=e=>new vt({typeName:M.ZodAny,...L(e)});var at=class extends U{constructor(){super(...arguments),this._unknown=!0}_parse(t){return _e(t.data)}};at.create=e=>new at({typeName:M.ZodUnknown,...L(e)});var Fe=class extends U{_parse(t){let n=this._getOrReturnCtx(t);return w(n,{code:E.invalid_type,expected:A.never,received:n.parsedType}),O}};Fe.create=e=>new Fe({typeName:M.ZodNever,...L(e)});var pn=class extends U{_parse(t){if(this._getType(t)!==A.undefined){let r=this._getOrReturnCtx(t);return w(r,{code:E.invalid_type,expected:A.void,received:r.parsedType}),O}return _e(t.data)}};pn.create=e=>new pn({typeName:M.ZodVoid,...L(e)});var lt=class e extends U{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==A.array)return w(n,{code:E.invalid_type,expected:A.array,received:n.parsedType}),O;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(w(n,{code:i?E.too_big:E.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(w(n,{code:E.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(w(n,{code:E.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new Oe(n,i,n.path,a)))).then(i=>ye.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new Oe(n,i,n.path,a)));return ye.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:I.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:I.toString(n)}})}nonempty(t){return this.min(1,t)}};lt.create=(e,t)=>new lt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...L(t)});function un(e){if(e instanceof ke){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Re.create(un(r))}return new ke({...e._def,shape:()=>t})}else return e instanceof lt?new lt({...e._def,type:un(e.element)}):e instanceof Re?Re.create(un(e.unwrap())):e instanceof et?et.create(un(e.unwrap())):e instanceof Qe?Qe.create(e.items.map(t=>un(t))):e}var ke=class e extends U{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=H.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==A.object){let c=this._getOrReturnCtx(t);return w(c,{code:E.invalid_type,expected:A.object,received:c.parsedType}),O}let{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Fe&&this._def.unknownKeys==="strip"))for(let c in o.data)i.includes(c)||a.push(c);let u=[];for(let c of i){let p=s[c],m=o.data[c];u.push({key:{status:"valid",value:c},value:p._parse(new Oe(o,m,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Fe){let c=this._def.unknownKeys;if(c==="passthrough")for(let p of a)u.push({key:{status:"valid",value:p},value:{status:"valid",value:o.data[p]}});else if(c==="strict")a.length>0&&(w(o,{code:E.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let p of a){let m=o.data[p];u.push({key:{status:"valid",value:p},value:c._parse(new Oe(o,m,o.path,p)),alwaysSet:p in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let c=[];for(let p of u){let m=await p.key,x=await p.value;c.push({key:m,value:x,alwaysSet:p.alwaysSet})}return c}).then(c=>ye.mergeObjectSync(r,c)):ye.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return I.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:I.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:M.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of H.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let r of H.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return un(this)}partial(t){let n={};for(let r of H.objectKeys(this.shape)){let o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of H.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Re;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:()=>n})}keyof(){return fl(H.objectKeys(this.shape))}};ke.create=(e,t)=>new ke({shape:()=>e,unknownKeys:"strip",catchall:Fe.create(),typeName:M.ZodObject,...L(t)});ke.strictCreate=(e,t)=>new ke({shape:()=>e,unknownKeys:"strict",catchall:Fe.create(),typeName:M.ZodObject,...L(t)});ke.lazycreate=(e,t)=>new ke({shape:e,unknownKeys:"strip",catchall:Fe.create(),typeName:M.ZodObject,...L(t)});var Ot=class extends U{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new we(a.ctx.common.issues));return w(n,{code:E.invalid_union,unionErrors:i}),O}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let u of r){let c={...n,common:{...n.common,issues:[]},parent:null},p=u._parseSync({data:n.data,path:n.path,parent:c});if(p.status==="valid")return p;p.status==="dirty"&&!s&&(s={result:p,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(u=>new we(u));return w(n,{code:E.invalid_union,unionErrors:a}),O}}get options(){return this._def.options}};Ot.create=(e,t)=>new Ot({options:e,typeName:M.ZodUnion,...L(t)});var it=e=>e instanceof Lt?it(e.schema):e instanceof Me?it(e.innerType()):e instanceof Pt?[e.value]:e instanceof Dt?e.options:e instanceof Ut?H.objectValues(e.enum):e instanceof Gt?it(e._def.innerType):e instanceof Nt?[void 0]:e instanceof Rt?[null]:e instanceof Re?[void 0,...it(e.unwrap())]:e instanceof et?[null,...it(e.unwrap())]:e instanceof $n||e instanceof Ht?it(e.unwrap()):e instanceof Ft?it(e._def.innerType):[],Ir=class e extends U{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.object)return w(n,{code:E.invalid_type,expected:A.object,received:n.parsedType}),O;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(w(n,{code:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),O)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let o=new Map;for(let s of n){let i=it(s.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);o.set(a,s)}}return new e({typeName:M.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...L(r)})}};function ei(e,t){let n=Je(e),r=Je(t);if(e===t)return{valid:!0,data:e};if(n===A.object&&r===A.object){let o=H.objectKeys(t),s=H.objectKeys(e).filter(a=>o.indexOf(a)!==-1),i={...e,...t};for(let a of s){let u=ei(e[a],t[a]);if(!u.valid)return{valid:!1};i[a]=u.data}return{valid:!0,data:i}}else if(n===A.array&&r===A.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let s=0;s<e.length;s++){let i=e[s],a=t[s],u=ei(i,a);if(!u.valid)return{valid:!1};o.push(u.data)}return{valid:!0,data:o}}else return n===A.date&&r===A.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Mt=class extends U{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=(s,i)=>{if(kr(s)||kr(i))return O;let a=ei(s.value,i.value);return a.valid?((Ar(s)||Ar(i))&&n.dirty(),{status:n.value,value:a.data}):(w(r,{code:E.invalid_intersection_types}),O)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Mt.create=(e,t,n)=>new Mt({left:e,right:t,typeName:M.ZodIntersection,...L(n)});var Qe=class e extends U{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.array)return w(r,{code:E.invalid_type,expected:A.array,received:r.parsedType}),O;if(r.data.length<this._def.items.length)return w(r,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),O;!this._def.rest&&r.data.length>this._def.items.length&&(w(r,{code:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new Oe(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>ye.mergeArray(n,i)):ye.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Qe.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Qe({items:e,typeName:M.ZodTuple,rest:null,...L(t)})};var Cr=class e extends U{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.object)return w(r,{code:E.invalid_type,expected:A.object,received:r.parsedType}),O;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new Oe(r,a,r.path,a)),value:i._parse(new Oe(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ye.mergeObjectAsync(n,o):ye.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof U?new e({keyType:t,valueType:n,typeName:M.ZodRecord,...L(r)}):new e({keyType:gt.create(),valueType:t,typeName:M.ZodRecord,...L(n)})}},fn=class extends U{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.map)return w(r,{code:E.invalid_type,expected:A.map,received:r.parsedType}),O;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,u],c)=>({key:o._parse(new Oe(r,a,r.path,[c,"key"])),value:s._parse(new Oe(r,u,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let u of i){let c=await u.key,p=await u.value;if(c.status==="aborted"||p.status==="aborted")return O;(c.status==="dirty"||p.status==="dirty")&&n.dirty(),a.set(c.value,p.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let u of i){let c=u.key,p=u.value;if(c.status==="aborted"||p.status==="aborted")return O;(c.status==="dirty"||p.status==="dirty")&&n.dirty(),a.set(c.value,p.value)}return{status:n.value,value:a}}}};fn.create=(e,t,n)=>new fn({valueType:t,keyType:e,typeName:M.ZodMap,...L(n)});var hn=class e extends U{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.set)return w(r,{code:E.invalid_type,expected:A.set,received:r.parsedType}),O;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(w(r,{code:E.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(w(r,{code:E.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(u){let c=new Set;for(let p of u){if(p.status==="aborted")return O;p.status==="dirty"&&n.dirty(),c.add(p.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((u,c)=>s._parse(new Oe(r,u,r.path,c)));return r.common.async?Promise.all(a).then(u=>i(u)):i(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:I.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};hn.create=(e,t)=>new hn({valueType:e,minSize:null,maxSize:null,typeName:M.ZodSet,...L(t)});var Nr=class e extends U{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.function)return w(n,{code:E.invalid_type,expected:A.function,received:n.parsedType}),O;function r(a,u){return Hn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ln(),st].filter(c=>!!c),issueData:{code:E.invalid_arguments,argumentsError:u}})}function o(a,u){return Hn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ln(),st].filter(c=>!!c),issueData:{code:E.invalid_return_type,returnTypeError:u}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof yt){let a=this;return _e(async function(...u){let c=new we([]),p=await a._def.args.parseAsync(u,s).catch(f=>{throw c.addIssue(r(u,f)),c}),m=await Reflect.apply(i,this,p);return await a._def.returns._def.type.parseAsync(m,s).catch(f=>{throw c.addIssue(o(m,f)),c})})}else{let a=this;return _e(function(...u){let c=a._def.args.safeParse(u,s);if(!c.success)throw new we([r(u,c.error)]);let p=Reflect.apply(i,this,c.data),m=a._def.returns.safeParse(p,s);if(!m.success)throw new we([o(p,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Qe.create(t).rest(at.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||Qe.create([]).rest(at.create()),returns:n||at.create(),typeName:M.ZodFunction,...L(r)})}},Lt=class extends U{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Lt.create=(e,t)=>new Lt({getter:e,typeName:M.ZodLazy,...L(t)});var Pt=class extends U{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return w(n,{received:n.data,code:E.invalid_literal,expected:this._def.value}),O}return{status:"valid",value:t.data}}get value(){return this._def.value}};Pt.create=(e,t)=>new Pt({value:e,typeName:M.ZodLiteral,...L(t)});function fl(e,t){return new Dt({values:e,typeName:M.ZodEnum,...L(t)})}var Dt=class e extends U{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return w(n,{expected:H.joinValues(r),received:n.parsedType,code:E.invalid_type}),O}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return w(n,{received:n.data,code:E.invalid_enum_value,options:r}),O}return _e(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};Dt.create=fl;var Ut=class extends U{_parse(t){let n=H.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==A.string&&r.parsedType!==A.number){let o=H.objectValues(n);return w(r,{expected:H.joinValues(o),received:r.parsedType,code:E.invalid_type}),O}if(this._cache||(this._cache=new Set(H.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=H.objectValues(n);return w(r,{received:r.data,code:E.invalid_enum_value,options:o}),O}return _e(t.data)}get enum(){return this._def.values}};Ut.create=(e,t)=>new Ut({values:e,typeName:M.ZodNativeEnum,...L(t)});var yt=class extends U{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.promise&&n.common.async===!1)return w(n,{code:E.invalid_type,expected:A.promise,received:n.parsedType}),O;let r=n.parsedType===A.promise?n.data:Promise.resolve(n.data);return _e(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};yt.create=(e,t)=>new yt({type:e,typeName:M.ZodPromise,...L(t)});var Me=class extends U{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:i=>{w(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return O;let u=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return u.status==="aborted"?O:u.status==="dirty"?wt(u.value):n.value==="dirty"?wt(u.value):u});{if(n.value==="aborted")return O;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?O:a.status==="dirty"?wt(a.value):n.value==="dirty"?wt(a.value):a}}if(o.type==="refinement"){let i=a=>{let u=o.refinement(a,s);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?O:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?O:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!mt(i))return O;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>mt(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):O);H.assertNever(o)}};Me.create=(e,t,n)=>new Me({schema:e,typeName:M.ZodEffects,effect:t,...L(n)});Me.createWithPreprocess=(e,t,n)=>new Me({schema:t,effect:{type:"preprocess",transform:e},typeName:M.ZodEffects,...L(n)});var Re=class extends U{_parse(t){return this._getType(t)===A.undefined?_e(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Re.create=(e,t)=>new Re({innerType:e,typeName:M.ZodOptional,...L(t)});var et=class extends U{_parse(t){return this._getType(t)===A.null?_e(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};et.create=(e,t)=>new et({innerType:e,typeName:M.ZodNullable,...L(t)});var Gt=class extends U{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===A.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Gt.create=(e,t)=>new Gt({innerType:e,typeName:M.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...L(t)});var Ft=class extends U{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return cn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new we(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new we(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Ft.create=(e,t)=>new Ft({innerType:e,typeName:M.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...L(t)});var mn=class extends U{_parse(t){if(this._getType(t)!==A.nan){let r=this._getOrReturnCtx(t);return w(r,{code:E.invalid_type,expected:A.nan,received:r.parsedType}),O}return{status:"valid",value:t.data}}};mn.create=e=>new mn({typeName:M.ZodNaN,...L(e)});var fp=Symbol("zod_brand"),$n=class extends U{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},zn=class e extends U{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?O:s.status==="dirty"?(n.dirty(),wt(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?O:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:M.ZodPipeline})}},Ht=class extends U{_parse(t){let n=this._def.innerType._parse(t),r=o=>(mt(o)&&(o.value=Object.freeze(o.value)),o);return cn(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Ht.create=(e,t)=>new Ht({innerType:e,typeName:M.ZodReadonly,...L(t)});function cl(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function hl(e,t={},n){return e?vt.create().superRefine((r,o)=>{let s=e(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=cl(t,r),u=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:u})}});if(!s){let i=cl(t,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):vt.create()}var hp={object:ke.lazycreate},M;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(M||(M={}));var mp=(e,t={message:`Input not instance of ${e.name}`})=>hl(n=>n instanceof e,t),ml=gt.create,gl=kt.create,gp=mn.create,vp=At.create,vl=It.create,yp=Ct.create,bp=dn.create,xp=Nt.create,Ep=Rt.create,_p=vt.create,Tp=at.create,Sp=Fe.create,wp=pn.create,kp=lt.create,Ap=ke.create,Ip=ke.strictCreate,Cp=Ot.create,Np=Ir.create,Rp=Mt.create,Op=Qe.create,Mp=Cr.create,Lp=fn.create,Pp=hn.create,Dp=Nr.create,Up=Lt.create,Gp=Pt.create,Fp=Dt.create,Hp=Ut.create,$p=yt.create,zp=Me.create,Bp=Re.create,Vp=et.create,jp=Me.createWithPreprocess,Wp=zn.create,Xp=()=>ml().optional(),Zp=()=>gl().optional(),Kp=()=>vl().optional(),Yp={string:(e=>gt.create({...e,coerce:!0})),number:(e=>kt.create({...e,coerce:!0})),boolean:(e=>It.create({...e,coerce:!0})),bigint:(e=>At.create({...e,coerce:!0})),date:(e=>Ct.create({...e,coerce:!0}))};var qp=O;var Jp=l.object({name:l.string(),arguments:l.string()}),Qp=l.object({id:l.string(),type:l.literal("function"),function:Jp,encryptedValue:l.string().optional()}),Rr=l.object({id:l.string(),role:l.string(),content:l.string().optional(),name:l.string().optional(),encryptedValue:l.string().optional()}),ef=l.object({type:l.literal("text"),text:l.string()}),tf=l.object({type:l.literal("data"),value:l.string(),mimeType:l.string()}),nf=l.object({type:l.literal("url"),value:l.string(),mimeType:l.string().optional()}),Or=l.discriminatedUnion("type",[tf,nf]),rf=l.object({type:l.literal("image"),source:Or,metadata:l.unknown().optional()}),of=l.object({type:l.literal("audio"),source:Or,metadata:l.unknown().optional()}),sf=l.object({type:l.literal("video"),source:Or,metadata:l.unknown().optional()}),af=l.object({type:l.literal("document"),source:Or,metadata:l.unknown().optional()});var yl=l.object({type:l.literal("binary"),mimeType:l.string(),id:l.string().optional(),url:l.string().optional(),data:l.string().optional(),filename:l.string().optional()}),bl=(e,t)=>{!e.id&&!e.url&&!e.data&&t.addIssue({code:l.ZodIssueCode.custom,message:"BinaryInputContent requires at least one of id, url, or data.",path:["id"]})},xv=yl.superRefine((e,t)=>{bl(e,t)}),lf=l.discriminatedUnion("type",[ef,rf,of,sf,af,yl]),cf=lf.superRefine((e,t)=>{e.type==="binary"&&bl(e,t)}),uf=Rr.extend({role:l.literal("developer"),content:l.string()}),df=Rr.extend({role:l.literal("system"),content:l.string()}),pf=Rr.extend({role:l.literal("assistant"),content:l.string().optional(),toolCalls:l.array(Qp).optional()}),ff=Rr.extend({role:l.literal("user"),content:l.union([l.string(),l.array(cf)])}),hf=l.object({id:l.string(),content:l.string(),role:l.literal("tool"),toolCallId:l.string(),error:l.string().optional(),encryptedValue:l.string().optional()}),mf=l.object({id:l.string(),role:l.literal("activity"),activityType:l.string(),content:l.record(l.any())}),gf=l.object({id:l.string(),role:l.literal("reasoning"),content:l.string(),encryptedValue:l.string().optional()}),xl=l.discriminatedUnion("role",[uf,df,pf,ff,hf,mf,gf]),Ev=l.union([l.literal("developer"),l.literal("system"),l.literal("assistant"),l.literal("user"),l.literal("tool"),l.literal("activity"),l.literal("reasoning")]),vf=l.object({description:l.string(),value:l.string()}),El=l.object({name:l.string(),description:l.string(),parameters:l.any(),metadata:l.record(l.any()).optional()}),yf=l.object({id:l.string(),reason:l.string(),message:l.string().optional(),toolCallId:l.string().optional(),responseSchema:l.record(l.any()).optional(),expiresAt:l.string().optional(),metadata:l.record(l.any()).optional()}),bf=l.object({interruptId:l.string(),status:l.enum(["resolved","cancelled"]),payload:l.any().optional()}),xf=l.object({threadId:l.string(),runId:l.string(),parentRunId:l.string().optional(),state:l.any(),messages:l.array(xl),tools:l.array(El),context:l.array(vf),forwardedProps:l.any(),resume:l.array(bf).optional()}),Ef=l.any(),q=class extends Error{constructor(e){super(e)}},ti=class extends q{constructor(){super("Connect not implemented. This method is not supported by the current agent.")}},_f=l.object({name:l.string(),description:l.string().optional()}),Tf=l.object({name:l.string().optional(),type:l.string().optional(),description:l.string().optional(),version:l.string().optional(),provider:l.string().optional(),documentationUrl:l.string().optional(),metadata:l.record(l.unknown()).optional()}),Sf=l.object({streaming:l.boolean().optional(),websocket:l.boolean().optional(),httpBinary:l.boolean().optional(),pushNotifications:l.boolean().optional(),resumable:l.boolean().optional()}),wf=l.object({supported:l.boolean().optional(),items:l.array(El).optional(),parallelCalls:l.boolean().optional(),clientProvided:l.boolean().optional()}),kf=l.object({structuredOutput:l.boolean().optional(),supportedMimeTypes:l.array(l.string()).optional()}),Af=l.object({snapshots:l.boolean().optional(),deltas:l.boolean().optional(),memory:l.boolean().optional(),persistentState:l.boolean().optional()}),If=l.object({supported:l.boolean().optional(),delegation:l.boolean().optional(),handoffs:l.boolean().optional(),subAgents:l.array(_f).optional()}),Cf=l.object({supported:l.boolean().optional(),streaming:l.boolean().optional(),encrypted:l.boolean().optional()}),Nf=l.object({image:l.boolean().optional(),audio:l.boolean().optional(),video:l.boolean().optional(),pdf:l.boolean().optional(),file:l.boolean().optional()}),Rf=l.object({image:l.boolean().optional(),audio:l.boolean().optional()}),Of=l.object({input:Nf.optional(),output:Rf.optional()}),Mf=l.object({codeExecution:l.boolean().optional(),sandboxed:l.boolean().optional(),maxIterations:l.number().optional(),maxExecutionTime:l.number().optional()}),Lf=l.object({supported:l.boolean().optional(),approvals:l.boolean().optional(),interventions:l.boolean().optional(),feedback:l.boolean().optional(),interrupts:l.boolean().optional(),approveWithEdits:l.boolean().optional()}),_v=l.object({identity:Tf.optional(),transport:Sf.optional(),tools:wf.optional(),output:kf.optional(),state:Af.optional(),multiAgent:If.optional(),reasoning:Cf.optional(),multimodal:Of.optional(),execution:Mf.optional(),humanInTheLoop:Lf.optional(),custom:l.record(l.unknown()).optional()}),_l=l.union([l.literal("developer"),l.literal("system"),l.literal("assistant"),l.literal("user")]),v=(function(e){return e.TEXT_MESSAGE_START="TEXT_MESSAGE_START",e.TEXT_MESSAGE_CONTENT="TEXT_MESSAGE_CONTENT",e.TEXT_MESSAGE_END="TEXT_MESSAGE_END",e.TEXT_MESSAGE_CHUNK="TEXT_MESSAGE_CHUNK",e.TOOL_CALL_START="TOOL_CALL_START",e.TOOL_CALL_ARGS="TOOL_CALL_ARGS",e.TOOL_CALL_END="TOOL_CALL_END",e.TOOL_CALL_CHUNK="TOOL_CALL_CHUNK",e.TOOL_CALL_RESULT="TOOL_CALL_RESULT",e.THINKING_START="THINKING_START",e.THINKING_END="THINKING_END",e.THINKING_TEXT_MESSAGE_START="THINKING_TEXT_MESSAGE_START",e.THINKING_TEXT_MESSAGE_CONTENT="THINKING_TEXT_MESSAGE_CONTENT",e.THINKING_TEXT_MESSAGE_END="THINKING_TEXT_MESSAGE_END",e.STATE_SNAPSHOT="STATE_SNAPSHOT",e.STATE_DELTA="STATE_DELTA",e.MESSAGES_SNAPSHOT="MESSAGES_SNAPSHOT",e.ACTIVITY_SNAPSHOT="ACTIVITY_SNAPSHOT",e.ACTIVITY_DELTA="ACTIVITY_DELTA",e.RAW="RAW",e.CUSTOM="CUSTOM",e.RUN_STARTED="RUN_STARTED",e.RUN_FINISHED="RUN_FINISHED",e.RUN_ERROR="RUN_ERROR",e.STEP_STARTED="STEP_STARTED",e.STEP_FINISHED="STEP_FINISHED",e.REASONING_START="REASONING_START",e.REASONING_MESSAGE_START="REASONING_MESSAGE_START",e.REASONING_MESSAGE_CONTENT="REASONING_MESSAGE_CONTENT",e.REASONING_MESSAGE_END="REASONING_MESSAGE_END",e.REASONING_MESSAGE_CHUNK="REASONING_MESSAGE_CHUNK",e.REASONING_END="REASONING_END",e.REASONING_ENCRYPTED_VALUE="REASONING_ENCRYPTED_VALUE",e})({}),V=l.object({type:l.nativeEnum(v),timestamp:l.number().optional(),rawEvent:l.any().optional()}).passthrough(),Pf=V.extend({type:l.literal(v.TEXT_MESSAGE_START),messageId:l.string(),role:_l.default("assistant"),name:l.string().optional()}),Tl=V.extend({type:l.literal(v.TEXT_MESSAGE_CONTENT),messageId:l.string(),delta:l.string()}),Df=V.extend({type:l.literal(v.TEXT_MESSAGE_END),messageId:l.string()}),Uf=V.extend({type:l.literal(v.TEXT_MESSAGE_CHUNK),messageId:l.string().optional(),role:_l.optional(),delta:l.string().optional(),name:l.string().optional()}),Gf=V.extend({type:l.literal(v.THINKING_TEXT_MESSAGE_START)}),Ff=Tl.omit({messageId:!0,type:!0}).extend({type:l.literal(v.THINKING_TEXT_MESSAGE_CONTENT)}),Hf=V.extend({type:l.literal(v.THINKING_TEXT_MESSAGE_END)}),$f=V.extend({type:l.literal(v.TOOL_CALL_START),toolCallId:l.string(),toolCallName:l.string(),parentMessageId:l.string().optional()}),zf=V.extend({type:l.literal(v.TOOL_CALL_ARGS),toolCallId:l.string(),delta:l.string()}),Bf=V.extend({type:l.literal(v.TOOL_CALL_END),toolCallId:l.string()}),Vf=V.extend({messageId:l.string(),type:l.literal(v.TOOL_CALL_RESULT),toolCallId:l.string(),content:l.string(),role:l.literal("tool").optional()}),jf=V.extend({type:l.literal(v.TOOL_CALL_CHUNK),toolCallId:l.string().optional(),toolCallName:l.string().optional(),parentMessageId:l.string().optional(),delta:l.string().optional()}),Wf=V.extend({type:l.literal(v.THINKING_START),title:l.string().optional()}),Xf=V.extend({type:l.literal(v.THINKING_END)}),Zf=V.extend({type:l.literal(v.STATE_SNAPSHOT),snapshot:Ef}),Kf=V.extend({type:l.literal(v.STATE_DELTA),delta:l.array(l.any())}),Yf=V.extend({type:l.literal(v.MESSAGES_SNAPSHOT),messages:l.array(xl)}),qf=V.extend({type:l.literal(v.ACTIVITY_SNAPSHOT),messageId:l.string(),activityType:l.string(),content:l.record(l.any()),replace:l.boolean().optional().default(!0)}),Jf=V.extend({type:l.literal(v.ACTIVITY_DELTA),messageId:l.string(),activityType:l.string(),patch:l.array(l.any())}),Qf=V.extend({type:l.literal(v.RAW),event:l.any(),source:l.string().optional()}),eh=V.extend({type:l.literal(v.CUSTOM),name:l.string(),value:l.any()}),th=V.extend({type:l.literal(v.RUN_STARTED),threadId:l.string(),runId:l.string(),parentRunId:l.string().optional(),input:xf.optional()}),nh=l.object({type:l.literal("success")}).strict(),rh=l.object({type:l.literal("interrupt"),interrupts:l.array(yf).min(1)}).strict(),oh=l.discriminatedUnion("type",[nh,rh]),sh=V.extend({type:l.literal(v.RUN_FINISHED),threadId:l.string(),runId:l.string(),result:l.any().optional(),outcome:oh.nullable().optional().transform(e=>e??void 0)}),ih=V.extend({type:l.literal(v.RUN_ERROR),message:l.string(),code:l.string().optional()}),ah=V.extend({type:l.literal(v.STEP_STARTED),stepName:l.string()}),lh=V.extend({type:l.literal(v.STEP_FINISHED),stepName:l.string()}),ch=l.union([l.literal("tool-call"),l.literal("message")]),uh=V.extend({type:l.literal(v.REASONING_START),messageId:l.string()}),dh=V.extend({type:l.literal(v.REASONING_MESSAGE_START),messageId:l.string(),role:l.literal("reasoning")}),ph=V.extend({type:l.literal(v.REASONING_MESSAGE_CONTENT),messageId:l.string(),delta:l.string()}),fh=V.extend({type:l.literal(v.REASONING_MESSAGE_END),messageId:l.string()}),hh=V.extend({type:l.literal(v.REASONING_MESSAGE_CHUNK),messageId:l.string().optional(),delta:l.string().optional()}),mh=V.extend({type:l.literal(v.REASONING_END),messageId:l.string()}),gh=V.extend({type:l.literal(v.REASONING_ENCRYPTED_VALUE),subtype:ch,entityId:l.string(),encryptedValue:l.string()}),Mr=l.discriminatedUnion("type",[Pf,Tl,Df,Uf,Wf,Xf,Gf,Ff,Hf,$f,zf,Bf,jf,Vf,Zf,Kf,Yf,qf,Jf,Qf,eh,th,sh,ih,ah,lh,uh,dh,ph,fh,hh,mh,gh]);var ni={};ms(ni,{JsonPatchError:()=>re,_areEquals:()=>jn,applyOperation:()=>$t,applyPatch:()=>Hr,applyReducer:()=>Eh,deepClone:()=>bh,getValueByPointer:()=>Gr,validate:()=>wl,validator:()=>Fr});var vh=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var s in o)o.hasOwnProperty(s)&&(r[s]=o[s])},e(t,n)};return function(t,n){e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),yh=Object.prototype.hasOwnProperty;function Pr(e,t){return yh.call(e,t)}function Dr(e){if(Array.isArray(e)){for(var t=new Array(e.length),n=0;n<t.length;n++)t[n]=""+n;return t}if(Object.keys)return Object.keys(e);var r=[];for(var o in e)Pr(e,o)&&r.push(o);return r}function be(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function Ur(e){for(var t=0,n=e.length,r;t<n;){if(r=e.charCodeAt(t),r>=48&&r<=57){t++;continue}return!1}return!0}function tt(e){return e.indexOf("/")===-1&&e.indexOf("~")===-1?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function Bn(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Lr(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(var t=0,n=e.length;t<n;t++)if(Lr(e[t]))return!0}else if(typeof e=="object"){for(var r=Dr(e),o=r.length,s=0;s<o;s++)if(Lr(e[r[s]]))return!0}}return!1}function Sl(e,t){var n=[e];for(var r in t){var o=typeof t[r]=="object"?JSON.stringify(t[r],null,2):t[r];typeof o<"u"&&n.push(r+": "+o)}return n.join(`
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(`
698
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:
699
712
  `+n.map(function(r,o){return o+1+") "+r.toString()}).join(`
700
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
@@ -704,7 +717,7 @@ Patch operations: ${JSON.stringify(h,null,2)}
704
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(`
705
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(`
706
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(`
707
- `)},km=(e,t,n)=>r=>{let o={},s=!0,i=!0,a="",u=null,c=null,p=[],m={},x=f=>{typeof f=="object"&&f&&("messages"in f&&delete f.messages,o=f)};return r.pipe(Ae(f=>{switch(f.type){case v.TEXT_MESSAGE_START:{let h=f;return[{type:K.enum.TextMessageStart,messageId:h.messageId,role:h.role}]}case v.TEXT_MESSAGE_CONTENT:{let h=f;return[{type:K.enum.TextMessageContent,messageId:h.messageId,content:h.delta}]}case v.TEXT_MESSAGE_END:{let h=f;return[{type:K.enum.TextMessageEnd,messageId:h.messageId}]}case v.TOOL_CALL_START:{let h=f;return p.push({id:h.toolCallId,type:"function",function:{name:h.toolCallName,arguments:""}}),i=!0,m[h.toolCallId]=h.toolCallName,[{type:K.enum.ActionExecutionStart,actionExecutionId:h.toolCallId,actionName:h.toolCallName,parentMessageId:h.parentMessageId}]}case v.TOOL_CALL_ARGS:{let h=f,g=p.find(S=>S.id===h.toolCallId);if(!g)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${h.toolCallId}'`),[];g.function.arguments+=h.delta;let _=!1;if(c){let S=c.find(b=>b.tool==g.function.name);if(S)try{let b=JSON.parse(ho(g.function.arguments));S.tool_argument&&S.tool_argument in b?(x({...o,[S.state_key]:b[S.tool_argument]}),_=!0):S.tool_argument||(x({...o,[S.state_key]:b}),_=!0)}catch{}}return[{type:K.enum.ActionExecutionArgs,actionExecutionId:h.toolCallId,args:h.delta},..._?[{type:K.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:a,runId:t,running:s,role:"assistant",state:JSON.stringify(o),active:i}]:[]]}case v.TOOL_CALL_END:{let h=f;return[{type:K.enum.ActionExecutionEnd,actionExecutionId:h.toolCallId}]}case v.TOOL_CALL_RESULT:{let h=f;return[{type:K.enum.ActionExecutionResult,actionExecutionId:h.toolCallId,result:h.content,actionName:m[h.toolCallId]||"unknown"}]}case v.RAW:return[];case v.CUSTOM:{let h=f;switch(h.name){case"Exit":s=!1;break;case"PredictState":c=h.value;break}return[{type:K.enum.MetaEvent,name:h.name,value:h.value}]}case v.STATE_SNAPSHOT:return x(f.snapshot),[{type:K.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:a,runId:t,running:s,role:"assistant",state:JSON.stringify(o),active:i}];case v.STATE_DELTA:{let h=f,g=$r.applyPatch(o,h.delta,!0,!1);return g?(x(g.newDocument),[{type:K.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:a,runId:t,running:s,role:"assistant",state:JSON.stringify(o),active:i}]):[]}case v.MESSAGES_SNAPSHOT:return u=f.messages,[{type:K.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:a,runId:t,running:s,role:"assistant",state:JSON.stringify({...o,...u?{messages:u}:{}}),active:!0}];case v.RUN_STARTED:return[];case v.RUN_FINISHED:return u&&(o.messages=u),Object.keys(o).length===0?[]:[{type:K.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:a,runId:t,running:s,role:"assistant",state:JSON.stringify({...o,...u?{messages:Am(u)}:{}}),active:!1}];case v.RUN_ERROR:{let h=f;return[{type:K.enum.RunError,message:h.message,code:h.code}]}case v.STEP_STARTED:return a=f.stepName,p=[],c=null,[{type:K.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:a,runId:t,running:s,role:"assistant",state:JSON.stringify(o),active:!0}];case v.STEP_FINISHED:return p=[],c=null,[{type:K.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:a,runId:t,running:s,role:"assistant",state:JSON.stringify(o),active:!1}];default:return[]}}))};function Am(e){let t=[];for(let n of e)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let r=wm(n.content);if(r){let o={id:n.id,role:n.role,content:r};t.push(o)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let o of n.toolCalls){let s={id:o.id,name:o.function.name,arguments:JSON.parse(o.function.arguments),parentMessageId:n.id};t.push(s)}}else if(n.role==="tool"){let r="unknown";for(let s of e)if(s.role==="assistant"&&s.toolCalls?.length){for(let i of s.toolCalls)if(i.id===n.toolCallId){r=i.function.name;break}}let o={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:r};t.push(o)}return t}var Yo=e=>t=>{let n=Qn(e),r,o,s,i,a=()=>{if(!r||i!=="text")throw Error("No text message to close");let m={type:v.TEXT_MESSAGE_END,messageId:r.messageId};return i=void 0,r=void 0,n?.event("TRANSFORM","TEXT_MESSAGE_END",m,{messageId:m.messageId}),m},u=()=>{if(!o||i!=="tool")throw Error("No tool call to close");let m={type:v.TOOL_CALL_END,toolCallId:o.toolCallId};return i=void 0,o=void 0,n?.event("TRANSFORM","TOOL_CALL_END",m,{toolCallId:m.toolCallId}),m},c=()=>{if(!s||i!=="reasoning")throw Error("No reasoning message to close");let m={type:v.REASONING_MESSAGE_END,messageId:s.messageId};return i=void 0,s=void 0,n?.event("TRANSFORM","REASONING_MESSAGE_END",m,{messageId:m.messageId}),m},p=()=>i==="text"?[a()]:i==="tool"?[u()]:i==="reasoning"?[c()]:[];return t.pipe(Ae(m=>{switch(m.type){case v.TEXT_MESSAGE_START:case v.TEXT_MESSAGE_CONTENT:case v.TEXT_MESSAGE_END:case v.TOOL_CALL_START:case v.TOOL_CALL_ARGS:case v.TOOL_CALL_END:case v.TOOL_CALL_RESULT:case v.STATE_SNAPSHOT:case v.STATE_DELTA:case v.MESSAGES_SNAPSHOT:case v.CUSTOM:case v.RUN_STARTED:case v.RUN_FINISHED:case v.RUN_ERROR:case v.STEP_STARTED:case v.STEP_FINISHED:case v.THINKING_START:case v.THINKING_END:case v.THINKING_TEXT_MESSAGE_START:case v.THINKING_TEXT_MESSAGE_CONTENT:case v.THINKING_TEXT_MESSAGE_END:case v.REASONING_START:case v.REASONING_MESSAGE_START:case v.REASONING_MESSAGE_CONTENT:case v.REASONING_MESSAGE_END:case v.REASONING_END:return[...p(),m];case v.RAW:case v.ACTIVITY_SNAPSHOT:case v.ACTIVITY_DELTA:case v.REASONING_ENCRYPTED_VALUE:return[m];case v.TEXT_MESSAGE_CHUNK:let x=m,f=[];if((i!=="text"||x.messageId!==void 0&&x.messageId!==r?.messageId)&&f.push(...p()),i!=="text"){if(x.messageId===void 0)throw Error("First TEXT_MESSAGE_CHUNK must have a messageId");r={messageId:x.messageId,name:x.name},i="text";let b={type:v.TEXT_MESSAGE_START,messageId:x.messageId,role:x.role||"assistant",...x.name!==void 0&&{name:x.name}};f.push(b),n?.event("TRANSFORM","TEXT_MESSAGE_START",b,{messageId:x.messageId})}if(x.delta!==void 0){let b={type:v.TEXT_MESSAGE_CONTENT,messageId:r.messageId,delta:x.delta};f.push(b),n?.event("TRANSFORM","TEXT_MESSAGE_CONTENT",b,{messageId:r.messageId})}return f;case v.TOOL_CALL_CHUNK:let h=m,g=[];if((i!=="tool"||h.toolCallId!==void 0&&h.toolCallId!==o?.toolCallId)&&g.push(...p()),i!=="tool"){if(h.toolCallId===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallId");if(h.toolCallName===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallName");o={toolCallId:h.toolCallId,toolCallName:h.toolCallName,parentMessageId:h.parentMessageId},i="tool";let b={type:v.TOOL_CALL_START,toolCallId:h.toolCallId,toolCallName:h.toolCallName,parentMessageId:h.parentMessageId};g.push(b),n?.event("TRANSFORM","TOOL_CALL_START",b,{toolCallId:h.toolCallId,toolCallName:h.toolCallName})}if(h.delta!==void 0){let b={type:v.TOOL_CALL_ARGS,toolCallId:o.toolCallId,delta:h.delta};g.push(b),n?.event("TRANSFORM","TOOL_CALL_ARGS",b,{toolCallId:o.toolCallId})}return g;case v.REASONING_MESSAGE_CHUNK:let _=m,S=[];if((i!=="reasoning"||_.messageId&&_.messageId!==s?.messageId)&&S.push(...p()),i!=="reasoning"){if(_.messageId===void 0)throw Error("First REASONING_MESSAGE_CHUNK must have a messageId");s={messageId:_.messageId},i="reasoning";let b={type:v.REASONING_MESSAGE_START,messageId:_.messageId};S.push(b),n?.event("TRANSFORM","REASONING_MESSAGE_START",b,{messageId:_.messageId})}if(_.delta!==void 0){let b={type:v.REASONING_MESSAGE_CONTENT,messageId:s.messageId,delta:_.delta};S.push(b),n?.event("TRANSFORM","REASONING_MESSAGE_CONTENT",b,{messageId:s.messageId})}return S}return m.type,[]}),Wt(()=>{p()}))};function Im(e,t=new Date){return e.expiresAt===void 0?!1:new Date(e.expiresAt)<=t}var qo=class{runNext(e,t){return t.run(e).pipe(Yo(!1))}runNextWithState(e,t){let n=B(e.messages||[]),r=B(e.state||{}),o=new Kr;return Xc(e,o,t,[]).subscribe(s=>{s.messages!==void 0&&(n=s.messages),s.state!==void 0&&(r=s.state)}),this.runNext(e,t).pipe(po(async s=>(o.next(s),await new Promise(i=>setTimeout(i,0)),{event:s,messages:B(n),state:B(r)})))}},Cm=class extends qo{constructor(e){super(),this.fn=e}run(e,t){return this.fn(e,t)}};function Nm(e){let t=e.content;if(Array.isArray(t)){let n=t.filter(r=>typeof r=="object"&&!!r&&"type"in r&&r.type==="text"&&typeof r.text=="string").map(r=>r.text).join("");return{...e,content:n}}return typeof t=="string"?e:{...e,content:""}}var Rm=class extends qo{run(e,t){let{parentRunId:n,...r}=e,o={...r,messages:r.messages.map(Nm)};return this.runNext(o,t)}},zc="THINKING_START",Bc="THINKING_END",Vc="THINKING_TEXT_MESSAGE_START",jc="THINKING_TEXT_MESSAGE_CONTENT",Wc="THINKING_TEXT_MESSAGE_END",Om=class extends qo{constructor(...e){super(...e),this.currentReasoningId=null,this.currentMessageId=null}warnAboutTransformation(e,t){typeof process<"u"&&process.env!==void 0&&process.env.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is converting ${e} to ${t}. To remove this warning, upgrade your AG-UI integration package (e.g. @ag-ui/langgraph). To surpress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(e,t){return this.currentReasoningId=null,this.currentMessageId=null,this.runNext(e,t).pipe(jt(n=>this.transformEvent(n)))}transformEvent(e){switch(e.type){case zc:{this.currentReasoningId=ze();let{title:t,...n}=e;return this.warnAboutTransformation(zc,v.REASONING_START),{...n,type:v.REASONING_START,messageId:this.currentReasoningId}}case Vc:return this.currentMessageId=ze(),this.warnAboutTransformation(Vc,v.REASONING_MESSAGE_START),{...e,type:v.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:"assistant"};case jc:{let{delta:t,...n}=e;return this.warnAboutTransformation(jc,v.REASONING_MESSAGE_CONTENT),{...n,type:v.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??ze(),delta:t}}case Wc:{let t=this.currentMessageId??ze();return this.warnAboutTransformation(Wc,v.REASONING_MESSAGE_END),{...e,type:v.REASONING_MESSAGE_END,messageId:t}}case Bc:{let t=this.currentReasoningId??ze();return this.warnAboutTransformation(Bc,v.REASONING_END),{...e,type:v.REASONING_END,messageId:t}}default:return e}}};function Mm(e){return e.startsWith("image/")?"image":e.startsWith("audio/")?"audio":e.startsWith("video/")?"video":"document"}function Lm(e){return typeof e=="object"&&!!e&&"type"in e&&e.type==="binary"&&"mimeType"in e&&typeof e.mimeType=="string"}function Pm(e){let t=Mm(e.mimeType);return e.data?{type:t,source:{type:"data",value:e.data,mimeType:e.mimeType},...e.filename?{metadata:{filename:e.filename}}:{}}:e.url?{type:t,source:{type:"url",value:e.url,mimeType:e.mimeType},...e.filename?{metadata:{filename:e.filename}}:{}}:e}function Dm(e){let t=e.content;if(!Array.isArray(t))return e;let n=t.map(r=>Lm(r)?Pm(r):r);return{...e,content:n}}var Um=class extends qo{run(e,t){let n={...e,messages:e.messages.map(Dm)};return this.runNext(n,t)}},Gm="0.0.54",Fm=class{get maxVersion(){return Gm}get debug(){return this._debug}set debug(e){this._debug=Ko(e),this._debugLogger=Oi(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(e){typeof e=="boolean"?this._debugLogger=e?Oi(Ko(!0)):void 0:this._debugLogger=e}constructor({agentId:e,description:t,threadId:n,initialMessages:r,initialState:o,debug:s}={}){this.subscribers=[],this.isRunning=!1,this.pendingInterrupts=[],this.middlewares=[],this.agentId=e,this.description=t??"",this.threadId=n??ht(),this.messages=B(r??[]),this.state=B(o??{}),this._debug=Ko(s),this._debugLogger=Oi(this._debug),Jn(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new Rm),Jn(this.maxVersion,"0.0.45")<=0&&this.middlewares.unshift(new Om),Jn(this.maxVersion,"0.0.47")<=0&&this.middlewares.unshift(new Um)}subscribe(e){return this.subscribers.push(e),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(t=>t!==e)}}}use(...e){let t=e.map(n=>typeof n=="function"?new Cm(n):n);return this.middlewares.push(...t),this}async runAgent(e,t){try{this.isRunning=!0,this.agentId=this.agentId??ht();let n=this.prepareRunAgentInput(e);this.debugLogger?.lifecycle("LIFECYCLE","Run started:",{agentId:this.agentId,threadId:this.threadId});let r,o=new Set(this.messages.map(u=>u.id)),s=[{onRunFinishedEvent:u=>{u.outcome==="success"&&(r=u.result)}},...this.subscribers,t??{}];await this.onInitialize(n,s),this.activeRunDetach$=new rt;let i;this.activeRunCompletionPromise=new Promise(u=>{i=u}),await co(Zr(()=>this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((u,c)=>({run:p=>c.run(p,u),get messages(){return u.messages},get state(){return u.state}}),this).run(n),Yo(this.debugLogger),Mi(this.debugLogger),u=>u.pipe(fo(this.activeRunDetach$)),u=>this.apply(n,u,s),u=>this.processApplyEvents(n,u,s),Kn(u=>(this.debugLogger?.lifecycle("LIFECYCLE","Run errored:",{agentId:this.agentId,error:u instanceof Error?u.message:String(u)}),this.isRunning=!1,this.onError(n,u,s))),Wt(()=>{this.debugLogger?.lifecycle("LIFECYCLE","Run finished:",{agentId:this.agentId,threadId:this.threadId}),this.isRunning=!1,this.onFinalize(n,s),i?.(),i=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(te(null)));let a=B(this.messages).filter(u=>!o.has(u.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}connect(e){throw new ti}async connectAgent(e,t){try{this.isRunning=!0,this.agentId=this.agentId??ht();let n=this.prepareRunAgentInput(e),r,o=new Set(this.messages.map(u=>u.id)),s=[{onRunFinishedEvent:u=>{u.outcome==="success"&&(r=u.result)}},...this.subscribers,t??{}];await this.onInitialize(n,s),this.activeRunDetach$=new rt;let i;this.activeRunCompletionPromise=new Promise(u=>{i=u}),await co(Zr(()=>uo(()=>this.connect(n)),Yo(this.debugLogger),Mi(this.debugLogger),u=>u.pipe(fo(this.activeRunDetach$)),u=>this.apply(n,u,s),u=>this.processApplyEvents(n,u,s),Kn(u=>(this.isRunning=!1,u instanceof ti?Yr:this.onError(n,u,s))),Wt(()=>{this.isRunning=!1,this.onFinalize(n,s),i?.(),i=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(te(null)),{defaultValue:void 0});let a=B(this.messages).filter(u=>!o.has(u.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let e=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await e}apply(e,t,n){return Xc(e,t,this,n,this.debugLogger)}processApplyEvents(e,t,n){return t.pipe(vi(r=>{r.messages&&(this.messages=r.messages,n.forEach(o=>{o.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),r.state&&(this.state=r.state,n.forEach(o=>{o.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})}))}))}prepareRunAgentInput(e){let t=B(this.messages).filter(n=>n.role!=="activity");return{threadId:this.threadId,runId:e?.runId||ht(),tools:B(e?.tools??[]),context:B(e?.context??[]),forwardedProps:B(e?.forwardedProps??{}),state:B(this.state),messages:t,...e?.resume===void 0?{}:{resume:B(e.resume)}}}async onInitialize(e,t){if(this.pendingInterrupts.length>0){let r=new Set((e.resume??[]).map(s=>s.interruptId)),o=this.pendingInterrupts.map(s=>s.id).filter(s=>!r.has(s));if(o.length>0)throw new q(`Thread has ${o.length} pending interrupt(s) not addressed by resume: ${o.join(", ")}`);for(let s of this.pendingInterrupts)if(Im(s))throw new q(`Interrupt ${s.id} expired at ${s.expiresAt}`)}let n=await W(t,this.messages,this.state,(r,o,s)=>r.onRunInitialized?.({messages:o,state:s,agent:this,input:e}));(n.messages!==void 0||n.state!==void 0)&&(n.messages&&(this.messages=n.messages,e.messages=n.messages,t.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),n.state&&(this.state=n.state,e.state=n.state,t.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})})))}onError(e,t,n){return Vt(W(n,this.messages,this.state,(r,o,s)=>r.onRunFailed?.({error:t,messages:o,state:s,agent:this,input:e}))).pipe(jt(r=>{let o=r;if((o.messages!==void 0||o.state!==void 0)&&(o.messages!==void 0&&(this.messages=o.messages,n.forEach(s=>{s.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),o.state!==void 0&&(this.state=o.state,n.forEach(s=>{s.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})}))),o.stopPropagation!==!0){let s=String(t);if(!(t.name==="AbortError"||t.message==="Fetch is aborted"||t.message==="signal is aborted without reason"||t.message==="component unmounted"||s==="component unmounted"))throw console.error("Agent execution failed:",t),t}return{}}))}async onFinalize(e,t){let n=await W(t,this.messages,this.state,(r,o,s)=>r.onRunFinalized?.({messages:o,state:s,agent:this,input:e}));(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,t.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),n.state!==void 0&&(this.state=n.state,t.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})})))}clone(){let e=Object.create(Object.getPrototypeOf(this));return e.agentId=this.agentId,e.description=this.description,e.threadId=this.threadId,e.messages=B(this.messages),e.state=B(this.state),e._debug=this._debug,e._debugLogger=this._debugLogger,e.isRunning=this.isRunning,e.subscribers=[...this.subscribers],e.middlewares=[...this.middlewares],e.pendingInterrupts=B(this.pendingInterrupts),e}addMessage(e){this.messages.push(e),(async()=>{for(let t of this.subscribers)await t.onNewMessage?.({message:e,messages:this.messages,state:this.state,agent:this});if(e.role==="assistant"&&e.toolCalls)for(let t of e.toolCalls)for(let n of this.subscribers)await n.onNewToolCall?.({toolCall:t,messages:this.messages,state:this.state,agent:this});for(let t of this.subscribers)await t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}addMessages(e){this.messages.push(...e),(async()=>{for(let t of e){for(let n of this.subscribers)await n.onNewMessage?.({message:t,messages:this.messages,state:this.state,agent:this});if(t.role==="assistant"&&t.toolCalls)for(let n of t.toolCalls)for(let r of this.subscribers)await r.onNewToolCall?.({toolCall:n,messages:this.messages,state:this.state,agent:this})}for(let t of this.subscribers)await t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setMessages(e){this.messages=B(e),(async()=>{for(let t of this.subscribers)await t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(e){this.state=B(e),(async()=>{for(let t of this.subscribers)await t.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(e){this.agentId=this.agentId??ht();let t=this.prepareRunAgentInput(e);return(this.middlewares.length===0?this.run(t):this.middlewares.reduceRight((n,r)=>({run:o=>r.run(o,n),get messages(){return n.messages},get state(){return n.state}}),this).run(t)).pipe(Yo(this.debugLogger),Mi(this.debugLogger),km(this.threadId,t.runId,this.agentId),n=>n.pipe(jt(r=>(this.debugLogger?.event("LEGACY","Event:",r,{type:r.type}),r))))}},Zc=class extends Fm{requestInit(e){return{method:"POST",headers:{...this.headers,"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify(e),signal:this.abortController.signal}}runAgent(e,t){return this.abortController=e?.abortController??new AbortController,super.runAgent(e,t)}abortRun(){this.abortController.abort(),super.abortRun()}constructor(e){super(e),this.abortController=new AbortController,this.url=e.url,this.headers=B(e.headers??{}),this.fetch=e.fetch??fetch}run(e){return fm(um(()=>this.fetch(this.url,this.requestInit(e))),this.debugLogger)}clone(){let e=super.clone();e.url=this.url,e.headers=B(this.headers??{}),e.fetch=this.fetch;let t=new AbortController,n=this.abortController.signal;return n.aborted&&t.abort(n.reason),e.abortController=t,e}};var er=class{#e;#n;#i;#u;#a;#o;constructor(t){this.#e=t.agent,this.#n=t.handlers,this.#i=t.getTools??(()=>[]),this.#u=t.getContext??(()=>[]),this.#a=t.executeTool??null,this.#o=t.onPersist??(()=>{})}get running(){return this.#e.isRunning}get messages(){return this.#e.messages}async send(t){this.#e.addMessage({id:ze(),role:"user",content:t}),this.#o(this.#e.messages),await this.#t()}async resume(){await this.#t()}addToolResult(t,n){this.#e.addMessage({id:ze(),role:"tool",content:n,toolCallId:t}),this.#o(this.#e.messages)}async#t(){try{await this.#r()}catch(t){this.#n.onError(t instanceof Error?t.message:String(t))}finally{this.#n.onSettled()}}async#r(){for(let t=0;t<bs;t+=1){let n=[];if(await this.#e.runAgent({tools:this.#i(),context:this.#u()},this.#s(n)),this.#o(this.#e.messages),this.#a===null||n.length===0)return;let r=!1;for(let o of n){let s=await this.#a(o);if(s!==null){if(s.halt===!0)return;this.#e.addMessage({id:ze(),role:"tool",content:s.content,toolCallId:o.id}),this.#o(this.#e.messages),r=!0}}if(!r)return}}#s(t){let n=this.#n;return{onRunInitialized(){n.onRunStart()},onTextMessageContentEvent({textMessageBuffer:r}){n.onTextDelta(r)},onTextMessageEndEvent({textMessageBuffer:r}){n.onTextEnd(r)},onToolCallEndEvent({event:r,toolCallName:o,toolCallArgs:s}){let i={id:r.toolCallId,name:o,args:s};t.push(i),n.onToolCall(i)},onToolCallResultEvent({event:r}){n.onToolResult(r.toolCallId,r.content)},onRunErrorEvent({event:r}){n.onError(r.message)},onRunFinalized(){n.onRunEnd()}}}};var Di="ag-ui-chat:thread",Ui="ag-ui-chat:messages:",Gi="ag-ui-chat:checkpoint:",tr=class{threadId(){let t=sessionStorage.getItem(Di);if(t!==null)return t;let n=ze();return sessionStorage.setItem(Di,n),n}loadMessages(t){return Promise.resolve(this.#e(Ui+t))}saveMessages(t,n){sessionStorage.setItem(Ui+t,JSON.stringify(n))}loadCheckpoint(t){return this.#e(Gi+t)}saveCheckpoint(t,n){let r=Gi+t;if(n===null){sessionStorage.removeItem(r);return}sessionStorage.setItem(r,JSON.stringify(n))}clear(t){sessionStorage.removeItem(Ui+t),sessionStorage.removeItem(Gi+t),sessionStorage.removeItem(Di)}#e(t){let n=sessionStorage.getItem(t);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function Fi(e){return new Zc({url:e.endpoint,headers:e.headers??{},fetch:(t,n)=>{let r=e.getHeaders?.();if(r===void 0)return fetch(t,n);let o=new Headers(n?.headers);for(let[s,i]of Object.entries(r))o.set(s,i);return fetch(t,{...n,headers:o})},...e.threadId!==void 0?{threadId:e.threadId}:{},...e.initialMessages!==void 0?{initialMessages:[...e.initialMessages]}:{}})}var Kc="ag-ui-chat:collapsed",nr=class extends HTMLElement{agentFactory=Fi;headers={};allowImages=!1;autoConfirm=!1;confirmPredicate=null;getTools=()=>[...this.#k().map(t=>({name:t.name,description:t.description,parameters:t.parameters})),...this.#n.tools()];getContext=()=>Ts(this.getPageMap,this.autoInjectPageMap);routeMap=[];navigate=null;getPageMap=null;autoInjectPageMap=!0;conversationStore=new tr;navigationResult=()=>({navigated:!0,url:window.location.href});skillContext=()=>({});toolSummaries={};#e={};#n=new On;#i=new Map;#u=new Set;#a;#o;#t;#r;#s;#f;#l;#p;#m=null;#d=null;#y=0;#g=null;#c="";#b=[];#T=[];#S=[];#w=[];constructor(){super(),this.#a=this.attachShadow({mode:"open"}),this.#o=document.createElement("div"),this.#t=document.createElement("div"),this.#r=document.createElement("textarea"),this.#s=document.createElement("button"),this.#f=document.createElement("span"),this.#p=document.createElement("div"),this.#l=new wr(t=>this.#U(t))}static get observedAttributes(){return["title-text"]}attributeChangedCallback(t,n,r){this.#f.textContent=r??"Assistant"}registerTool(t){this.#n.register(t)}registerStateHook(t){for(let n of ks(t))this.#n.register(n)}#R(){return this.routeMap.length===0?[]:ws(()=>this.routeMap,()=>this.navigate)}#O(){let t=this.getPageMap;return t===null?[]:[{name:"read_page",description:"Read the current page's structure (fields, buttons, route). Call after acting to observe the result within the same turn.",parameters:{type:"object",properties:{},required:[],[Xe]:"Read the page"},handler:()=>t()}]}#k(){return[...this.#R(),...this.#O()]}#A(t){let n=this.#k().find(r=>r.name===t);return n!==void 0?n:this.#n.has(t)?this.#n.get(t):null}get endpoint(){return this.getAttribute("endpoint")??""}set endpoint(t){this.setAttribute("endpoint",t)}get toolDisplay(){let t=this.getAttribute("data-tool-display");return t===Ze.MINIMAL||t===Ze.COMPACT?t:Ze.FULL}set toolDisplay(t){this.setAttribute("data-tool-display",t)}connectedCallback(){this.#z(),sessionStorage.getItem(Kc)==="1"&&this.setAttribute("collapsed",""),this.#L(),this.#M(),this.#c=this.conversationStore.threadId(),this.#G()}async#M(){let t=this.getAttribute("data-tools-url");if(t!==null)try{let n=await fetch(t,{headers:this.headers});this.#e=Ss(await n.json())}catch{}}setSkills(t){this.#w=t,this.#x()}#L(){this.#l.enableChips(this.getAttribute("data-prompt-chips")==="true"),this.#l.enableSlash(this.getAttribute("data-slash-commands")==="true"),this.#S=this.#P(),this.#x(),this.#D()}#P(){let t=this.getAttribute("data-skills");if(t===null)return[];try{return xs(JSON.parse(t))}catch{return[]}}async#D(){let t=this.getAttribute("data-skills-url");if(t!==null)try{let n=await fetch(t,{headers:this.headers});this.#T=xs(await n.json()),this.#x()}catch{}}#x(){let t=new Map;for(let n of[...this.#T,...this.#S,...this.#w])t.set(n.name,n);this.#l.setSkills([...t.values()])}#U(t){let{text:n,missing:r}=va(t.prompt,this.skillContext());if(r.length>0){this.#p.textContent=`\u201C${t.title}\u201D needs: ${r.join(", ")}`,this.#p.hidden=!1;return}this.#p.hidden=!0,this.#r.value=n,t.sendImmediately===!0?this.#E():this.#r.focus()}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(t){this.setCollapsed(t)}setCollapsed(t){t?this.setAttribute("collapsed",""):this.removeAttribute("collapsed"),sessionStorage.setItem(Kc,t?"1":"0"),this.dispatchEvent(new CustomEvent(vs,{detail:{collapsed:t},bubbles:!0,composed:!0}))}toggleCollapsed(){this.setCollapsed(!this.collapsed)}newChat(){this.conversationStore.clear(this.#c),this.#m=null,this.#d=null,this.#h(),this.#i.clear(),this.#u.clear(),this.#b=[],this.#t.replaceChildren(),this.#c=this.conversationStore.threadId(),this.#s.disabled=!1}async#G(){let t=await this.conversationStore.loadMessages(this.#c);if(t!==null){this.#b=t;for(let r of t)this.#F(r)}let n=this.conversationStore.loadCheckpoint(this.#c);n!==null&&await this.#$(n)}#F(t){let n=typeof t.content=="string"?t.content:"";if(t.role===We.USER){n!==""&&this.appendMessage(We.USER,n);return}if(t.role===We.ASSISTANT){n!==""&&this.appendMessage(We.ASSISTANT,n).classList.add("message--restored");let r=t.toolCalls;if(r!==void 0)for(let o of r)this.#_({id:o.id,name:o.function.name,args:this.#H(o.function.arguments)});return}if(t.role==="tool"){let r=this.#i.get(t.toolCallId);r!==void 0&&r.settle(de.DONE,t.content)}}#H(t){try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#I(t){this.getAttribute("data-text-animation")==="word"&&rl(t)}async#$(t){this.conversationStore.saveCheckpoint(this.#c,null);let n=this.#C();n.addToolResult(t.toolCallId,JSON.stringify(this.navigationResult(t))),await n.resume()}appendMessage(t,n){let r=document.createElement("div");return r.className=`message message--${t}`,t===We.ASSISTANT?r.innerHTML=Sr(n,{allowImages:this.allowImages}):r.textContent=n,this.#t.appendChild(r),this.#t.scrollTop=this.#t.scrollHeight,r}#z(){let t=document.createElement("style");t.textContent=ol,this.#o.className="chat";let n=document.createElement("div");n.className="header";let r=this.#f;r.className="header-title",r.textContent=this.getAttribute("title-text")??"Assistant";let o=document.createElement("div");o.className="header-controls";let s=document.createElement("button");s.type="button",s.className="header-btn header-btn--new",s.title="New chat",s.setAttribute("aria-label","New chat"),s.textContent="\u271A",s.addEventListener("click",()=>this.newChat());let i=document.createElement("button");i.type="button",i.className="header-btn header-btn--collapse",i.title="Collapse",i.setAttribute("aria-label","Collapse"),i.textContent="\u2014",i.addEventListener("click",()=>this.toggleCollapsed()),o.append(s,i),n.append(r,o),this.#t.className="messages",this.#t.setAttribute("role","log"),this.#t.setAttribute("aria-live","polite"),this.#t.setAttribute("aria-label","Conversation");let a=document.createElement("div");a.className="input-row",this.#r.className="input",this.#r.setAttribute("aria-label","Message"),this.#r.rows=2,this.#r.placeholder="Ask anything\u2026",this.#r.addEventListener("keydown",u=>this.#V(u)),this.#r.addEventListener("input",()=>this.#B()),this.#s.className="send",this.#s.type="button",this.#s.textContent="Send",this.#s.addEventListener("click",()=>{this.#E()}),this.#p.className="skill-hint",this.#p.hidden=!0,a.append(this.#r,this.#s),this.#o.append(n,this.#t,this.#l.palette,this.#l.chips,this.#p,a),this.#a.append(t,this.#o)}#B(){this.#l.onInput(this.#r.value),this.#p.hidden=!0}#V(t){if(this.#l.onKeydown(t)){t.preventDefault();return}t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),this.#E())}async#E(){let t=this.#r.value.trim();t!==""&&(this.appendMessage(We.USER,t),this.#r.value="",this.dispatchEvent(new CustomEvent(gs,{detail:{content:t},bubbles:!0,composed:!0})),await this.#j(t))}async#j(t){this.endpoint!==""&&await this.#C().send(t)}#C(){if(this.#m===null){let t=this.agentFactory({endpoint:this.endpoint,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#c,initialMessages:this.#b});this.#m=new er({agent:t,handlers:this.#Z(),getTools:()=>this.getTools(),getContext:()=>this.getContext(),executeTool:n=>this.#X(n),onPersist:n=>this.conversationStore.saveMessages(this.#c,n)})}return this.#m}async#W(t,n){return this.autoConfirm?!1:this.confirmPredicate!==null?await this.confirmPredicate(t.name,t.args)===!0:Es(n.parameters)}async#X(t){let n=this.#_(t);this.#i.delete(t.id);let r=this.#A(t.name);if(r===null)return this.#u.has(t.id)||n.settle(de.DONE,"No result returned."),null;if(await this.#W(t,r)){let s={toolName:t.name,args:t.args},i=r.parameters[ys];typeof i=="string"&&(s.message=i);let a=As(this.#t,s);if(this.#t.scrollTop=this.#t.scrollHeight,!await a){let c="User declined the action.";return n.settle(de.DECLINED,c),this.#v(),{content:c}}}let o=_s(r.parameters)&&this.navigate===null;o&&this.conversationStore.saveCheckpoint(this.#c,{toolCallId:t.id});try{let s=await r.handler(t.args);if(o)return n.settle(de.DONE,"Navigating\u2026"),{content:"",halt:!0};let i=JSON.stringify(s??null);return n.settle(de.DONE,i),this.#v(),{content:i}}catch(s){o&&this.conversationStore.saveCheckpoint(this.#c,null);let i=s instanceof Error?s.message:String(s);return n.settle(de.ERROR,i),this.#v(),{content:`Error: ${i}`,error:i}}}#Z(){return{onRunStart:()=>{this.#s.disabled=!0,this.#v()},onTextDelta:t=>{this.#h(),this.#N(t),this.#y+=1},onTextEnd:t=>{let n=this.#N(t);this.#y<=1&&this.#I(n),this.#d=null},onToolCall:t=>{this.#h(),this.#_(t)},onToolResult:(t,n)=>{let r=this.#i.get(t);r!==void 0&&(r.settle(de.DONE,n),this.#u.add(t))},onRunEnd:()=>{this.#h(),this.#s.disabled=!1,this.#d=null},onError:t=>{this.#h(),this.#I(this.appendMessage(We.ASSISTANT,`\u26A0\uFE0F ${t}`)),this.#s.disabled=!1,this.#d=null},onSettled:()=>{this.#h(),this.#s.disabled=!1,this.#d=null}}}#v(){if(this.#g!==null)return;let t=document.createElement("div");t.className="pending",t.setAttribute("role","status"),t.setAttribute("aria-label","Assistant is thinking\u2026");for(let n=0;n<3;n+=1){let r=document.createElement("span");r.className="pending-dot",t.appendChild(r)}this.#g=t,this.#t.appendChild(t),this.#t.scrollTop=this.#t.scrollHeight}#h(){this.#g?.remove(),this.#g=null}#N(t){return this.#d===null&&(this.#d=this.appendMessage(We.ASSISTANT,""),this.#y=0),this.#d.innerHTML=Sr(t,{allowImages:this.allowImages}),this.#t.scrollTop=this.#t.scrollHeight,this.#d}#_(t){let n=this.#i.get(t.id);if(n!==void 0)return n;let r=this.#A(t.name)?.parameters[Xe],o=typeof r=="string"?r:this.toolSummaries[t.name]??this.#e[t.name]??Is(t.name),s=new Fn(t.name,t.args,this.toolDisplay,o);return this.#i.set(t.id,s),this.#t.appendChild(s.element),this.#t.scrollTop=this.#t.scrollHeight,s}};function Hm(){customElements.get(gr)===void 0&&customElements.define(gr,nr)}function Jo(e,t){return Object.getOwnPropertyDescriptor(e,t).set}var $m=Jo(HTMLInputElement.prototype,"value"),zm=Jo(HTMLTextAreaElement.prototype,"value"),Bm=Jo(HTMLSelectElement.prototype,"value"),Vm=Jo(HTMLInputElement.prototype,"checked");function Zt(e,t){e instanceof HTMLTextAreaElement?zm.call(e,t):e instanceof HTMLSelectElement?Bm.call(e,t):$m.call(e,t)}function rr(e,t){Vm.call(e,t)}var Yc="#4f46e5";function Qo(e){return new Promise(t=>{setTimeout(t,e)})}async function Hi(e,t,n={}){let r=n.charDelayMs??35;Zt(e,""),e.dispatchEvent(new Event("input",{bubbles:!0}));for(let o of t)Zt(e,e.value+o),e.dispatchEvent(new Event("input",{bubbles:!0})),r>0&&await Qo(r);e.dispatchEvent(new Event("change",{bubbles:!0}))}async function $i(e,t={}){let n=t.highlightMs??280,r=e.style.outline,o=e.style.outlineOffset;e.style.outline=`2px solid ${Yc}`,e.style.outlineOffset="2px",await Qo(n),e.style.outline=r,e.style.outlineOffset=o,e.click()}function Kt(e){e.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}async function zi(e,t={}){let n=t.flashMs??200;e.focus();let r=e.style.boxShadow;e.style.boxShadow="0 0 0 3px rgba(79, 70, 229, 0.4)",await Qo(n),e.style.boxShadow=r}var qc="0 0 0 3px rgba(79, 70, 229, 0.4)";function Jc(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Bi(e){return e<=0||Jc()?Promise.resolve():Qo(e)}async function Vi(e,t={}){let n=t.pressMs??140,r=e.style.transform,o=e.style.transition,s=e.style.boxShadow;e.style.transition="transform 80ms ease",e.style.transform="scale(0.96)",e.style.boxShadow=qc,await Bi(n),e.style.transform=r,e.style.transition=o,e.style.boxShadow=s,e.click()}function jm(e,t){for(let n of Array.from(e.options))if(n.value===t||n.text===t)return n;return null}async function ji(e,t,n={}){let r=jm(e,t);if(r===null)throw new Error(`no <option> matching "${t}"`);let o=n.highlightMs??220,s=e.style.outline,i=e.style.outlineOffset;e.style.outline=`2px solid ${Yc}`,e.style.outlineOffset="2px",await Bi(o),Zt(e,r.value),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.style.outline=s,e.style.outlineOffset=i}async function Wi(e,t,n={}){let r=n.flashMs??200,o=e.style.boxShadow;e.style.boxShadow=qc,await Bi(r),rr(e,t),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.style.boxShadow=o}async function Wm(e,t,n={}){Kt(e),await zi(e,{flashMs:n.flashMs??0}),await Hi(e,t,n)}async function Xm(e,t={}){Kt(e),await $i(e,t)}async function Zm(e,t={}){Kt(e),await Vi(e,t)}async function Km(e,t,n={}){Kt(e),await ji(e,t,n)}async function Ym(e,t,n={}){Kt(e),await Wi(e,t,n)}function qm(e,t){e instanceof HTMLInputElement&&e.type==="checkbox"?rr(e,!!t):Zt(e,String(t)),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}))}var Jm="0.3.1";export{nr as AgUiChat,er as AgUiClient,On as ClientToolRegistry,gr as ELEMENT_TAG,bs as MAX_TOOL_ROUNDS,We as MESSAGE_ROLE,gs as SUBMIT_EVENT,tr as SessionStorageStore,vs as TOGGLE_EVENT,de as TOOL_CALL_STATUS,Ze as TOOL_DISPLAY,Fn as ToolCallCard,Jm as VERSION,ys as X_CONFIRM_KEY,Nn as X_DESTRUCTIVE_KEY,Rn as X_NAVIGATES_KEY,Xe as X_SUMMARY_KEY,Xm as clickElement,Fi as createHttpAgent,Ts as createPageMapContext,ws as createRouteTools,ks as createStateHookTools,Hm as defineAgUiChat,Wm as fillField,zi as focusWithFlash,$i as highlightThenClick,Es as isDestructive,_s as isNavigates,Ss as parseToolCatalog,Jc as prefersReducedMotion,Zm as pressButton,Vi as pressThenClick,Is as prettifyToolName,Sr as renderMarkdown,As as requestConfirmation,Kt as scrollIntoCenterView,Km as selectControl,ji as selectOption,qm as setControlValue,rr as setNativeChecked,Zt as setNativeValue,Ym as toggleCheckbox,Wi as toggleControl,Hi as typeInto};
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};
708
721
  /*! Bundled license information:
709
722
 
710
723
  dompurify/dist/purify.es.mjs: