@invergent/website-widget 2.7.8 → 2.7.9

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,12 +1,12 @@
1
- "use strict";var SurogatesWidget=(()=>{var Xr=Object.defineProperty;var Ls=Object.getOwnPropertyDescriptor;var Ds=Object.getOwnPropertyNames;var Us=Object.prototype.hasOwnProperty;var Bt=(t,e)=>{for(var r in e)Xr(t,r,{get:e[r],enumerable:!0})},Gs=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ds(e))!Us.call(t,o)&&o!==r&&Xr(t,o,{get:()=>e[o],enumerable:!(n=Ls(e,o))||n.enumerable});return t};var Fs=t=>Gs(Xr({},"__esModule",{value:!0}),t);var Vu={};Bt(Vu,{AbstractAgent:()=>Or,EventType:()=>g,PROTOCOL_VERSION:()=>Bo,SDK_VERSION:()=>Rr,SURG_EVENT:()=>D,SurogatesAuthError:()=>fe,SurogatesError:()=>Re,SurogatesNetworkError:()=>st,SurogatesProtocolError:()=>Me,SurogatesRateLimitError:()=>Pe,Translator:()=>at,WebsiteAgent:()=>wt,mount:()=>Rs});var Y=[];for(let t=0;t<256;++t)Y.push((t+256).toString(16).slice(1));function Wn(t,e=0){return(Y[t[e+0]]+Y[t[e+1]]+Y[t[e+2]]+Y[t[e+3]]+"-"+Y[t[e+4]]+Y[t[e+5]]+"-"+Y[t[e+6]]+Y[t[e+7]]+"-"+Y[t[e+8]]+Y[t[e+9]]+"-"+Y[t[e+10]]+Y[t[e+11]]+Y[t[e+12]]+Y[t[e+13]]+Y[t[e+14]]+Y[t[e+15]]).toLowerCase()}var zr,Hs=new Uint8Array(16);function Kr(){if(!zr){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");zr=crypto.getRandomValues.bind(crypto)}return zr(Hs)}var Vs=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Zr={randomUUID:Vs};function $s(t,e,r){if(Zr.randomUUID&&!e&&!t)return Zr.randomUUID();t=t||{};let n=t.random??t.rng?.()??Kr();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[r+o]=n[o];return e}return Wn(n)}var Ae=$s;var l={};Bt(l,{BRAND:()=>ma,DIRTY:()=>Ue,EMPTY_PATH:()=>Xs,INVALID:()=>w,NEVER:()=>Ja,OK:()=>Q,ParseStatus:()=>q,Schema:()=>C,ZodAny:()=>Ce,ZodArray:()=>Se,ZodBigInt:()=>Fe,ZodBoolean:()=>He,ZodBranded:()=>Ot,ZodCatch:()=>qe,ZodDate:()=>Ve,ZodDefault:()=>Ye,ZodDiscriminatedUnion:()=>zt,ZodEffects:()=>le,ZodEnum:()=>Ke,ZodError:()=>re,ZodFirstPartyTypeKind:()=>A,ZodFunction:()=>Zt,ZodIntersection:()=>We,ZodIssueCode:()=>b,ZodLazy:()=>Xe,ZodLiteral:()=>ze,ZodMap:()=>pt,ZodNaN:()=>ht,ZodNativeEnum:()=>Ze,ZodNever:()=>ce,ZodNull:()=>je,ZodNullable:()=>ge,ZodNumber:()=>Ge,ZodObject:()=>ne,ZodOptional:()=>ae,ZodParsedType:()=>x,ZodPipeline:()=>Rt,ZodPromise:()=>ke,ZodReadonly:()=>Je,ZodRecord:()=>Kt,ZodSchema:()=>C,ZodSet:()=>mt,ZodString:()=>Ne,ZodSymbol:()=>dt,ZodTransformer:()=>le,ZodTuple:()=>he,ZodType:()=>C,ZodUndefined:()=>$e,ZodUnion:()=>Be,ZodUnknown:()=>be,ZodVoid:()=>ft,addIssueToContext:()=>S,any:()=>xa,array:()=>Ia,bigint:()=>va,boolean:()=>ro,coerce:()=>qa,custom:()=>Qn,date:()=>ya,datetimeRegex:()=>qn,defaultErrorMap:()=>ye,discriminatedUnion:()=>Oa,effect:()=>ja,enum:()=>Ha,function:()=>Ua,getErrorMap:()=>lt,getParsedType:()=>me,instanceof:()=>ga,intersection:()=>Ra,isAborted:()=>Wt,isAsync:()=>ut,isDirty:()=>Xt,isValid:()=>Ie,late:()=>ha,lazy:()=>Ga,literal:()=>Fa,makeIssue:()=>kt,map:()=>La,nan:()=>_a,nativeEnum:()=>Va,never:()=>wa,null:()=>Sa,nullable:()=>Wa,number:()=>to,object:()=>Na,objectUtil:()=>Yr,oboolean:()=>Ya,onumber:()=>Za,optional:()=>Ba,ostring:()=>Ka,pipeline:()=>za,preprocess:()=>Xa,promise:()=>$a,quotelessJson:()=>js,record:()=>Ma,set:()=>Da,setErrorMap:()=>Ws,strictObject:()=>Ca,string:()=>eo,symbol:()=>Ea,transformer:()=>ja,tuple:()=>Pa,undefined:()=>ba,union:()=>ka,unknown:()=>Ta,util:()=>O,void:()=>Aa});var O;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let a of o)s[a]=a;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(i=>typeof o[o[i]]!="number"),a={};for(let i of s)a[i]=o[i];return t.objectValues(a)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},t.find=(o,s)=>{for(let a of o)if(s(a))return a},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(O||(O={}));var Yr;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Yr||(Yr={}));var x=O.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),me=t=>{switch(typeof t){case"undefined":return x.undefined;case"string":return x.string;case"number":return Number.isNaN(t)?x.nan:x.number;case"boolean":return x.boolean;case"function":return x.function;case"bigint":return x.bigint;case"symbol":return x.symbol;case"object":return Array.isArray(t)?x.array:t===null?x.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?x.promise:typeof Map<"u"&&t instanceof Map?x.map:typeof Set<"u"&&t instanceof Set?x.set:typeof Date<"u"&&t instanceof Date?x.date:x.object;default:return x.unknown}};var b=O.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"]),js=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),re=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let i=n,c=0;for(;c<a.path.length;){let u=a.path[c];c===a.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(r(a))):i[u]=i[u]||{_errors:[]},i=i[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,O.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};re.create=t=>new re(t);var Bs=(t,e)=>{let r;switch(t.code){case b.invalid_type:t.received===x.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case b.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,O.jsonStringifyReplacer)}`;break;case b.unrecognized_keys:r=`Unrecognized key(s) in object: ${O.joinValues(t.keys,", ")}`;break;case b.invalid_union:r="Invalid input";break;case b.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${O.joinValues(t.options)}`;break;case b.invalid_enum_value:r=`Invalid enum value. Expected ${O.joinValues(t.options)}, received '${t.received}'`;break;case b.invalid_arguments:r="Invalid function arguments";break;case b.invalid_return_type:r="Invalid function return type";break;case b.invalid_date:r="Invalid date";break;case b.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:O.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case b.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case b.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case b.custom:r="Invalid input";break;case b.invalid_intersection_types:r="Intersection results could not be merged";break;case b.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case b.not_finite:r="Number must be finite";break;default:r=e.defaultError,O.assertNever(t)}return{message:r}},ye=Bs;var Xn=ye;function Ws(t){Xn=t}function lt(){return Xn}var kt=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let i="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)i=u(a,{data:e,defaultError:i}).message;return{...o,path:s,message:i}},Xs=[];function S(t,e){let r=lt(),n=kt({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===ye?void 0:ye].filter(o=>!!o)});t.common.issues.push(n)}var q=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return w;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,a=await o.value;n.push({key:s,value:a})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return w;s.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(n[s.value]=a.value)}return{status:e.value,value:n}}},w=Object.freeze({status:"aborted"}),Ue=t=>({status:"dirty",value:t}),Q=t=>({status:"valid",value:t}),Wt=t=>t.status==="aborted",Xt=t=>t.status==="dirty",Ie=t=>t.status==="valid",ut=t=>typeof Promise<"u"&&t instanceof Promise;var T;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(T||(T={}));var ie=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,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}},zn=(t,e)=>{if(Ie(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new re(t.common.issues);return this._error=r,this._error}}};function N(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(a,i)=>{let{message:c}=t;return a.code==="invalid_enum_value"?{message:c??i.defaultError}:typeof i.data>"u"?{message:c??n??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:c??r??i.defaultError}},description:o}}var C=class{get description(){return this._def.description}_getType(e){return me(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:me(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new q,ctx:{common:e.parent.common,data:e.data,parsedType:me(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ut(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:me(e)},o=this._parseSync({data:e,path:n.path,parent:n});return zn(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:me(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Ie(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Ie(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:me(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(ut(o)?o:Promise.resolve(o));return zn(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let a=e(o),i=()=>s.addIssue({code:b.custom,...n(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(i(),!1)):a?!0:(i(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new le({schema:this,typeName:A.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return ae.create(this,this._def)}nullable(){return ge.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Se.create(this)}promise(){return ke.create(this,this._def)}or(e){return Be.create([this,e],this._def)}and(e){return We.create(this,e,this._def)}transform(e){return new le({...N(this._def),schema:this,typeName:A.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Ye({...N(this._def),innerType:this,defaultValue:r,typeName:A.ZodDefault})}brand(){return new Ot({typeName:A.ZodBranded,type:this,...N(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new qe({...N(this._def),innerType:this,catchValue:r,typeName:A.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Rt.create(this,e)}readonly(){return Je.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},zs=/^c[^\s-]{8,}$/i,Ks=/^[0-9a-z]+$/,Zs=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ys=/^[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,qs=/^[a-z0-9_-]{21}$/i,Js=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Qs=/^[-+]?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)?)??$/,ea=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ta="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",qr,ra=/^(?:(?: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])$/,na=/^(?:(?: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])$/,oa=/^(([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]))$/,sa=/^(([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])$/,aa=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ia=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Zn="((\\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])))",la=new RegExp(`^${Zn}$`);function Yn(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function ua(t){return new RegExp(`^${Yn(t)}$`)}function qn(t){let e=`${Zn}T${Yn(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function ca(t,e){return!!((e==="v4"||!e)&&ra.test(t)||(e==="v6"||!e)&&oa.test(t))}function da(t,e){if(!Js.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function fa(t,e){return!!((e==="v4"||!e)&&na.test(t)||(e==="v6"||!e)&&sa.test(t))}var Ne=class t extends C{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==x.string){let s=this._getOrReturnCtx(e);return S(s,{code:b.invalid_type,expected:x.string,received:s.parsedType}),w}let n=new q,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),S(o,{code:b.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),S(o,{code:b.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let a=e.data.length>s.value,i=e.data.length<s.value;(a||i)&&(o=this._getOrReturnCtx(e,o),a?S(o,{code:b.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&S(o,{code:b.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")ea.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"email",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")qr||(qr=new RegExp(ta,"u")),qr.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"emoji",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Ys.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"uuid",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")qs.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"nanoid",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")zs.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"cuid",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")Ks.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"cuid2",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Zs.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"ulid",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),S(o,{validation:"url",code:b.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"regex",code:b.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),S(o,{code:b.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),S(o,{code:b.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),S(o,{code:b.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?qn(s).test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{code:b.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?la.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{code:b.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?ua(s).test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{code:b.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?Qs.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"duration",code:b.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?ca(e.data,s.version)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"ip",code:b.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?da(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"jwt",code:b.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?fa(e.data,s.version)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"cidr",code:b.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?aa.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"base64",code:b.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?ia.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"base64url",code:b.invalid_string,message:s.message}),n.dirty()):O.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:b.invalid_string,...T.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...T.errToObj(e)})}url(e){return this._addCheck({kind:"url",...T.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...T.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...T.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...T.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...T.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...T.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...T.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...T.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...T.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...T.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...T.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...T.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...T.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...T.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...T.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...T.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...T.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...T.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...T.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...T.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...T.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...T.errToObj(r)})}nonempty(e){return this.min(1,T.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Ne.create=t=>new Ne({checks:[],typeName:A.ZodString,coerce:t?.coerce??!1,...N(t)});function pa(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),a=Number.parseInt(e.toFixed(o).replace(".",""));return s%a/10**o}var Ge=class t extends C{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==x.number){let s=this._getOrReturnCtx(e);return S(s,{code:b.invalid_type,expected:x.number,received:s.parsedType}),w}let n,o=new q;for(let s of this._def.checks)s.kind==="int"?O.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{code:b.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),S(n,{code:b.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),S(n,{code:b.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?pa(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),S(n,{code:b.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{code:b.not_finite,message:s.message}),o.dirty()):O.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,T.toString(r))}gt(e,r){return this.setLimit("min",e,!1,T.toString(r))}lte(e,r){return this.setLimit("max",e,!0,T.toString(r))}lt(e,r){return this.setLimit("max",e,!1,T.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:T.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:T.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:T.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:T.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:T.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:T.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:T.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:T.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:T.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:T.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&O.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Ge.create=t=>new Ge({checks:[],typeName:A.ZodNumber,coerce:t?.coerce||!1,...N(t)});var Fe=class t extends C{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==x.bigint)return this._getInvalidInput(e);let n,o=new q;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),S(n,{code:b.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),S(n,{code:b.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),S(n,{code:b.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):O.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return S(r,{code:b.invalid_type,expected:x.bigint,received:r.parsedType}),w}gte(e,r){return this.setLimit("min",e,!0,T.toString(r))}gt(e,r){return this.setLimit("min",e,!1,T.toString(r))}lte(e,r){return this.setLimit("max",e,!0,T.toString(r))}lt(e,r){return this.setLimit("max",e,!1,T.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:T.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:T.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:T.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:T.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:T.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:T.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Fe.create=t=>new Fe({checks:[],typeName:A.ZodBigInt,coerce:t?.coerce??!1,...N(t)});var He=class extends C{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==x.boolean){let n=this._getOrReturnCtx(e);return S(n,{code:b.invalid_type,expected:x.boolean,received:n.parsedType}),w}return Q(e.data)}};He.create=t=>new He({typeName:A.ZodBoolean,coerce:t?.coerce||!1,...N(t)});var Ve=class t extends C{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==x.date){let s=this._getOrReturnCtx(e);return S(s,{code:b.invalid_type,expected:x.date,received:s.parsedType}),w}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return S(s,{code:b.invalid_date}),w}let n=new q,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),S(o,{code:b.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),S(o,{code:b.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):O.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:T.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:T.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Ve.create=t=>new Ve({checks:[],coerce:t?.coerce||!1,typeName:A.ZodDate,...N(t)});var dt=class extends C{_parse(e){if(this._getType(e)!==x.symbol){let n=this._getOrReturnCtx(e);return S(n,{code:b.invalid_type,expected:x.symbol,received:n.parsedType}),w}return Q(e.data)}};dt.create=t=>new dt({typeName:A.ZodSymbol,...N(t)});var $e=class extends C{_parse(e){if(this._getType(e)!==x.undefined){let n=this._getOrReturnCtx(e);return S(n,{code:b.invalid_type,expected:x.undefined,received:n.parsedType}),w}return Q(e.data)}};$e.create=t=>new $e({typeName:A.ZodUndefined,...N(t)});var je=class extends C{_parse(e){if(this._getType(e)!==x.null){let n=this._getOrReturnCtx(e);return S(n,{code:b.invalid_type,expected:x.null,received:n.parsedType}),w}return Q(e.data)}};je.create=t=>new je({typeName:A.ZodNull,...N(t)});var Ce=class extends C{constructor(){super(...arguments),this._any=!0}_parse(e){return Q(e.data)}};Ce.create=t=>new Ce({typeName:A.ZodAny,...N(t)});var be=class extends C{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Q(e.data)}};be.create=t=>new be({typeName:A.ZodUnknown,...N(t)});var ce=class extends C{_parse(e){let r=this._getOrReturnCtx(e);return S(r,{code:b.invalid_type,expected:x.never,received:r.parsedType}),w}};ce.create=t=>new ce({typeName:A.ZodNever,...N(t)});var ft=class extends C{_parse(e){if(this._getType(e)!==x.undefined){let n=this._getOrReturnCtx(e);return S(n,{code:b.invalid_type,expected:x.void,received:n.parsedType}),w}return Q(e.data)}};ft.create=t=>new ft({typeName:A.ZodVoid,...N(t)});var Se=class t extends C{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==x.array)return S(r,{code:b.invalid_type,expected:x.array,received:r.parsedType}),w;if(o.exactLength!==null){let a=r.data.length>o.exactLength.value,i=r.data.length<o.exactLength.value;(a||i)&&(S(r,{code:a?b.too_big:b.too_small,minimum:i?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(S(r,{code:b.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(S(r,{code:b.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,i)=>o.type._parseAsync(new ie(r,a,r.path,i)))).then(a=>q.mergeArray(n,a));let s=[...r.data].map((a,i)=>o.type._parseSync(new ie(r,a,r.path,i)));return q.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:T.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:T.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:T.toString(r)}})}nonempty(e){return this.min(1,e)}};Se.create=(t,e)=>new Se({type:t,minLength:null,maxLength:null,exactLength:null,typeName:A.ZodArray,...N(e)});function ct(t){if(t instanceof ne){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ae.create(ct(n))}return new ne({...t._def,shape:()=>e})}else return t instanceof Se?new Se({...t._def,type:ct(t.element)}):t instanceof ae?ae.create(ct(t.unwrap())):t instanceof ge?ge.create(ct(t.unwrap())):t instanceof he?he.create(t.items.map(e=>ct(e))):t}var ne=class t extends C{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=O.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==x.object){let u=this._getOrReturnCtx(e);return S(u,{code:b.invalid_type,expected:x.object,received:u.parsedType}),w}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof ce&&this._def.unknownKeys==="strip"))for(let u in o.data)a.includes(u)||i.push(u);let c=[];for(let u of a){let p=s[u],f=o.data[u];c.push({key:{status:"valid",value:u},value:p._parse(new ie(o,f,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof ce){let u=this._def.unknownKeys;if(u==="passthrough")for(let p of i)c.push({key:{status:"valid",value:p},value:{status:"valid",value:o.data[p]}});else if(u==="strict")i.length>0&&(S(o,{code:b.unrecognized_keys,keys:i}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let p of i){let f=o.data[p];c.push({key:{status:"valid",value:p},value:u._parse(new ie(o,f,o.path,p)),alwaysSet:p in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let p of c){let f=await p.key,v=await p.value;u.push({key:f,value:v,alwaysSet:p.alwaysSet})}return u}).then(u=>q.mergeObjectSync(n,u)):q.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return T.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:T.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:A.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of O.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of O.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return ct(this)}partial(e){let r={};for(let n of O.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of O.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof ae;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Jn(O.objectKeys(this.shape))}};ne.create=(t,e)=>new ne({shape:()=>t,unknownKeys:"strip",catchall:ce.create(),typeName:A.ZodObject,...N(e)});ne.strictCreate=(t,e)=>new ne({shape:()=>t,unknownKeys:"strict",catchall:ce.create(),typeName:A.ZodObject,...N(e)});ne.lazycreate=(t,e)=>new ne({shape:t,unknownKeys:"strip",catchall:ce.create(),typeName:A.ZodObject,...N(e)});var Be=class extends C{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let i of s)if(i.result.status==="valid")return i.result;for(let i of s)if(i.result.status==="dirty")return r.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map(i=>new re(i.ctx.common.issues));return S(r,{code:b.invalid_union,unionErrors:a}),w}if(r.common.async)return Promise.all(n.map(async s=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(o);{let s,a=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},p=c._parseSync({data:r.data,path:r.path,parent:u});if(p.status==="valid")return p;p.status==="dirty"&&!s&&(s={result:p,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let i=a.map(c=>new re(c));return S(r,{code:b.invalid_union,unionErrors:i}),w}}get options(){return this._def.options}};Be.create=(t,e)=>new Be({options:t,typeName:A.ZodUnion,...N(e)});var Ee=t=>t instanceof Xe?Ee(t.schema):t instanceof le?Ee(t.innerType()):t instanceof ze?[t.value]:t instanceof Ke?t.options:t instanceof Ze?O.objectValues(t.enum):t instanceof Ye?Ee(t._def.innerType):t instanceof $e?[void 0]:t instanceof je?[null]:t instanceof ae?[void 0,...Ee(t.unwrap())]:t instanceof ge?[null,...Ee(t.unwrap())]:t instanceof Ot||t instanceof Je?Ee(t.unwrap()):t instanceof qe?Ee(t._def.innerType):[],zt=class t extends C{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==x.object)return S(r,{code:b.invalid_type,expected:x.object,received:r.parsedType}),w;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(S(r,{code:b.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),w)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let a=Ee(s.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of a){if(o.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);o.set(i,s)}}return new t({typeName:A.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...N(n)})}};function Jr(t,e){let r=me(t),n=me(e);if(t===e)return{valid:!0,data:t};if(r===x.object&&n===x.object){let o=O.objectKeys(e),s=O.objectKeys(t).filter(i=>o.indexOf(i)!==-1),a={...t,...e};for(let i of s){let c=Jr(t[i],e[i]);if(!c.valid)return{valid:!1};a[i]=c.data}return{valid:!0,data:a}}else if(r===x.array&&n===x.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let a=t[s],i=e[s],c=Jr(a,i);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===x.date&&n===x.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var We=class extends C{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,a)=>{if(Wt(s)||Wt(a))return w;let i=Jr(s.value,a.value);return i.valid?((Xt(s)||Xt(a))&&r.dirty(),{status:r.value,value:i.data}):(S(n,{code:b.invalid_intersection_types}),w)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};We.create=(t,e,r)=>new We({left:t,right:e,typeName:A.ZodIntersection,...N(r)});var he=class t extends C{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==x.array)return S(n,{code:b.invalid_type,expected:x.array,received:n.parsedType}),w;if(n.data.length<this._def.items.length)return S(n,{code:b.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w;!this._def.rest&&n.data.length>this._def.items.length&&(S(n,{code:b.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((a,i)=>{let c=this._def.items[i]||this._def.rest;return c?c._parse(new ie(n,a,n.path,i)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>q.mergeArray(r,a)):q.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};he.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new he({items:t,typeName:A.ZodTuple,rest:null,...N(e)})};var Kt=class t extends C{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==x.object)return S(n,{code:b.invalid_type,expected:x.object,received:n.parsedType}),w;let o=[],s=this._def.keyType,a=this._def.valueType;for(let i in n.data)o.push({key:s._parse(new ie(n,i,n.path,i)),value:a._parse(new ie(n,n.data[i],n.path,i)),alwaysSet:i in n.data});return n.common.async?q.mergeObjectAsync(r,o):q.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof C?new t({keyType:e,valueType:r,typeName:A.ZodRecord,...N(n)}):new t({keyType:Ne.create(),valueType:e,typeName:A.ZodRecord,...N(r)})}},pt=class extends C{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==x.map)return S(n,{code:b.invalid_type,expected:x.map,received:n.parsedType}),w;let o=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([i,c],u)=>({key:o._parse(new ie(n,i,n.path,[u,"key"])),value:s._parse(new ie(n,c,n.path,[u,"value"]))}));if(n.common.async){let i=new Map;return Promise.resolve().then(async()=>{for(let c of a){let u=await c.key,p=await c.value;if(u.status==="aborted"||p.status==="aborted")return w;(u.status==="dirty"||p.status==="dirty")&&r.dirty(),i.set(u.value,p.value)}return{status:r.value,value:i}})}else{let i=new Map;for(let c of a){let u=c.key,p=c.value;if(u.status==="aborted"||p.status==="aborted")return w;(u.status==="dirty"||p.status==="dirty")&&r.dirty(),i.set(u.value,p.value)}return{status:r.value,value:i}}}};pt.create=(t,e,r)=>new pt({valueType:e,keyType:t,typeName:A.ZodMap,...N(r)});var mt=class t extends C{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==x.set)return S(n,{code:b.invalid_type,expected:x.set,received:n.parsedType}),w;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(S(n,{code:b.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(S(n,{code:b.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function a(c){let u=new Set;for(let p of c){if(p.status==="aborted")return w;p.status==="dirty"&&r.dirty(),u.add(p.value)}return{status:r.value,value:u}}let i=[...n.data.values()].map((c,u)=>s._parse(new ie(n,c,n.path,u)));return n.common.async?Promise.all(i).then(c=>a(c)):a(i)}min(e,r){return new t({...this._def,minSize:{value:e,message:T.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:T.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};mt.create=(t,e)=>new mt({valueType:t,minSize:null,maxSize:null,typeName:A.ZodSet,...N(e)});var Zt=class t extends C{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==x.function)return S(r,{code:b.invalid_type,expected:x.function,received:r.parsedType}),w;function n(i,c){return kt({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,lt(),ye].filter(u=>!!u),issueData:{code:b.invalid_arguments,argumentsError:c}})}function o(i,c){return kt({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,lt(),ye].filter(u=>!!u),issueData:{code:b.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof ke){let i=this;return Q(async function(...c){let u=new re([]),p=await i._def.args.parseAsync(c,s).catch(d=>{throw u.addIssue(n(c,d)),u}),f=await Reflect.apply(a,this,p);return await i._def.returns._def.type.parseAsync(f,s).catch(d=>{throw u.addIssue(o(f,d)),u})})}else{let i=this;return Q(function(...c){let u=i._def.args.safeParse(c,s);if(!u.success)throw new re([n(c,u.error)]);let p=Reflect.apply(a,this,u.data),f=i._def.returns.safeParse(p,s);if(!f.success)throw new re([o(p,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:he.create(e).rest(be.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||he.create([]).rest(be.create()),returns:r||be.create(),typeName:A.ZodFunction,...N(n)})}},Xe=class extends C{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Xe.create=(t,e)=>new Xe({getter:t,typeName:A.ZodLazy,...N(e)});var ze=class extends C{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return S(r,{received:r.data,code:b.invalid_literal,expected:this._def.value}),w}return{status:"valid",value:e.data}}get value(){return this._def.value}};ze.create=(t,e)=>new ze({value:t,typeName:A.ZodLiteral,...N(e)});function Jn(t,e){return new Ke({values:t,typeName:A.ZodEnum,...N(e)})}var Ke=class t extends C{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return S(r,{expected:O.joinValues(n),received:r.parsedType,code:b.invalid_type}),w}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return S(r,{received:r.data,code:b.invalid_enum_value,options:n}),w}return Q(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Ke.create=Jn;var Ze=class extends C{_parse(e){let r=O.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==x.string&&n.parsedType!==x.number){let o=O.objectValues(r);return S(n,{expected:O.joinValues(o),received:n.parsedType,code:b.invalid_type}),w}if(this._cache||(this._cache=new Set(O.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=O.objectValues(r);return S(n,{received:n.data,code:b.invalid_enum_value,options:o}),w}return Q(e.data)}get enum(){return this._def.values}};Ze.create=(t,e)=>new Ze({values:t,typeName:A.ZodNativeEnum,...N(e)});var ke=class extends C{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==x.promise&&r.common.async===!1)return S(r,{code:b.invalid_type,expected:x.promise,received:r.parsedType}),w;let n=r.parsedType===x.promise?r.data:Promise.resolve(r.data);return Q(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ke.create=(t,e)=>new ke({type:t,typeName:A.ZodPromise,...N(e)});var le=class extends C{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===A.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:a=>{S(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let a=o.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async i=>{if(r.value==="aborted")return w;let c=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});return c.status==="aborted"?w:c.status==="dirty"?Ue(c.value):r.value==="dirty"?Ue(c.value):c});{if(r.value==="aborted")return w;let i=this._def.schema._parseSync({data:a,path:n.path,parent:n});return i.status==="aborted"?w:i.status==="dirty"?Ue(i.value):r.value==="dirty"?Ue(i.value):i}}if(o.type==="refinement"){let a=i=>{let c=o.refinement(i,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?w:(i.status==="dirty"&&r.dirty(),a(i.value),{status:r.value,value:i.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>i.status==="aborted"?w:(i.status==="dirty"&&r.dirty(),a(i.value).then(()=>({status:r.value,value:i.value}))))}if(o.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Ie(a))return w;let i=o.transform(a.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:i}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Ie(a)?Promise.resolve(o.transform(a.value,s)).then(i=>({status:r.value,value:i})):w);O.assertNever(o)}};le.create=(t,e,r)=>new le({schema:t,typeName:A.ZodEffects,effect:e,...N(r)});le.createWithPreprocess=(t,e,r)=>new le({schema:e,effect:{type:"preprocess",transform:t},typeName:A.ZodEffects,...N(r)});var ae=class extends C{_parse(e){return this._getType(e)===x.undefined?Q(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ae.create=(t,e)=>new ae({innerType:t,typeName:A.ZodOptional,...N(e)});var ge=class extends C{_parse(e){return this._getType(e)===x.null?Q(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ge.create=(t,e)=>new ge({innerType:t,typeName:A.ZodNullable,...N(e)});var Ye=class extends C{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===x.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Ye.create=(t,e)=>new Ye({innerType:t,typeName:A.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...N(e)});var qe=class extends C{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ut(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new re(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new re(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};qe.create=(t,e)=>new qe({innerType:t,typeName:A.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...N(e)});var ht=class extends C{_parse(e){if(this._getType(e)!==x.nan){let n=this._getOrReturnCtx(e);return S(n,{code:b.invalid_type,expected:x.nan,received:n.parsedType}),w}return{status:"valid",value:e.data}}};ht.create=t=>new ht({typeName:A.ZodNaN,...N(t)});var ma=Symbol("zod_brand"),Ot=class extends C{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Rt=class t extends C{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?w:s.status==="dirty"?(r.dirty(),Ue(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?w:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:A.ZodPipeline})}},Je=class extends C{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Ie(o)&&(o.value=Object.freeze(o.value)),o);return ut(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Je.create=(t,e)=>new Je({innerType:t,typeName:A.ZodReadonly,...N(e)});function Kn(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Qn(t,e={},r){return t?Ce.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(a=>{if(!a){let i=Kn(e,n),c=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:c})}});if(!s){let a=Kn(e,n),i=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:i})}}):Ce.create()}var ha={object:ne.lazycreate},A;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(A||(A={}));var ga=(t,e={message:`Input not instance of ${t.name}`})=>Qn(r=>r instanceof t,e),eo=Ne.create,to=Ge.create,_a=ht.create,va=Fe.create,ro=He.create,ya=Ve.create,Ea=dt.create,ba=$e.create,Sa=je.create,xa=Ce.create,Ta=be.create,wa=ce.create,Aa=ft.create,Ia=Se.create,Na=ne.create,Ca=ne.strictCreate,ka=Be.create,Oa=zt.create,Ra=We.create,Pa=he.create,Ma=Kt.create,La=pt.create,Da=mt.create,Ua=Zt.create,Ga=Xe.create,Fa=ze.create,Ha=Ke.create,Va=Ze.create,$a=ke.create,ja=le.create,Ba=ae.create,Wa=ge.create,Xa=le.createWithPreprocess,za=Rt.create,Ka=()=>eo().optional(),Za=()=>to().optional(),Ya=()=>ro().optional(),qa={string:(t=>Ne.create({...t,coerce:!0})),number:(t=>Ge.create({...t,coerce:!0})),boolean:(t=>He.create({...t,coerce:!0})),bigint:(t=>Fe.create({...t,coerce:!0})),date:(t=>Ve.create({...t,coerce:!0}))};var Ja=w;var Qa=l.object({name:l.string(),arguments:l.string()}),ei=l.object({id:l.string(),type:l.literal("function"),function:Qa,encryptedValue:l.string().optional()}),Yt=l.object({id:l.string(),role:l.string(),content:l.string().optional(),name:l.string().optional(),encryptedValue:l.string().optional()}),ti=l.object({type:l.literal("text"),text:l.string()}),ri=l.object({type:l.literal("data"),value:l.string(),mimeType:l.string()}),ni=l.object({type:l.literal("url"),value:l.string(),mimeType:l.string().optional()}),qt=l.discriminatedUnion("type",[ri,ni]),oi=l.object({type:l.literal("image"),source:qt,metadata:l.unknown().optional()}),si=l.object({type:l.literal("audio"),source:qt,metadata:l.unknown().optional()}),ai=l.object({type:l.literal("video"),source:qt,metadata:l.unknown().optional()}),ii=l.object({type:l.literal("document"),source:qt,metadata:l.unknown().optional()});var no=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()}),oo=(t,e)=>{!t.id&&!t.url&&!t.data&&e.addIssue({code:l.ZodIssueCode.custom,message:"BinaryInputContent requires at least one of id, url, or data.",path:["id"]})},wc=no.superRefine((t,e)=>{oo(t,e)}),li=l.discriminatedUnion("type",[ti,oi,si,ai,ii,no]),ui=li.superRefine((t,e)=>{t.type==="binary"&&oo(t,e)}),ci=Yt.extend({role:l.literal("developer"),content:l.string()}),di=Yt.extend({role:l.literal("system"),content:l.string()}),fi=Yt.extend({role:l.literal("assistant"),content:l.string().optional(),toolCalls:l.array(ei).optional()}),pi=Yt.extend({role:l.literal("user"),content:l.union([l.string(),l.array(ui)])}),mi=l.object({id:l.string(),content:l.string(),role:l.literal("tool"),toolCallId:l.string(),error:l.string().optional(),encryptedValue:l.string().optional()}),hi=l.object({id:l.string(),role:l.literal("activity"),activityType:l.string(),content:l.record(l.any())}),gi=l.object({id:l.string(),role:l.literal("reasoning"),content:l.string(),encryptedValue:l.string().optional()}),so=l.discriminatedUnion("role",[ci,di,fi,pi,mi,hi,gi]),Ac=l.union([l.literal("developer"),l.literal("system"),l.literal("assistant"),l.literal("user"),l.literal("tool"),l.literal("activity"),l.literal("reasoning")]),_i=l.object({description:l.string(),value:l.string()}),ao=l.object({name:l.string(),description:l.string(),parameters:l.any(),metadata:l.record(l.any()).optional()}),vi=l.object({threadId:l.string(),runId:l.string(),parentRunId:l.string().optional(),state:l.any(),messages:l.array(so),tools:l.array(ao),context:l.array(_i),forwardedProps:l.any()}),yi=l.any(),F=class extends Error{constructor(t){super(t)}},Qr=class extends F{constructor(){super("Connect not implemented. This method is not supported by the current agent.")}},Ei=l.object({name:l.string(),description:l.string().optional()}),bi=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()}),Si=l.object({streaming:l.boolean().optional(),websocket:l.boolean().optional(),httpBinary:l.boolean().optional(),pushNotifications:l.boolean().optional(),resumable:l.boolean().optional()}),xi=l.object({supported:l.boolean().optional(),items:l.array(ao).optional(),parallelCalls:l.boolean().optional(),clientProvided:l.boolean().optional()}),Ti=l.object({structuredOutput:l.boolean().optional(),supportedMimeTypes:l.array(l.string()).optional()}),wi=l.object({snapshots:l.boolean().optional(),deltas:l.boolean().optional(),memory:l.boolean().optional(),persistentState:l.boolean().optional()}),Ai=l.object({supported:l.boolean().optional(),delegation:l.boolean().optional(),handoffs:l.boolean().optional(),subAgents:l.array(Ei).optional()}),Ii=l.object({supported:l.boolean().optional(),streaming:l.boolean().optional(),encrypted:l.boolean().optional()}),Ni=l.object({image:l.boolean().optional(),audio:l.boolean().optional(),video:l.boolean().optional(),pdf:l.boolean().optional(),file:l.boolean().optional()}),Ci=l.object({image:l.boolean().optional(),audio:l.boolean().optional()}),ki=l.object({input:Ni.optional(),output:Ci.optional()}),Oi=l.object({codeExecution:l.boolean().optional(),sandboxed:l.boolean().optional(),maxIterations:l.number().optional(),maxExecutionTime:l.number().optional()}),Ri=l.object({supported:l.boolean().optional(),approvals:l.boolean().optional(),interventions:l.boolean().optional(),feedback:l.boolean().optional()}),Ic=l.object({identity:bi.optional(),transport:Si.optional(),tools:xi.optional(),output:Ti.optional(),state:wi.optional(),multiAgent:Ai.optional(),reasoning:Ii.optional(),multimodal:ki.optional(),execution:Oi.optional(),humanInTheLoop:Ri.optional(),custom:l.record(l.unknown()).optional()}),io=l.union([l.literal("developer"),l.literal("system"),l.literal("assistant"),l.literal("user")]),g=(function(t){return t.TEXT_MESSAGE_START="TEXT_MESSAGE_START",t.TEXT_MESSAGE_CONTENT="TEXT_MESSAGE_CONTENT",t.TEXT_MESSAGE_END="TEXT_MESSAGE_END",t.TEXT_MESSAGE_CHUNK="TEXT_MESSAGE_CHUNK",t.TOOL_CALL_START="TOOL_CALL_START",t.TOOL_CALL_ARGS="TOOL_CALL_ARGS",t.TOOL_CALL_END="TOOL_CALL_END",t.TOOL_CALL_CHUNK="TOOL_CALL_CHUNK",t.TOOL_CALL_RESULT="TOOL_CALL_RESULT",t.THINKING_START="THINKING_START",t.THINKING_END="THINKING_END",t.THINKING_TEXT_MESSAGE_START="THINKING_TEXT_MESSAGE_START",t.THINKING_TEXT_MESSAGE_CONTENT="THINKING_TEXT_MESSAGE_CONTENT",t.THINKING_TEXT_MESSAGE_END="THINKING_TEXT_MESSAGE_END",t.STATE_SNAPSHOT="STATE_SNAPSHOT",t.STATE_DELTA="STATE_DELTA",t.MESSAGES_SNAPSHOT="MESSAGES_SNAPSHOT",t.ACTIVITY_SNAPSHOT="ACTIVITY_SNAPSHOT",t.ACTIVITY_DELTA="ACTIVITY_DELTA",t.RAW="RAW",t.CUSTOM="CUSTOM",t.RUN_STARTED="RUN_STARTED",t.RUN_FINISHED="RUN_FINISHED",t.RUN_ERROR="RUN_ERROR",t.STEP_STARTED="STEP_STARTED",t.STEP_FINISHED="STEP_FINISHED",t.REASONING_START="REASONING_START",t.REASONING_MESSAGE_START="REASONING_MESSAGE_START",t.REASONING_MESSAGE_CONTENT="REASONING_MESSAGE_CONTENT",t.REASONING_MESSAGE_END="REASONING_MESSAGE_END",t.REASONING_MESSAGE_CHUNK="REASONING_MESSAGE_CHUNK",t.REASONING_END="REASONING_END",t.REASONING_ENCRYPTED_VALUE="REASONING_ENCRYPTED_VALUE",t})({}),P=l.object({type:l.nativeEnum(g),timestamp:l.number().optional(),rawEvent:l.any().optional()}).passthrough(),Pi=P.extend({type:l.literal(g.TEXT_MESSAGE_START),messageId:l.string(),role:io.default("assistant"),name:l.string().optional()}),lo=P.extend({type:l.literal(g.TEXT_MESSAGE_CONTENT),messageId:l.string(),delta:l.string()}),Mi=P.extend({type:l.literal(g.TEXT_MESSAGE_END),messageId:l.string()}),Li=P.extend({type:l.literal(g.TEXT_MESSAGE_CHUNK),messageId:l.string().optional(),role:io.optional(),delta:l.string().optional(),name:l.string().optional()}),Di=P.extend({type:l.literal(g.THINKING_TEXT_MESSAGE_START)}),Ui=lo.omit({messageId:!0,type:!0}).extend({type:l.literal(g.THINKING_TEXT_MESSAGE_CONTENT)}),Gi=P.extend({type:l.literal(g.THINKING_TEXT_MESSAGE_END)}),Fi=P.extend({type:l.literal(g.TOOL_CALL_START),toolCallId:l.string(),toolCallName:l.string(),parentMessageId:l.string().optional()}),Hi=P.extend({type:l.literal(g.TOOL_CALL_ARGS),toolCallId:l.string(),delta:l.string()}),Vi=P.extend({type:l.literal(g.TOOL_CALL_END),toolCallId:l.string()}),$i=P.extend({messageId:l.string(),type:l.literal(g.TOOL_CALL_RESULT),toolCallId:l.string(),content:l.string(),role:l.literal("tool").optional()}),ji=P.extend({type:l.literal(g.TOOL_CALL_CHUNK),toolCallId:l.string().optional(),toolCallName:l.string().optional(),parentMessageId:l.string().optional(),delta:l.string().optional()}),Bi=P.extend({type:l.literal(g.THINKING_START),title:l.string().optional()}),Wi=P.extend({type:l.literal(g.THINKING_END)}),Xi=P.extend({type:l.literal(g.STATE_SNAPSHOT),snapshot:yi}),zi=P.extend({type:l.literal(g.STATE_DELTA),delta:l.array(l.any())}),Ki=P.extend({type:l.literal(g.MESSAGES_SNAPSHOT),messages:l.array(so)}),Zi=P.extend({type:l.literal(g.ACTIVITY_SNAPSHOT),messageId:l.string(),activityType:l.string(),content:l.record(l.any()),replace:l.boolean().optional().default(!0)}),Yi=P.extend({type:l.literal(g.ACTIVITY_DELTA),messageId:l.string(),activityType:l.string(),patch:l.array(l.any())}),qi=P.extend({type:l.literal(g.RAW),event:l.any(),source:l.string().optional()}),Ji=P.extend({type:l.literal(g.CUSTOM),name:l.string(),value:l.any()}),Qi=P.extend({type:l.literal(g.RUN_STARTED),threadId:l.string(),runId:l.string(),parentRunId:l.string().optional(),input:vi.optional()}),el=P.extend({type:l.literal(g.RUN_FINISHED),threadId:l.string(),runId:l.string(),result:l.any().optional()}),tl=P.extend({type:l.literal(g.RUN_ERROR),message:l.string(),code:l.string().optional()}),rl=P.extend({type:l.literal(g.STEP_STARTED),stepName:l.string()}),nl=P.extend({type:l.literal(g.STEP_FINISHED),stepName:l.string()}),ol=l.union([l.literal("tool-call"),l.literal("message")]),sl=P.extend({type:l.literal(g.REASONING_START),messageId:l.string()}),al=P.extend({type:l.literal(g.REASONING_MESSAGE_START),messageId:l.string(),role:l.literal("reasoning")}),il=P.extend({type:l.literal(g.REASONING_MESSAGE_CONTENT),messageId:l.string(),delta:l.string()}),ll=P.extend({type:l.literal(g.REASONING_MESSAGE_END),messageId:l.string()}),ul=P.extend({type:l.literal(g.REASONING_MESSAGE_CHUNK),messageId:l.string().optional(),delta:l.string().optional()}),cl=P.extend({type:l.literal(g.REASONING_END),messageId:l.string()}),dl=P.extend({type:l.literal(g.REASONING_ENCRYPTED_VALUE),subtype:ol,entityId:l.string(),encryptedValue:l.string()}),uo=l.discriminatedUnion("type",[Pi,lo,Mi,Li,Bi,Wi,Di,Ui,Gi,Fi,Hi,Vi,ji,$i,Xi,zi,Ki,Zi,Yi,qi,Ji,Qi,el,tl,rl,nl,sl,al,il,ll,ul,cl,dl]);var en={};Bt(en,{JsonPatchError:()=>W,_areEquals:()=>Lt,applyOperation:()=>Qe,applyPatch:()=>Oe,applyReducer:()=>gl,deepClone:()=>ml,getValueByPointer:()=>rr,validate:()=>fo,validator:()=>nr});var fl=(function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var s in o)o.hasOwnProperty(s)&&(n[s]=o[s])},t(e,r)};return function(e,r){t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),pl=Object.prototype.hasOwnProperty;function Qt(t,e){return pl.call(t,e)}function er(t){if(Array.isArray(t)){for(var e=new Array(t.length),r=0;r<e.length;r++)e[r]=""+r;return e}if(Object.keys)return Object.keys(t);var n=[];for(var o in t)Qt(t,o)&&n.push(o);return n}function J(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function tr(t){for(var e=0,r=t.length,n;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function _e(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function Pt(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Jt(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,r=t.length;e<r;e++)if(Jt(t[e]))return!0}else if(typeof t=="object"){for(var n=er(t),o=n.length,s=0;s<o;s++)if(Jt(t[n[s]]))return!0}}return!1}function co(t,e){var r=[t];for(var n in e){var o=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof o<"u"&&r.push(n+": "+o)}return r.join(`
2
- `)}var Mt=(function(t){fl(e,t);function e(r,n,o,s,a){var i=this.constructor,c=t.call(this,co(r,{name:n,index:o,operation:s,tree:a}))||this;return c.name=n,c.index=o,c.operation=s,c.tree=a,Object.setPrototypeOf(c,i.prototype),c.message=co(r,{name:n,index:o,operation:s,tree:a}),c}return e})(Error);var W=Mt,ml=J,gt={add:function(t,e,r){return t[e]=this.value,{newDocument:r}},remove:function(t,e,r){var n=t[e];return delete t[e],{newDocument:r,removed:n}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:function(t,e,r){var n=rr(r,this.path);n&&(n=J(n));var o=Qe(r,{op:"remove",path:this.from}).removed;return Qe(r,{op:"add",path:this.path,value:o}),{newDocument:r,removed:n}},copy:function(t,e,r){var n=rr(r,this.from);return Qe(r,{op:"add",path:this.path,value:J(n)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:Lt(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}},hl={add:function(t,e,r){return tr(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},remove:function(t,e,r){var n=t.splice(e,1);return{newDocument:r,removed:n[0]}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:gt.move,copy:gt.copy,test:gt.test,_get:gt._get};function rr(t,e){if(e=="")return t;var r={op:"_get",path:e};return Qe(t,r),r.value}function Qe(t,e,r,n,o,s){if(r===void 0&&(r=!1),n===void 0&&(n=!0),o===void 0&&(o=!0),s===void 0&&(s=0),r&&(typeof r=="function"?r(e,0,t,e.path):nr(e,0)),e.path===""){var a={newDocument:t};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=t,a;if(e.op==="move"||e.op==="copy")return a.newDocument=rr(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=Lt(t,e.value),a.test===!1)throw new W("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return a.newDocument=t,a}else{if(e.op==="remove")return a.removed=t,a.newDocument=null,a;if(e.op==="_get")return e.value=t,a;if(r)throw new W("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,t);return a}}else{n||(t=J(t));var i=e.path||"",c=i.split("/"),u=t,p=1,f=c.length,v=void 0,d=void 0,m=void 0;for(typeof r=="function"?m=r:m=nr;;){if(d=c[p],d&&d.indexOf("~")!=-1&&(d=Pt(d)),o&&(d=="__proto__"||d=="prototype"&&p>0&&c[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(r&&v===void 0&&(u[d]===void 0?v=c.slice(0,p).join("/"):p==f-1&&(v=e.path),v!==void 0&&m(e,0,t,v)),p++,Array.isArray(u)){if(d==="-")d=u.length;else{if(r&&!tr(d))throw new W("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,t);tr(d)&&(d=~~d)}if(p>=f){if(r&&e.op==="add"&&d>u.length)throw new W("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,t);var a=hl[e.op].call(e,u,d,t);if(a.test===!1)throw new W("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return a}}else if(p>=f){var a=gt[e.op].call(e,u,d,t);if(a.test===!1)throw new W("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return a}if(u=u[d],r&&p<f&&(!u||typeof u!="object"))throw new W("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,t)}}}function Oe(t,e,r,n,o){if(n===void 0&&(n=!0),o===void 0&&(o=!0),r&&!Array.isArray(e))throw new W("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=J(t));for(var s=new Array(e.length),a=0,i=e.length;a<i;a++)s[a]=Qe(t,e[a],r,!0,o,a),t=s[a].newDocument;return s.newDocument=t,s}function gl(t,e,r){var n=Qe(t,e);if(n.test===!1)throw new W("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function nr(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new W("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(gt[t.op]){if(typeof t.path!="string")throw new W("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new W('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new W("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new W("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&Jt(t.value))throw new W("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var o=t.path.split("/").length,s=n.split("/").length;if(o!==s+1&&o!==s)throw new W("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new W("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var a={op:"_get",path:t.from,value:void 0},i=fo([a],r);if(i&&i.name==="OPERATION_PATH_UNRESOLVABLE")throw new W("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new W("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function fo(t,e,r){try{if(!Array.isArray(t))throw new W("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Oe(J(e),J(t),r||!0);else{r=r||nr;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(o){if(o instanceof W)return o;throw o}}function Lt(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=Array.isArray(t),n=Array.isArray(e),o,s,a;if(r&&n){if(s=t.length,s!=e.length)return!1;for(o=s;o--!==0;)if(!Lt(t[o],e[o]))return!1;return!0}if(r!=n)return!1;var i=Object.keys(t);if(s=i.length,s!==Object.keys(e).length)return!1;for(o=s;o--!==0;)if(!e.hasOwnProperty(i[o]))return!1;for(o=s;o--!==0;)if(a=i[o],!Lt(t[a],e[a]))return!1;return!0}return t!==t&&e!==e}var on={};Bt(on,{compare:()=>Tl,generate:()=>tn,observe:()=>xl,unobserve:()=>Sl});var rn=new WeakMap,_l=(function(){function t(e){this.observers=new Map,this.obj=e}return t})(),vl=(function(){function t(e,r){this.callback=e,this.observer=r}return t})();function yl(t){return rn.get(t)}function El(t,e){return t.observers.get(e)}function bl(t,e){t.observers.delete(e.callback)}function Sl(t,e){e.unobserve()}function xl(t,e){var r=[],n,o=yl(t);if(!o)o=new _l(t),rn.set(t,o);else{var s=El(o,e);n=s&&s.observer}if(n)return n;if(n={},o.value=J(t),e){n.callback=e,n.next=null;var a=function(){tn(n)},i=function(){clearTimeout(n.next),n.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",i),window.addEventListener("keyup",i),window.addEventListener("mousedown",i),window.addEventListener("keydown",i),window.addEventListener("change",i))}return n.patches=r,n.object=t,n.unobserve=function(){tn(n),clearTimeout(n.next),bl(o,n),typeof window<"u"&&(window.removeEventListener("mouseup",i),window.removeEventListener("keyup",i),window.removeEventListener("mousedown",i),window.removeEventListener("keydown",i),window.removeEventListener("change",i))},o.observers.set(e,new vl(e,n)),n}function tn(t,e){e===void 0&&(e=!1);var r=rn.get(t.object);nn(r.value,t.object,t.patches,"",e),t.patches.length&&Oe(r.value,t.patches);var n=t.patches;return n.length>0&&(t.patches=[],t.callback&&t.callback(n)),n}function nn(t,e,r,n,o){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=er(e),a=er(t),i=!1,c=!1,u=a.length-1;u>=0;u--){var p=a[u],f=t[p];if(Qt(e,p)&&!(e[p]===void 0&&f!==void 0&&Array.isArray(e)===!1)){var v=e[p];typeof f=="object"&&f!=null&&typeof v=="object"&&v!=null&&Array.isArray(f)===Array.isArray(v)?nn(f,v,r,n+"/"+_e(p),o):f!==v&&(i=!0,o&&r.push({op:"test",path:n+"/"+_e(p),value:J(f)}),r.push({op:"replace",path:n+"/"+_e(p),value:J(v)}))}else Array.isArray(t)===Array.isArray(e)?(o&&r.push({op:"test",path:n+"/"+_e(p),value:J(f)}),r.push({op:"remove",path:n+"/"+_e(p)}),c=!0):(o&&r.push({op:"test",path:n,value:t}),r.push({op:"replace",path:n,value:e}),i=!0)}if(!(!c&&s.length==a.length))for(var u=0;u<s.length;u++){var p=s[u];!Qt(t,p)&&e[p]!==void 0&&r.push({op:"add",path:n+"/"+_e(p),value:J(e[p])})}}}function Tl(t,e,r){r===void 0&&(r=!1);var n=[];return nn(t,e,n,"",r),n}var Dc=Object.assign({},en,on,{JsonPatchError:Mt,deepClone:J,escapePathComponent:_e,unescapePathComponent:Pt});var sn=function(t,e){return sn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[o]=n[o])},sn(t,e)};function ve(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");sn(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function po(t,e,r,n){function o(s){return s instanceof r?s:new r(function(a){a(s)})}return new(r||(r=Promise))(function(s,a){function i(p){try{u(n.next(p))}catch(f){a(f)}}function c(p){try{u(n.throw(p))}catch(f){a(f)}}function u(p){p.done?s(p.value):o(p.value).then(i,c)}u((n=n.apply(t,e||[])).next())})}function or(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,o,s,a=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return a.next=i(0),a.throw=i(1),a.return=i(2),typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function i(u){return function(p){return c([u,p])}}function c(u){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,u[0]&&(r=0)),r;)try{if(n=1,o&&(s=u[0]&2?o.return:u[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,u[1])).done)return s;switch(o=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,o=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){r.label=u[1];break}if(u[0]===6&&r.label<s[1]){r.label=s[1],s=u;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(u);break}s[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(p){u=[6,p],o=0}finally{n=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function xe(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function _t(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,s=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s}function vt(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,s;n<o;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))}function et(t){return this instanceof et?(this.v=t,this):new et(t)}function mo(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),i("next"),i("throw"),i("return",a),o[Symbol.asyncIterator]=function(){return this},o;function a(d){return function(m){return Promise.resolve(m).then(d,f)}}function i(d,m){n[d]&&(o[d]=function(h){return new Promise(function(y,E){s.push([d,h,y,E])>1||c(d,h)})},m&&(o[d]=m(o[d])))}function c(d,m){try{u(n[d](m))}catch(h){v(s[0][3],h)}}function u(d){d.value instanceof et?Promise.resolve(d.value.v).then(p,f):v(s[0][2],d)}function p(d){c("next",d)}function f(d){c("throw",d)}function v(d,m){d(m),s.shift(),s.length&&c(s[0][0],s[0][1])}}function ho(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof xe=="function"?xe(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(a){return new Promise(function(i,c){a=t[s](a),o(i,c,a.done,a.value)})}}function o(s,a,i,c){Promise.resolve(c).then(function(u){s({value:u,done:i})},a)}}function k(t){return typeof t=="function"}function yt(t){var e=function(n){Error.call(n),n.stack=new Error().stack},r=t(e);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var sr=yt(function(t){return function(r){t(this),this.message=r?r.length+` errors occurred during unsubscription:
1
+ "use strict";var SurogatesWidget=(()=>{var zr=Object.defineProperty;var Fs=Object.getOwnPropertyDescriptor;var Hs=Object.getOwnPropertyNames;var Vs=Object.prototype.hasOwnProperty;var Bt=(t,e)=>{for(var r in e)zr(t,r,{get:e[r],enumerable:!0})},$s=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Hs(e))!Vs.call(t,o)&&o!==r&&zr(t,o,{get:()=>e[o],enumerable:!(n=Fs(e,o))||n.enumerable});return t};var js=t=>$s(zr({},"__esModule",{value:!0}),t);var Wu={};Bt(Wu,{AbstractAgent:()=>Rr,EventType:()=>g,PROTOCOL_VERSION:()=>Wo,SDK_VERSION:()=>Or,SURG_EVENT:()=>D,SurogatesAuthError:()=>ce,SurogatesError:()=>Pe,SurogatesNetworkError:()=>Le,SurogatesProtocolError:()=>ye,SurogatesRateLimitError:()=>Me,Translator:()=>at,WebsiteAgent:()=>wt,mount:()=>Xr,mountWithPairing:()=>Ds});var Y=[];for(let t=0;t<256;++t)Y.push((t+256).toString(16).slice(1));function Xn(t,e=0){return(Y[t[e+0]]+Y[t[e+1]]+Y[t[e+2]]+Y[t[e+3]]+"-"+Y[t[e+4]]+Y[t[e+5]]+"-"+Y[t[e+6]]+Y[t[e+7]]+"-"+Y[t[e+8]]+Y[t[e+9]]+"-"+Y[t[e+10]]+Y[t[e+11]]+Y[t[e+12]]+Y[t[e+13]]+Y[t[e+14]]+Y[t[e+15]]).toLowerCase()}var Kr,Bs=new Uint8Array(16);function Zr(){if(!Kr){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Kr=crypto.getRandomValues.bind(crypto)}return Kr(Bs)}var Ws=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Yr={randomUUID:Ws};function Xs(t,e,r){if(Yr.randomUUID&&!e&&!t)return Yr.randomUUID();t=t||{};let n=t.random??t.rng?.()??Zr();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[r+o]=n[o];return e}return Xn(n)}var Ie=Xs;var l={};Bt(l,{BRAND:()=>va,DIRTY:()=>Ge,EMPTY_PATH:()=>Ys,INVALID:()=>w,NEVER:()=>ri,OK:()=>Q,ParseStatus:()=>q,Schema:()=>C,ZodAny:()=>ke,ZodArray:()=>xe,ZodBigInt:()=>He,ZodBoolean:()=>Ve,ZodBranded:()=>Rt,ZodCatch:()=>Je,ZodDate:()=>$e,ZodDefault:()=>qe,ZodDiscriminatedUnion:()=>zt,ZodEffects:()=>le,ZodEnum:()=>Ze,ZodError:()=>re,ZodFirstPartyTypeKind:()=>A,ZodFunction:()=>Zt,ZodIntersection:()=>Xe,ZodIssueCode:()=>b,ZodLazy:()=>ze,ZodLiteral:()=>Ke,ZodMap:()=>pt,ZodNaN:()=>ht,ZodNativeEnum:()=>Ye,ZodNever:()=>de,ZodNull:()=>Be,ZodNullable:()=>ge,ZodNumber:()=>Fe,ZodObject:()=>ne,ZodOptional:()=>ae,ZodParsedType:()=>x,ZodPipeline:()=>Ot,ZodPromise:()=>Re,ZodReadonly:()=>Qe,ZodRecord:()=>Kt,ZodSchema:()=>C,ZodSet:()=>mt,ZodString:()=>Ce,ZodSymbol:()=>dt,ZodTransformer:()=>le,ZodTuple:()=>he,ZodType:()=>C,ZodUndefined:()=>je,ZodUnion:()=>We,ZodUnknown:()=>Se,ZodVoid:()=>ft,addIssueToContext:()=>S,any:()=>Ia,array:()=>Ra,bigint:()=>Sa,boolean:()=>no,coerce:()=>ti,custom:()=>eo,date:()=>xa,datetimeRegex:()=>Jn,defaultErrorMap:()=>Ee,discriminatedUnion:()=>La,effect:()=>za,enum:()=>Ba,function:()=>Va,getErrorMap:()=>lt,getParsedType:()=>me,instanceof:()=>Ea,intersection:()=>Da,isAborted:()=>Wt,isAsync:()=>ut,isDirty:()=>Xt,isValid:()=>Ne,late:()=>ya,lazy:()=>$a,literal:()=>ja,makeIssue:()=>kt,map:()=>Fa,nan:()=>ba,nativeEnum:()=>Wa,never:()=>Ca,null:()=>Aa,nullable:()=>Za,number:()=>ro,object:()=>Oa,objectUtil:()=>qr,oboolean:()=>ei,onumber:()=>Qa,optional:()=>Ka,ostring:()=>Ja,pipeline:()=>qa,preprocess:()=>Ya,promise:()=>Xa,quotelessJson:()=>zs,record:()=>Ga,set:()=>Ha,setErrorMap:()=>Zs,strictObject:()=>Pa,string:()=>to,symbol:()=>Ta,transformer:()=>za,tuple:()=>Ua,undefined:()=>wa,union:()=>Ma,unknown:()=>Na,util:()=>R,void:()=>ka});var R;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let a of o)s[a]=a;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(i=>typeof o[o[i]]!="number"),a={};for(let i of s)a[i]=o[i];return t.objectValues(a)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},t.find=(o,s)=>{for(let a of o)if(s(a))return a},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(R||(R={}));var qr;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(qr||(qr={}));var x=R.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),me=t=>{switch(typeof t){case"undefined":return x.undefined;case"string":return x.string;case"number":return Number.isNaN(t)?x.nan:x.number;case"boolean":return x.boolean;case"function":return x.function;case"bigint":return x.bigint;case"symbol":return x.symbol;case"object":return Array.isArray(t)?x.array:t===null?x.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?x.promise:typeof Map<"u"&&t instanceof Map?x.map:typeof Set<"u"&&t instanceof Set?x.set:typeof Date<"u"&&t instanceof Date?x.date:x.object;default:return x.unknown}};var b=R.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"]),zs=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),re=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let i=n,c=0;for(;c<a.path.length;){let u=a.path[c];c===a.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(r(a))):i[u]=i[u]||{_errors:[]},i=i[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,R.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};re.create=t=>new re(t);var Ks=(t,e)=>{let r;switch(t.code){case b.invalid_type:t.received===x.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case b.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,R.jsonStringifyReplacer)}`;break;case b.unrecognized_keys:r=`Unrecognized key(s) in object: ${R.joinValues(t.keys,", ")}`;break;case b.invalid_union:r="Invalid input";break;case b.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${R.joinValues(t.options)}`;break;case b.invalid_enum_value:r=`Invalid enum value. Expected ${R.joinValues(t.options)}, received '${t.received}'`;break;case b.invalid_arguments:r="Invalid function arguments";break;case b.invalid_return_type:r="Invalid function return type";break;case b.invalid_date:r="Invalid date";break;case b.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:R.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case b.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case b.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case b.custom:r="Invalid input";break;case b.invalid_intersection_types:r="Intersection results could not be merged";break;case b.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case b.not_finite:r="Number must be finite";break;default:r=e.defaultError,R.assertNever(t)}return{message:r}},Ee=Ks;var zn=Ee;function Zs(t){zn=t}function lt(){return zn}var kt=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let i="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)i=u(a,{data:e,defaultError:i}).message;return{...o,path:s,message:i}},Ys=[];function S(t,e){let r=lt(),n=kt({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ee?void 0:Ee].filter(o=>!!o)});t.common.issues.push(n)}var q=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return w;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,a=await o.value;n.push({key:s,value:a})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return w;s.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(n[s.value]=a.value)}return{status:e.value,value:n}}},w=Object.freeze({status:"aborted"}),Ge=t=>({status:"dirty",value:t}),Q=t=>({status:"valid",value:t}),Wt=t=>t.status==="aborted",Xt=t=>t.status==="dirty",Ne=t=>t.status==="valid",ut=t=>typeof Promise<"u"&&t instanceof Promise;var T;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(T||(T={}));var ie=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,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}},Kn=(t,e)=>{if(Ne(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new re(t.common.issues);return this._error=r,this._error}}};function N(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(a,i)=>{let{message:c}=t;return a.code==="invalid_enum_value"?{message:c??i.defaultError}:typeof i.data>"u"?{message:c??n??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:c??r??i.defaultError}},description:o}}var C=class{get description(){return this._def.description}_getType(e){return me(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:me(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new q,ctx:{common:e.parent.common,data:e.data,parsedType:me(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ut(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:me(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Kn(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:me(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Ne(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Ne(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:me(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(ut(o)?o:Promise.resolve(o));return Kn(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let a=e(o),i=()=>s.addIssue({code:b.custom,...n(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(i(),!1)):a?!0:(i(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new le({schema:this,typeName:A.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return ae.create(this,this._def)}nullable(){return ge.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return xe.create(this)}promise(){return Re.create(this,this._def)}or(e){return We.create([this,e],this._def)}and(e){return Xe.create(this,e,this._def)}transform(e){return new le({...N(this._def),schema:this,typeName:A.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new qe({...N(this._def),innerType:this,defaultValue:r,typeName:A.ZodDefault})}brand(){return new Rt({typeName:A.ZodBranded,type:this,...N(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Je({...N(this._def),innerType:this,catchValue:r,typeName:A.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Ot.create(this,e)}readonly(){return Qe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},qs=/^c[^\s-]{8,}$/i,Js=/^[0-9a-z]+$/,Qs=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ea=/^[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,ta=/^[a-z0-9_-]{21}$/i,ra=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,na=/^[-+]?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)?)??$/,oa=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sa="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Jr,aa=/^(?:(?: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])$/,ia=/^(?:(?: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])$/,la=/^(([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]))$/,ua=/^(([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])$/,ca=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,da=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Yn="((\\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])))",fa=new RegExp(`^${Yn}$`);function qn(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function pa(t){return new RegExp(`^${qn(t)}$`)}function Jn(t){let e=`${Yn}T${qn(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function ma(t,e){return!!((e==="v4"||!e)&&aa.test(t)||(e==="v6"||!e)&&la.test(t))}function ha(t,e){if(!ra.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function ga(t,e){return!!((e==="v4"||!e)&&ia.test(t)||(e==="v6"||!e)&&ua.test(t))}var Ce=class t extends C{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==x.string){let s=this._getOrReturnCtx(e);return S(s,{code:b.invalid_type,expected:x.string,received:s.parsedType}),w}let n=new q,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),S(o,{code:b.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),S(o,{code:b.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let a=e.data.length>s.value,i=e.data.length<s.value;(a||i)&&(o=this._getOrReturnCtx(e,o),a?S(o,{code:b.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&S(o,{code:b.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")oa.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"email",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Jr||(Jr=new RegExp(sa,"u")),Jr.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"emoji",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")ea.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"uuid",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")ta.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"nanoid",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")qs.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"cuid",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")Js.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"cuid2",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Qs.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"ulid",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),S(o,{validation:"url",code:b.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"regex",code:b.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),S(o,{code:b.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),S(o,{code:b.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),S(o,{code:b.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Jn(s).test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{code:b.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?fa.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{code:b.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?pa(s).test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{code:b.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?na.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"duration",code:b.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?ma(e.data,s.version)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"ip",code:b.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?ha(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"jwt",code:b.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?ga(e.data,s.version)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"cidr",code:b.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?ca.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"base64",code:b.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?da.test(e.data)||(o=this._getOrReturnCtx(e,o),S(o,{validation:"base64url",code:b.invalid_string,message:s.message}),n.dirty()):R.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:b.invalid_string,...T.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...T.errToObj(e)})}url(e){return this._addCheck({kind:"url",...T.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...T.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...T.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...T.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...T.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...T.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...T.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...T.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...T.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...T.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...T.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...T.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...T.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...T.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...T.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...T.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...T.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...T.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...T.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...T.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...T.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...T.errToObj(r)})}nonempty(e){return this.min(1,T.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Ce.create=t=>new Ce({checks:[],typeName:A.ZodString,coerce:t?.coerce??!1,...N(t)});function _a(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),a=Number.parseInt(e.toFixed(o).replace(".",""));return s%a/10**o}var Fe=class t extends C{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==x.number){let s=this._getOrReturnCtx(e);return S(s,{code:b.invalid_type,expected:x.number,received:s.parsedType}),w}let n,o=new q;for(let s of this._def.checks)s.kind==="int"?R.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{code:b.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),S(n,{code:b.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),S(n,{code:b.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?_a(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),S(n,{code:b.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{code:b.not_finite,message:s.message}),o.dirty()):R.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,T.toString(r))}gt(e,r){return this.setLimit("min",e,!1,T.toString(r))}lte(e,r){return this.setLimit("max",e,!0,T.toString(r))}lt(e,r){return this.setLimit("max",e,!1,T.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:T.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:T.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:T.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:T.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:T.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:T.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:T.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:T.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:T.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:T.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&R.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Fe.create=t=>new Fe({checks:[],typeName:A.ZodNumber,coerce:t?.coerce||!1,...N(t)});var He=class t extends C{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==x.bigint)return this._getInvalidInput(e);let n,o=new q;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),S(n,{code:b.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),S(n,{code:b.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),S(n,{code:b.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):R.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return S(r,{code:b.invalid_type,expected:x.bigint,received:r.parsedType}),w}gte(e,r){return this.setLimit("min",e,!0,T.toString(r))}gt(e,r){return this.setLimit("min",e,!1,T.toString(r))}lte(e,r){return this.setLimit("max",e,!0,T.toString(r))}lt(e,r){return this.setLimit("max",e,!1,T.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:T.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:T.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:T.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:T.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:T.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:T.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};He.create=t=>new He({checks:[],typeName:A.ZodBigInt,coerce:t?.coerce??!1,...N(t)});var Ve=class extends C{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==x.boolean){let n=this._getOrReturnCtx(e);return S(n,{code:b.invalid_type,expected:x.boolean,received:n.parsedType}),w}return Q(e.data)}};Ve.create=t=>new Ve({typeName:A.ZodBoolean,coerce:t?.coerce||!1,...N(t)});var $e=class t extends C{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==x.date){let s=this._getOrReturnCtx(e);return S(s,{code:b.invalid_type,expected:x.date,received:s.parsedType}),w}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return S(s,{code:b.invalid_date}),w}let n=new q,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),S(o,{code:b.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),S(o,{code:b.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):R.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:T.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:T.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};$e.create=t=>new $e({checks:[],coerce:t?.coerce||!1,typeName:A.ZodDate,...N(t)});var dt=class extends C{_parse(e){if(this._getType(e)!==x.symbol){let n=this._getOrReturnCtx(e);return S(n,{code:b.invalid_type,expected:x.symbol,received:n.parsedType}),w}return Q(e.data)}};dt.create=t=>new dt({typeName:A.ZodSymbol,...N(t)});var je=class extends C{_parse(e){if(this._getType(e)!==x.undefined){let n=this._getOrReturnCtx(e);return S(n,{code:b.invalid_type,expected:x.undefined,received:n.parsedType}),w}return Q(e.data)}};je.create=t=>new je({typeName:A.ZodUndefined,...N(t)});var Be=class extends C{_parse(e){if(this._getType(e)!==x.null){let n=this._getOrReturnCtx(e);return S(n,{code:b.invalid_type,expected:x.null,received:n.parsedType}),w}return Q(e.data)}};Be.create=t=>new Be({typeName:A.ZodNull,...N(t)});var ke=class extends C{constructor(){super(...arguments),this._any=!0}_parse(e){return Q(e.data)}};ke.create=t=>new ke({typeName:A.ZodAny,...N(t)});var Se=class extends C{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Q(e.data)}};Se.create=t=>new Se({typeName:A.ZodUnknown,...N(t)});var de=class extends C{_parse(e){let r=this._getOrReturnCtx(e);return S(r,{code:b.invalid_type,expected:x.never,received:r.parsedType}),w}};de.create=t=>new de({typeName:A.ZodNever,...N(t)});var ft=class extends C{_parse(e){if(this._getType(e)!==x.undefined){let n=this._getOrReturnCtx(e);return S(n,{code:b.invalid_type,expected:x.void,received:n.parsedType}),w}return Q(e.data)}};ft.create=t=>new ft({typeName:A.ZodVoid,...N(t)});var xe=class t extends C{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==x.array)return S(r,{code:b.invalid_type,expected:x.array,received:r.parsedType}),w;if(o.exactLength!==null){let a=r.data.length>o.exactLength.value,i=r.data.length<o.exactLength.value;(a||i)&&(S(r,{code:a?b.too_big:b.too_small,minimum:i?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(S(r,{code:b.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(S(r,{code:b.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,i)=>o.type._parseAsync(new ie(r,a,r.path,i)))).then(a=>q.mergeArray(n,a));let s=[...r.data].map((a,i)=>o.type._parseSync(new ie(r,a,r.path,i)));return q.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:T.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:T.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:T.toString(r)}})}nonempty(e){return this.min(1,e)}};xe.create=(t,e)=>new xe({type:t,minLength:null,maxLength:null,exactLength:null,typeName:A.ZodArray,...N(e)});function ct(t){if(t instanceof ne){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ae.create(ct(n))}return new ne({...t._def,shape:()=>e})}else return t instanceof xe?new xe({...t._def,type:ct(t.element)}):t instanceof ae?ae.create(ct(t.unwrap())):t instanceof ge?ge.create(ct(t.unwrap())):t instanceof he?he.create(t.items.map(e=>ct(e))):t}var ne=class t extends C{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=R.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==x.object){let u=this._getOrReturnCtx(e);return S(u,{code:b.invalid_type,expected:x.object,received:u.parsedType}),w}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof de&&this._def.unknownKeys==="strip"))for(let u in o.data)a.includes(u)||i.push(u);let c=[];for(let u of a){let p=s[u],f=o.data[u];c.push({key:{status:"valid",value:u},value:p._parse(new ie(o,f,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof de){let u=this._def.unknownKeys;if(u==="passthrough")for(let p of i)c.push({key:{status:"valid",value:p},value:{status:"valid",value:o.data[p]}});else if(u==="strict")i.length>0&&(S(o,{code:b.unrecognized_keys,keys:i}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let p of i){let f=o.data[p];c.push({key:{status:"valid",value:p},value:u._parse(new ie(o,f,o.path,p)),alwaysSet:p in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let p of c){let f=await p.key,v=await p.value;u.push({key:f,value:v,alwaysSet:p.alwaysSet})}return u}).then(u=>q.mergeObjectSync(n,u)):q.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return T.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:T.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:A.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of R.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of R.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return ct(this)}partial(e){let r={};for(let n of R.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of R.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof ae;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Qn(R.objectKeys(this.shape))}};ne.create=(t,e)=>new ne({shape:()=>t,unknownKeys:"strip",catchall:de.create(),typeName:A.ZodObject,...N(e)});ne.strictCreate=(t,e)=>new ne({shape:()=>t,unknownKeys:"strict",catchall:de.create(),typeName:A.ZodObject,...N(e)});ne.lazycreate=(t,e)=>new ne({shape:t,unknownKeys:"strip",catchall:de.create(),typeName:A.ZodObject,...N(e)});var We=class extends C{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let i of s)if(i.result.status==="valid")return i.result;for(let i of s)if(i.result.status==="dirty")return r.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map(i=>new re(i.ctx.common.issues));return S(r,{code:b.invalid_union,unionErrors:a}),w}if(r.common.async)return Promise.all(n.map(async s=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(o);{let s,a=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},p=c._parseSync({data:r.data,path:r.path,parent:u});if(p.status==="valid")return p;p.status==="dirty"&&!s&&(s={result:p,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let i=a.map(c=>new re(c));return S(r,{code:b.invalid_union,unionErrors:i}),w}}get options(){return this._def.options}};We.create=(t,e)=>new We({options:t,typeName:A.ZodUnion,...N(e)});var be=t=>t instanceof ze?be(t.schema):t instanceof le?be(t.innerType()):t instanceof Ke?[t.value]:t instanceof Ze?t.options:t instanceof Ye?R.objectValues(t.enum):t instanceof qe?be(t._def.innerType):t instanceof je?[void 0]:t instanceof Be?[null]:t instanceof ae?[void 0,...be(t.unwrap())]:t instanceof ge?[null,...be(t.unwrap())]:t instanceof Rt||t instanceof Qe?be(t.unwrap()):t instanceof Je?be(t._def.innerType):[],zt=class t extends C{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==x.object)return S(r,{code:b.invalid_type,expected:x.object,received:r.parsedType}),w;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(S(r,{code:b.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),w)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let a=be(s.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of a){if(o.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);o.set(i,s)}}return new t({typeName:A.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...N(n)})}};function Qr(t,e){let r=me(t),n=me(e);if(t===e)return{valid:!0,data:t};if(r===x.object&&n===x.object){let o=R.objectKeys(e),s=R.objectKeys(t).filter(i=>o.indexOf(i)!==-1),a={...t,...e};for(let i of s){let c=Qr(t[i],e[i]);if(!c.valid)return{valid:!1};a[i]=c.data}return{valid:!0,data:a}}else if(r===x.array&&n===x.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let a=t[s],i=e[s],c=Qr(a,i);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===x.date&&n===x.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Xe=class extends C{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,a)=>{if(Wt(s)||Wt(a))return w;let i=Qr(s.value,a.value);return i.valid?((Xt(s)||Xt(a))&&r.dirty(),{status:r.value,value:i.data}):(S(n,{code:b.invalid_intersection_types}),w)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Xe.create=(t,e,r)=>new Xe({left:t,right:e,typeName:A.ZodIntersection,...N(r)});var he=class t extends C{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==x.array)return S(n,{code:b.invalid_type,expected:x.array,received:n.parsedType}),w;if(n.data.length<this._def.items.length)return S(n,{code:b.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w;!this._def.rest&&n.data.length>this._def.items.length&&(S(n,{code:b.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((a,i)=>{let c=this._def.items[i]||this._def.rest;return c?c._parse(new ie(n,a,n.path,i)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>q.mergeArray(r,a)):q.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};he.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new he({items:t,typeName:A.ZodTuple,rest:null,...N(e)})};var Kt=class t extends C{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==x.object)return S(n,{code:b.invalid_type,expected:x.object,received:n.parsedType}),w;let o=[],s=this._def.keyType,a=this._def.valueType;for(let i in n.data)o.push({key:s._parse(new ie(n,i,n.path,i)),value:a._parse(new ie(n,n.data[i],n.path,i)),alwaysSet:i in n.data});return n.common.async?q.mergeObjectAsync(r,o):q.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof C?new t({keyType:e,valueType:r,typeName:A.ZodRecord,...N(n)}):new t({keyType:Ce.create(),valueType:e,typeName:A.ZodRecord,...N(r)})}},pt=class extends C{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==x.map)return S(n,{code:b.invalid_type,expected:x.map,received:n.parsedType}),w;let o=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([i,c],u)=>({key:o._parse(new ie(n,i,n.path,[u,"key"])),value:s._parse(new ie(n,c,n.path,[u,"value"]))}));if(n.common.async){let i=new Map;return Promise.resolve().then(async()=>{for(let c of a){let u=await c.key,p=await c.value;if(u.status==="aborted"||p.status==="aborted")return w;(u.status==="dirty"||p.status==="dirty")&&r.dirty(),i.set(u.value,p.value)}return{status:r.value,value:i}})}else{let i=new Map;for(let c of a){let u=c.key,p=c.value;if(u.status==="aborted"||p.status==="aborted")return w;(u.status==="dirty"||p.status==="dirty")&&r.dirty(),i.set(u.value,p.value)}return{status:r.value,value:i}}}};pt.create=(t,e,r)=>new pt({valueType:e,keyType:t,typeName:A.ZodMap,...N(r)});var mt=class t extends C{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==x.set)return S(n,{code:b.invalid_type,expected:x.set,received:n.parsedType}),w;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(S(n,{code:b.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(S(n,{code:b.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function a(c){let u=new Set;for(let p of c){if(p.status==="aborted")return w;p.status==="dirty"&&r.dirty(),u.add(p.value)}return{status:r.value,value:u}}let i=[...n.data.values()].map((c,u)=>s._parse(new ie(n,c,n.path,u)));return n.common.async?Promise.all(i).then(c=>a(c)):a(i)}min(e,r){return new t({...this._def,minSize:{value:e,message:T.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:T.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};mt.create=(t,e)=>new mt({valueType:t,minSize:null,maxSize:null,typeName:A.ZodSet,...N(e)});var Zt=class t extends C{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==x.function)return S(r,{code:b.invalid_type,expected:x.function,received:r.parsedType}),w;function n(i,c){return kt({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,lt(),Ee].filter(u=>!!u),issueData:{code:b.invalid_arguments,argumentsError:c}})}function o(i,c){return kt({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,lt(),Ee].filter(u=>!!u),issueData:{code:b.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof Re){let i=this;return Q(async function(...c){let u=new re([]),p=await i._def.args.parseAsync(c,s).catch(d=>{throw u.addIssue(n(c,d)),u}),f=await Reflect.apply(a,this,p);return await i._def.returns._def.type.parseAsync(f,s).catch(d=>{throw u.addIssue(o(f,d)),u})})}else{let i=this;return Q(function(...c){let u=i._def.args.safeParse(c,s);if(!u.success)throw new re([n(c,u.error)]);let p=Reflect.apply(a,this,u.data),f=i._def.returns.safeParse(p,s);if(!f.success)throw new re([o(p,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:he.create(e).rest(Se.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||he.create([]).rest(Se.create()),returns:r||Se.create(),typeName:A.ZodFunction,...N(n)})}},ze=class extends C{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};ze.create=(t,e)=>new ze({getter:t,typeName:A.ZodLazy,...N(e)});var Ke=class extends C{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return S(r,{received:r.data,code:b.invalid_literal,expected:this._def.value}),w}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ke.create=(t,e)=>new Ke({value:t,typeName:A.ZodLiteral,...N(e)});function Qn(t,e){return new Ze({values:t,typeName:A.ZodEnum,...N(e)})}var Ze=class t extends C{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return S(r,{expected:R.joinValues(n),received:r.parsedType,code:b.invalid_type}),w}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return S(r,{received:r.data,code:b.invalid_enum_value,options:n}),w}return Q(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Ze.create=Qn;var Ye=class extends C{_parse(e){let r=R.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==x.string&&n.parsedType!==x.number){let o=R.objectValues(r);return S(n,{expected:R.joinValues(o),received:n.parsedType,code:b.invalid_type}),w}if(this._cache||(this._cache=new Set(R.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=R.objectValues(r);return S(n,{received:n.data,code:b.invalid_enum_value,options:o}),w}return Q(e.data)}get enum(){return this._def.values}};Ye.create=(t,e)=>new Ye({values:t,typeName:A.ZodNativeEnum,...N(e)});var Re=class extends C{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==x.promise&&r.common.async===!1)return S(r,{code:b.invalid_type,expected:x.promise,received:r.parsedType}),w;let n=r.parsedType===x.promise?r.data:Promise.resolve(r.data);return Q(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Re.create=(t,e)=>new Re({type:t,typeName:A.ZodPromise,...N(e)});var le=class extends C{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===A.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:a=>{S(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let a=o.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async i=>{if(r.value==="aborted")return w;let c=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});return c.status==="aborted"?w:c.status==="dirty"?Ge(c.value):r.value==="dirty"?Ge(c.value):c});{if(r.value==="aborted")return w;let i=this._def.schema._parseSync({data:a,path:n.path,parent:n});return i.status==="aborted"?w:i.status==="dirty"?Ge(i.value):r.value==="dirty"?Ge(i.value):i}}if(o.type==="refinement"){let a=i=>{let c=o.refinement(i,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?w:(i.status==="dirty"&&r.dirty(),a(i.value),{status:r.value,value:i.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>i.status==="aborted"?w:(i.status==="dirty"&&r.dirty(),a(i.value).then(()=>({status:r.value,value:i.value}))))}if(o.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Ne(a))return w;let i=o.transform(a.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:i}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Ne(a)?Promise.resolve(o.transform(a.value,s)).then(i=>({status:r.value,value:i})):w);R.assertNever(o)}};le.create=(t,e,r)=>new le({schema:t,typeName:A.ZodEffects,effect:e,...N(r)});le.createWithPreprocess=(t,e,r)=>new le({schema:e,effect:{type:"preprocess",transform:t},typeName:A.ZodEffects,...N(r)});var ae=class extends C{_parse(e){return this._getType(e)===x.undefined?Q(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ae.create=(t,e)=>new ae({innerType:t,typeName:A.ZodOptional,...N(e)});var ge=class extends C{_parse(e){return this._getType(e)===x.null?Q(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ge.create=(t,e)=>new ge({innerType:t,typeName:A.ZodNullable,...N(e)});var qe=class extends C{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===x.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};qe.create=(t,e)=>new qe({innerType:t,typeName:A.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...N(e)});var Je=class extends C{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ut(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new re(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new re(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Je.create=(t,e)=>new Je({innerType:t,typeName:A.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...N(e)});var ht=class extends C{_parse(e){if(this._getType(e)!==x.nan){let n=this._getOrReturnCtx(e);return S(n,{code:b.invalid_type,expected:x.nan,received:n.parsedType}),w}return{status:"valid",value:e.data}}};ht.create=t=>new ht({typeName:A.ZodNaN,...N(t)});var va=Symbol("zod_brand"),Rt=class extends C{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Ot=class t extends C{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?w:s.status==="dirty"?(r.dirty(),Ge(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?w:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:A.ZodPipeline})}},Qe=class extends C{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Ne(o)&&(o.value=Object.freeze(o.value)),o);return ut(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Qe.create=(t,e)=>new Qe({innerType:t,typeName:A.ZodReadonly,...N(e)});function Zn(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function eo(t,e={},r){return t?ke.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(a=>{if(!a){let i=Zn(e,n),c=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:c})}});if(!s){let a=Zn(e,n),i=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:i})}}):ke.create()}var ya={object:ne.lazycreate},A;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(A||(A={}));var Ea=(t,e={message:`Input not instance of ${t.name}`})=>eo(r=>r instanceof t,e),to=Ce.create,ro=Fe.create,ba=ht.create,Sa=He.create,no=Ve.create,xa=$e.create,Ta=dt.create,wa=je.create,Aa=Be.create,Ia=ke.create,Na=Se.create,Ca=de.create,ka=ft.create,Ra=xe.create,Oa=ne.create,Pa=ne.strictCreate,Ma=We.create,La=zt.create,Da=Xe.create,Ua=he.create,Ga=Kt.create,Fa=pt.create,Ha=mt.create,Va=Zt.create,$a=ze.create,ja=Ke.create,Ba=Ze.create,Wa=Ye.create,Xa=Re.create,za=le.create,Ka=ae.create,Za=ge.create,Ya=le.createWithPreprocess,qa=Ot.create,Ja=()=>to().optional(),Qa=()=>ro().optional(),ei=()=>no().optional(),ti={string:(t=>Ce.create({...t,coerce:!0})),number:(t=>Fe.create({...t,coerce:!0})),boolean:(t=>Ve.create({...t,coerce:!0})),bigint:(t=>He.create({...t,coerce:!0})),date:(t=>$e.create({...t,coerce:!0}))};var ri=w;var ni=l.object({name:l.string(),arguments:l.string()}),oi=l.object({id:l.string(),type:l.literal("function"),function:ni,encryptedValue:l.string().optional()}),Yt=l.object({id:l.string(),role:l.string(),content:l.string().optional(),name:l.string().optional(),encryptedValue:l.string().optional()}),si=l.object({type:l.literal("text"),text:l.string()}),ai=l.object({type:l.literal("data"),value:l.string(),mimeType:l.string()}),ii=l.object({type:l.literal("url"),value:l.string(),mimeType:l.string().optional()}),qt=l.discriminatedUnion("type",[ai,ii]),li=l.object({type:l.literal("image"),source:qt,metadata:l.unknown().optional()}),ui=l.object({type:l.literal("audio"),source:qt,metadata:l.unknown().optional()}),ci=l.object({type:l.literal("video"),source:qt,metadata:l.unknown().optional()}),di=l.object({type:l.literal("document"),source:qt,metadata:l.unknown().optional()});var oo=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()}),so=(t,e)=>{!t.id&&!t.url&&!t.data&&e.addIssue({code:l.ZodIssueCode.custom,message:"BinaryInputContent requires at least one of id, url, or data.",path:["id"]})},Cc=oo.superRefine((t,e)=>{so(t,e)}),fi=l.discriminatedUnion("type",[si,li,ui,ci,di,oo]),pi=fi.superRefine((t,e)=>{t.type==="binary"&&so(t,e)}),mi=Yt.extend({role:l.literal("developer"),content:l.string()}),hi=Yt.extend({role:l.literal("system"),content:l.string()}),gi=Yt.extend({role:l.literal("assistant"),content:l.string().optional(),toolCalls:l.array(oi).optional()}),_i=Yt.extend({role:l.literal("user"),content:l.union([l.string(),l.array(pi)])}),vi=l.object({id:l.string(),content:l.string(),role:l.literal("tool"),toolCallId:l.string(),error:l.string().optional(),encryptedValue:l.string().optional()}),yi=l.object({id:l.string(),role:l.literal("activity"),activityType:l.string(),content:l.record(l.any())}),Ei=l.object({id:l.string(),role:l.literal("reasoning"),content:l.string(),encryptedValue:l.string().optional()}),ao=l.discriminatedUnion("role",[mi,hi,gi,_i,vi,yi,Ei]),kc=l.union([l.literal("developer"),l.literal("system"),l.literal("assistant"),l.literal("user"),l.literal("tool"),l.literal("activity"),l.literal("reasoning")]),bi=l.object({description:l.string(),value:l.string()}),io=l.object({name:l.string(),description:l.string(),parameters:l.any(),metadata:l.record(l.any()).optional()}),Si=l.object({threadId:l.string(),runId:l.string(),parentRunId:l.string().optional(),state:l.any(),messages:l.array(ao),tools:l.array(io),context:l.array(bi),forwardedProps:l.any()}),xi=l.any(),F=class extends Error{constructor(t){super(t)}},en=class extends F{constructor(){super("Connect not implemented. This method is not supported by the current agent.")}},Ti=l.object({name:l.string(),description:l.string().optional()}),wi=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()}),Ai=l.object({streaming:l.boolean().optional(),websocket:l.boolean().optional(),httpBinary:l.boolean().optional(),pushNotifications:l.boolean().optional(),resumable:l.boolean().optional()}),Ii=l.object({supported:l.boolean().optional(),items:l.array(io).optional(),parallelCalls:l.boolean().optional(),clientProvided:l.boolean().optional()}),Ni=l.object({structuredOutput:l.boolean().optional(),supportedMimeTypes:l.array(l.string()).optional()}),Ci=l.object({snapshots:l.boolean().optional(),deltas:l.boolean().optional(),memory:l.boolean().optional(),persistentState:l.boolean().optional()}),ki=l.object({supported:l.boolean().optional(),delegation:l.boolean().optional(),handoffs:l.boolean().optional(),subAgents:l.array(Ti).optional()}),Ri=l.object({supported:l.boolean().optional(),streaming:l.boolean().optional(),encrypted:l.boolean().optional()}),Oi=l.object({image:l.boolean().optional(),audio:l.boolean().optional(),video:l.boolean().optional(),pdf:l.boolean().optional(),file:l.boolean().optional()}),Pi=l.object({image:l.boolean().optional(),audio:l.boolean().optional()}),Mi=l.object({input:Oi.optional(),output:Pi.optional()}),Li=l.object({codeExecution:l.boolean().optional(),sandboxed:l.boolean().optional(),maxIterations:l.number().optional(),maxExecutionTime:l.number().optional()}),Di=l.object({supported:l.boolean().optional(),approvals:l.boolean().optional(),interventions:l.boolean().optional(),feedback:l.boolean().optional()}),Rc=l.object({identity:wi.optional(),transport:Ai.optional(),tools:Ii.optional(),output:Ni.optional(),state:Ci.optional(),multiAgent:ki.optional(),reasoning:Ri.optional(),multimodal:Mi.optional(),execution:Li.optional(),humanInTheLoop:Di.optional(),custom:l.record(l.unknown()).optional()}),lo=l.union([l.literal("developer"),l.literal("system"),l.literal("assistant"),l.literal("user")]),g=(function(t){return t.TEXT_MESSAGE_START="TEXT_MESSAGE_START",t.TEXT_MESSAGE_CONTENT="TEXT_MESSAGE_CONTENT",t.TEXT_MESSAGE_END="TEXT_MESSAGE_END",t.TEXT_MESSAGE_CHUNK="TEXT_MESSAGE_CHUNK",t.TOOL_CALL_START="TOOL_CALL_START",t.TOOL_CALL_ARGS="TOOL_CALL_ARGS",t.TOOL_CALL_END="TOOL_CALL_END",t.TOOL_CALL_CHUNK="TOOL_CALL_CHUNK",t.TOOL_CALL_RESULT="TOOL_CALL_RESULT",t.THINKING_START="THINKING_START",t.THINKING_END="THINKING_END",t.THINKING_TEXT_MESSAGE_START="THINKING_TEXT_MESSAGE_START",t.THINKING_TEXT_MESSAGE_CONTENT="THINKING_TEXT_MESSAGE_CONTENT",t.THINKING_TEXT_MESSAGE_END="THINKING_TEXT_MESSAGE_END",t.STATE_SNAPSHOT="STATE_SNAPSHOT",t.STATE_DELTA="STATE_DELTA",t.MESSAGES_SNAPSHOT="MESSAGES_SNAPSHOT",t.ACTIVITY_SNAPSHOT="ACTIVITY_SNAPSHOT",t.ACTIVITY_DELTA="ACTIVITY_DELTA",t.RAW="RAW",t.CUSTOM="CUSTOM",t.RUN_STARTED="RUN_STARTED",t.RUN_FINISHED="RUN_FINISHED",t.RUN_ERROR="RUN_ERROR",t.STEP_STARTED="STEP_STARTED",t.STEP_FINISHED="STEP_FINISHED",t.REASONING_START="REASONING_START",t.REASONING_MESSAGE_START="REASONING_MESSAGE_START",t.REASONING_MESSAGE_CONTENT="REASONING_MESSAGE_CONTENT",t.REASONING_MESSAGE_END="REASONING_MESSAGE_END",t.REASONING_MESSAGE_CHUNK="REASONING_MESSAGE_CHUNK",t.REASONING_END="REASONING_END",t.REASONING_ENCRYPTED_VALUE="REASONING_ENCRYPTED_VALUE",t})({}),P=l.object({type:l.nativeEnum(g),timestamp:l.number().optional(),rawEvent:l.any().optional()}).passthrough(),Ui=P.extend({type:l.literal(g.TEXT_MESSAGE_START),messageId:l.string(),role:lo.default("assistant"),name:l.string().optional()}),uo=P.extend({type:l.literal(g.TEXT_MESSAGE_CONTENT),messageId:l.string(),delta:l.string()}),Gi=P.extend({type:l.literal(g.TEXT_MESSAGE_END),messageId:l.string()}),Fi=P.extend({type:l.literal(g.TEXT_MESSAGE_CHUNK),messageId:l.string().optional(),role:lo.optional(),delta:l.string().optional(),name:l.string().optional()}),Hi=P.extend({type:l.literal(g.THINKING_TEXT_MESSAGE_START)}),Vi=uo.omit({messageId:!0,type:!0}).extend({type:l.literal(g.THINKING_TEXT_MESSAGE_CONTENT)}),$i=P.extend({type:l.literal(g.THINKING_TEXT_MESSAGE_END)}),ji=P.extend({type:l.literal(g.TOOL_CALL_START),toolCallId:l.string(),toolCallName:l.string(),parentMessageId:l.string().optional()}),Bi=P.extend({type:l.literal(g.TOOL_CALL_ARGS),toolCallId:l.string(),delta:l.string()}),Wi=P.extend({type:l.literal(g.TOOL_CALL_END),toolCallId:l.string()}),Xi=P.extend({messageId:l.string(),type:l.literal(g.TOOL_CALL_RESULT),toolCallId:l.string(),content:l.string(),role:l.literal("tool").optional()}),zi=P.extend({type:l.literal(g.TOOL_CALL_CHUNK),toolCallId:l.string().optional(),toolCallName:l.string().optional(),parentMessageId:l.string().optional(),delta:l.string().optional()}),Ki=P.extend({type:l.literal(g.THINKING_START),title:l.string().optional()}),Zi=P.extend({type:l.literal(g.THINKING_END)}),Yi=P.extend({type:l.literal(g.STATE_SNAPSHOT),snapshot:xi}),qi=P.extend({type:l.literal(g.STATE_DELTA),delta:l.array(l.any())}),Ji=P.extend({type:l.literal(g.MESSAGES_SNAPSHOT),messages:l.array(ao)}),Qi=P.extend({type:l.literal(g.ACTIVITY_SNAPSHOT),messageId:l.string(),activityType:l.string(),content:l.record(l.any()),replace:l.boolean().optional().default(!0)}),el=P.extend({type:l.literal(g.ACTIVITY_DELTA),messageId:l.string(),activityType:l.string(),patch:l.array(l.any())}),tl=P.extend({type:l.literal(g.RAW),event:l.any(),source:l.string().optional()}),rl=P.extend({type:l.literal(g.CUSTOM),name:l.string(),value:l.any()}),nl=P.extend({type:l.literal(g.RUN_STARTED),threadId:l.string(),runId:l.string(),parentRunId:l.string().optional(),input:Si.optional()}),ol=P.extend({type:l.literal(g.RUN_FINISHED),threadId:l.string(),runId:l.string(),result:l.any().optional()}),sl=P.extend({type:l.literal(g.RUN_ERROR),message:l.string(),code:l.string().optional()}),al=P.extend({type:l.literal(g.STEP_STARTED),stepName:l.string()}),il=P.extend({type:l.literal(g.STEP_FINISHED),stepName:l.string()}),ll=l.union([l.literal("tool-call"),l.literal("message")]),ul=P.extend({type:l.literal(g.REASONING_START),messageId:l.string()}),cl=P.extend({type:l.literal(g.REASONING_MESSAGE_START),messageId:l.string(),role:l.literal("reasoning")}),dl=P.extend({type:l.literal(g.REASONING_MESSAGE_CONTENT),messageId:l.string(),delta:l.string()}),fl=P.extend({type:l.literal(g.REASONING_MESSAGE_END),messageId:l.string()}),pl=P.extend({type:l.literal(g.REASONING_MESSAGE_CHUNK),messageId:l.string().optional(),delta:l.string().optional()}),ml=P.extend({type:l.literal(g.REASONING_END),messageId:l.string()}),hl=P.extend({type:l.literal(g.REASONING_ENCRYPTED_VALUE),subtype:ll,entityId:l.string(),encryptedValue:l.string()}),co=l.discriminatedUnion("type",[Ui,uo,Gi,Fi,Ki,Zi,Hi,Vi,$i,ji,Bi,Wi,zi,Xi,Yi,qi,Ji,Qi,el,tl,rl,nl,ol,sl,al,il,ul,cl,dl,fl,pl,ml,hl]);var tn={};Bt(tn,{JsonPatchError:()=>W,_areEquals:()=>Lt,applyOperation:()=>et,applyPatch:()=>Oe,applyReducer:()=>El,deepClone:()=>vl,getValueByPointer:()=>rr,validate:()=>po,validator:()=>nr});var gl=(function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var s in o)o.hasOwnProperty(s)&&(n[s]=o[s])},t(e,r)};return function(e,r){t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),_l=Object.prototype.hasOwnProperty;function Qt(t,e){return _l.call(t,e)}function er(t){if(Array.isArray(t)){for(var e=new Array(t.length),r=0;r<e.length;r++)e[r]=""+r;return e}if(Object.keys)return Object.keys(t);var n=[];for(var o in t)Qt(t,o)&&n.push(o);return n}function J(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function tr(t){for(var e=0,r=t.length,n;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function _e(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function Pt(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Jt(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,r=t.length;e<r;e++)if(Jt(t[e]))return!0}else if(typeof t=="object"){for(var n=er(t),o=n.length,s=0;s<o;s++)if(Jt(t[n[s]]))return!0}}return!1}function fo(t,e){var r=[t];for(var n in e){var o=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof o<"u"&&r.push(n+": "+o)}return r.join(`
2
+ `)}var Mt=(function(t){gl(e,t);function e(r,n,o,s,a){var i=this.constructor,c=t.call(this,fo(r,{name:n,index:o,operation:s,tree:a}))||this;return c.name=n,c.index=o,c.operation=s,c.tree=a,Object.setPrototypeOf(c,i.prototype),c.message=fo(r,{name:n,index:o,operation:s,tree:a}),c}return e})(Error);var W=Mt,vl=J,gt={add:function(t,e,r){return t[e]=this.value,{newDocument:r}},remove:function(t,e,r){var n=t[e];return delete t[e],{newDocument:r,removed:n}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:function(t,e,r){var n=rr(r,this.path);n&&(n=J(n));var o=et(r,{op:"remove",path:this.from}).removed;return et(r,{op:"add",path:this.path,value:o}),{newDocument:r,removed:n}},copy:function(t,e,r){var n=rr(r,this.from);return et(r,{op:"add",path:this.path,value:J(n)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:Lt(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}},yl={add:function(t,e,r){return tr(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},remove:function(t,e,r){var n=t.splice(e,1);return{newDocument:r,removed:n[0]}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:gt.move,copy:gt.copy,test:gt.test,_get:gt._get};function rr(t,e){if(e=="")return t;var r={op:"_get",path:e};return et(t,r),r.value}function et(t,e,r,n,o,s){if(r===void 0&&(r=!1),n===void 0&&(n=!0),o===void 0&&(o=!0),s===void 0&&(s=0),r&&(typeof r=="function"?r(e,0,t,e.path):nr(e,0)),e.path===""){var a={newDocument:t};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=t,a;if(e.op==="move"||e.op==="copy")return a.newDocument=rr(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=Lt(t,e.value),a.test===!1)throw new W("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return a.newDocument=t,a}else{if(e.op==="remove")return a.removed=t,a.newDocument=null,a;if(e.op==="_get")return e.value=t,a;if(r)throw new W("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,t);return a}}else{n||(t=J(t));var i=e.path||"",c=i.split("/"),u=t,p=1,f=c.length,v=void 0,d=void 0,m=void 0;for(typeof r=="function"?m=r:m=nr;;){if(d=c[p],d&&d.indexOf("~")!=-1&&(d=Pt(d)),o&&(d=="__proto__"||d=="prototype"&&p>0&&c[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(r&&v===void 0&&(u[d]===void 0?v=c.slice(0,p).join("/"):p==f-1&&(v=e.path),v!==void 0&&m(e,0,t,v)),p++,Array.isArray(u)){if(d==="-")d=u.length;else{if(r&&!tr(d))throw new W("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,t);tr(d)&&(d=~~d)}if(p>=f){if(r&&e.op==="add"&&d>u.length)throw new W("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,t);var a=yl[e.op].call(e,u,d,t);if(a.test===!1)throw new W("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return a}}else if(p>=f){var a=gt[e.op].call(e,u,d,t);if(a.test===!1)throw new W("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return a}if(u=u[d],r&&p<f&&(!u||typeof u!="object"))throw new W("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,t)}}}function Oe(t,e,r,n,o){if(n===void 0&&(n=!0),o===void 0&&(o=!0),r&&!Array.isArray(e))throw new W("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=J(t));for(var s=new Array(e.length),a=0,i=e.length;a<i;a++)s[a]=et(t,e[a],r,!0,o,a),t=s[a].newDocument;return s.newDocument=t,s}function El(t,e,r){var n=et(t,e);if(n.test===!1)throw new W("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function nr(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new W("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(gt[t.op]){if(typeof t.path!="string")throw new W("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new W('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new W("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new W("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&Jt(t.value))throw new W("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var o=t.path.split("/").length,s=n.split("/").length;if(o!==s+1&&o!==s)throw new W("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new W("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var a={op:"_get",path:t.from,value:void 0},i=po([a],r);if(i&&i.name==="OPERATION_PATH_UNRESOLVABLE")throw new W("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new W("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function po(t,e,r){try{if(!Array.isArray(t))throw new W("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Oe(J(e),J(t),r||!0);else{r=r||nr;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(o){if(o instanceof W)return o;throw o}}function Lt(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=Array.isArray(t),n=Array.isArray(e),o,s,a;if(r&&n){if(s=t.length,s!=e.length)return!1;for(o=s;o--!==0;)if(!Lt(t[o],e[o]))return!1;return!0}if(r!=n)return!1;var i=Object.keys(t);if(s=i.length,s!==Object.keys(e).length)return!1;for(o=s;o--!==0;)if(!e.hasOwnProperty(i[o]))return!1;for(o=s;o--!==0;)if(a=i[o],!Lt(t[a],e[a]))return!1;return!0}return t!==t&&e!==e}var sn={};Bt(sn,{compare:()=>Nl,generate:()=>rn,observe:()=>Il,unobserve:()=>Al});var nn=new WeakMap,bl=(function(){function t(e){this.observers=new Map,this.obj=e}return t})(),Sl=(function(){function t(e,r){this.callback=e,this.observer=r}return t})();function xl(t){return nn.get(t)}function Tl(t,e){return t.observers.get(e)}function wl(t,e){t.observers.delete(e.callback)}function Al(t,e){e.unobserve()}function Il(t,e){var r=[],n,o=xl(t);if(!o)o=new bl(t),nn.set(t,o);else{var s=Tl(o,e);n=s&&s.observer}if(n)return n;if(n={},o.value=J(t),e){n.callback=e,n.next=null;var a=function(){rn(n)},i=function(){clearTimeout(n.next),n.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",i),window.addEventListener("keyup",i),window.addEventListener("mousedown",i),window.addEventListener("keydown",i),window.addEventListener("change",i))}return n.patches=r,n.object=t,n.unobserve=function(){rn(n),clearTimeout(n.next),wl(o,n),typeof window<"u"&&(window.removeEventListener("mouseup",i),window.removeEventListener("keyup",i),window.removeEventListener("mousedown",i),window.removeEventListener("keydown",i),window.removeEventListener("change",i))},o.observers.set(e,new Sl(e,n)),n}function rn(t,e){e===void 0&&(e=!1);var r=nn.get(t.object);on(r.value,t.object,t.patches,"",e),t.patches.length&&Oe(r.value,t.patches);var n=t.patches;return n.length>0&&(t.patches=[],t.callback&&t.callback(n)),n}function on(t,e,r,n,o){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=er(e),a=er(t),i=!1,c=!1,u=a.length-1;u>=0;u--){var p=a[u],f=t[p];if(Qt(e,p)&&!(e[p]===void 0&&f!==void 0&&Array.isArray(e)===!1)){var v=e[p];typeof f=="object"&&f!=null&&typeof v=="object"&&v!=null&&Array.isArray(f)===Array.isArray(v)?on(f,v,r,n+"/"+_e(p),o):f!==v&&(i=!0,o&&r.push({op:"test",path:n+"/"+_e(p),value:J(f)}),r.push({op:"replace",path:n+"/"+_e(p),value:J(v)}))}else Array.isArray(t)===Array.isArray(e)?(o&&r.push({op:"test",path:n+"/"+_e(p),value:J(f)}),r.push({op:"remove",path:n+"/"+_e(p)}),c=!0):(o&&r.push({op:"test",path:n,value:t}),r.push({op:"replace",path:n,value:e}),i=!0)}if(!(!c&&s.length==a.length))for(var u=0;u<s.length;u++){var p=s[u];!Qt(t,p)&&e[p]!==void 0&&r.push({op:"add",path:n+"/"+_e(p),value:J(e[p])})}}}function Nl(t,e,r){r===void 0&&(r=!1);var n=[];return on(t,e,n,"",r),n}var Hc=Object.assign({},tn,sn,{JsonPatchError:Mt,deepClone:J,escapePathComponent:_e,unescapePathComponent:Pt});var an=function(t,e){return an=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[o]=n[o])},an(t,e)};function ve(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");an(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function mo(t,e,r,n){function o(s){return s instanceof r?s:new r(function(a){a(s)})}return new(r||(r=Promise))(function(s,a){function i(p){try{u(n.next(p))}catch(f){a(f)}}function c(p){try{u(n.throw(p))}catch(f){a(f)}}function u(p){p.done?s(p.value):o(p.value).then(i,c)}u((n=n.apply(t,e||[])).next())})}function or(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,o,s,a=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return a.next=i(0),a.throw=i(1),a.return=i(2),typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function i(u){return function(p){return c([u,p])}}function c(u){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,u[0]&&(r=0)),r;)try{if(n=1,o&&(s=u[0]&2?o.return:u[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,u[1])).done)return s;switch(o=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,o=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){r.label=u[1];break}if(u[0]===6&&r.label<s[1]){r.label=s[1],s=u;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(u);break}s[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(p){u=[6,p],o=0}finally{n=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function Te(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function _t(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,s=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s}function vt(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,s;n<o;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))}function tt(t){return this instanceof tt?(this.v=t,this):new tt(t)}function ho(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),i("next"),i("throw"),i("return",a),o[Symbol.asyncIterator]=function(){return this},o;function a(d){return function(m){return Promise.resolve(m).then(d,f)}}function i(d,m){n[d]&&(o[d]=function(h){return new Promise(function(y,E){s.push([d,h,y,E])>1||c(d,h)})},m&&(o[d]=m(o[d])))}function c(d,m){try{u(n[d](m))}catch(h){v(s[0][3],h)}}function u(d){d.value instanceof tt?Promise.resolve(d.value.v).then(p,f):v(s[0][2],d)}function p(d){c("next",d)}function f(d){c("throw",d)}function v(d,m){d(m),s.shift(),s.length&&c(s[0][0],s[0][1])}}function go(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Te=="function"?Te(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(a){return new Promise(function(i,c){a=t[s](a),o(i,c,a.done,a.value)})}}function o(s,a,i,c){Promise.resolve(c).then(function(u){s({value:u,done:i})},a)}}function k(t){return typeof t=="function"}function yt(t){var e=function(n){Error.call(n),n.stack=new Error().stack},r=t(e);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var sr=yt(function(t){return function(r){t(this),this.message=r?r.length+` errors occurred during unsubscription:
3
3
  `+r.map(function(n,o){return o+1+") "+n.toString()}).join(`
4
- `):"",this.name="UnsubscriptionError",this.errors=r}});function Dt(t,e){if(t){var r=t.indexOf(e);0<=r&&t.splice(r,1)}}var Et=(function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,r,n,o,s;if(!this.closed){this.closed=!0;var a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var i=xe(a),c=i.next();!c.done;c=i.next()){var u=c.value;u.remove(this)}}catch(h){e={error:h}}finally{try{c&&!c.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}else a.remove(this);var p=this.initialTeardown;if(k(p))try{p()}catch(h){s=h instanceof sr?h.errors:[h]}var f=this._finalizers;if(f){this._finalizers=null;try{for(var v=xe(f),d=v.next();!d.done;d=v.next()){var m=d.value;try{go(m)}catch(h){s=s??[],h instanceof sr?s=vt(vt([],_t(s)),_t(h.errors)):s.push(h)}}}catch(h){n={error:h}}finally{try{d&&!d.done&&(o=v.return)&&o.call(v)}finally{if(n)throw n.error}}}if(s)throw new sr(s)}},t.prototype.add=function(e){var r;if(e&&e!==this)if(this.closed)go(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(r=this._finalizers)!==null&&r!==void 0?r:[]).push(e)}},t.prototype._hasParent=function(e){var r=this._parentage;return r===e||Array.isArray(r)&&r.includes(e)},t.prototype._addParent=function(e){var r=this._parentage;this._parentage=Array.isArray(r)?(r.push(e),r):r?[r,e]:e},t.prototype._removeParent=function(e){var r=this._parentage;r===e?this._parentage=null:Array.isArray(r)&&Dt(r,e)},t.prototype.remove=function(e){var r=this._finalizers;r&&Dt(r,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})();var an=Et.EMPTY;function ar(t){return t instanceof Et||t&&"closed"in t&&k(t.remove)&&k(t.add)&&k(t.unsubscribe)}function go(t){k(t)?t():t.unsubscribe()}var de={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var bt={setTimeout:function(t,e){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];var o=bt.delegate;return o?.setTimeout?o.setTimeout.apply(o,vt([t,e],_t(r))):setTimeout.apply(void 0,vt([t,e],_t(r)))},clearTimeout:function(t){var e=bt.delegate;return(e?.clearTimeout||clearTimeout)(t)},delegate:void 0};function ir(t){bt.setTimeout(function(){var e=de.onUnhandledError;if(e)e(t);else throw t})}function Ut(){}var _o=(function(){return ln("C",void 0,void 0)})();function vo(t){return ln("E",void 0,t)}function yo(t){return ln("N",t,void 0)}function ln(t,e,r){return{kind:t,value:e,error:r}}var tt=null;function St(t){if(de.useDeprecatedSynchronousErrorHandling){var e=!tt;if(e&&(tt={errorThrown:!1,error:null}),t(),e){var r=tt,n=r.errorThrown,o=r.error;if(tt=null,n)throw o}}else t()}function Eo(t){de.useDeprecatedSynchronousErrorHandling&&tt&&(tt.errorThrown=!0,tt.error=t)}var Gt=(function(t){ve(e,t);function e(r){var n=t.call(this)||this;return n.isStopped=!1,r?(n.destination=r,ar(r)&&r.add(n)):n.destination=Cl,n}return e.create=function(r,n,o){return new ur(r,n,o)},e.prototype.next=function(r){this.isStopped?cn(yo(r),this):this._next(r)},e.prototype.error=function(r){this.isStopped?cn(vo(r),this):(this.isStopped=!0,this._error(r))},e.prototype.complete=function(){this.isStopped?cn(_o,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(r){this.destination.next(r)},e.prototype._error=function(r){try{this.destination.error(r)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(Et);var Al=Function.prototype.bind;function un(t,e){return Al.call(t,e)}var Il=(function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var r=this.partialObserver;if(r.next)try{r.next(e)}catch(n){lr(n)}},t.prototype.error=function(e){var r=this.partialObserver;if(r.error)try{r.error(e)}catch(n){lr(n)}else lr(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(r){lr(r)}},t})(),ur=(function(t){ve(e,t);function e(r,n,o){var s=t.call(this)||this,a;if(k(r)||!r)a={next:r??void 0,error:n??void 0,complete:o??void 0};else{var i;s&&de.useDeprecatedNextContext?(i=Object.create(r),i.unsubscribe=function(){return s.unsubscribe()},a={next:r.next&&un(r.next,i),error:r.error&&un(r.error,i),complete:r.complete&&un(r.complete,i)}):a=r}return s.destination=new Il(a),s}return e})(Gt);function lr(t){de.useDeprecatedSynchronousErrorHandling?Eo(t):ir(t)}function Nl(t){throw t}function cn(t,e){var r=de.onStoppedNotification;r&&bt.setTimeout(function(){return r(t,e)})}var Cl={closed:!0,next:Ut,error:Nl,complete:Ut};var xt=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Tt(t){return t}function cr(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return dn(t)}function dn(t){return t.length===0?Tt:t.length===1?t[0]:function(r){return t.reduce(function(n,o){return o(n)},r)}}var H=(function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var r=new t;return r.source=this,r.operator=e,r},t.prototype.subscribe=function(e,r,n){var o=this,s=Ol(e)?e:new ur(e,r,n);return St(function(){var a=o,i=a.operator,c=a.source;s.add(i?i.call(s,c):c?o._subscribe(s):o._trySubscribe(s))}),s},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(r){e.error(r)}},t.prototype.forEach=function(e,r){var n=this;return r=bo(r),new r(function(o,s){var a=new ur({next:function(i){try{e(i)}catch(c){s(c),a.unsubscribe()}},error:s,complete:o});n.subscribe(a)})},t.prototype._subscribe=function(e){var r;return(r=this.source)===null||r===void 0?void 0:r.subscribe(e)},t.prototype[xt]=function(){return this},t.prototype.pipe=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return dn(e)(this)},t.prototype.toPromise=function(e){var r=this;return e=bo(e),new e(function(n,o){var s;r.subscribe(function(a){return s=a},function(a){return o(a)},function(){return n(s)})})},t.create=function(e){return new t(e)},t})();function bo(t){var e;return(e=t??de.Promise)!==null&&e!==void 0?e:Promise}function kl(t){return t&&k(t.next)&&k(t.error)&&k(t.complete)}function Ol(t){return t&&t instanceof Gt||kl(t)&&ar(t)}function Rl(t){return k(t?.lift)}function K(t){return function(e){if(Rl(e))return e.lift(function(r){try{return t(r,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}function te(t,e,r,n,o){return new Pl(t,e,r,n,o)}var Pl=(function(t){ve(e,t);function e(r,n,o,s,a,i){var c=t.call(this,r)||this;return c.onFinalize=a,c.shouldUnsubscribe=i,c._next=n?function(u){try{n(u)}catch(p){r.error(p)}}:t.prototype._next,c._error=s?function(u){try{s(u)}catch(p){r.error(p)}finally{this.unsubscribe()}}:t.prototype._error,c._complete=o?function(){try{o()}catch(u){r.error(u)}finally{this.unsubscribe()}}:t.prototype._complete,c}return e.prototype.unsubscribe=function(){var r;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;t.prototype.unsubscribe.call(this),!n&&((r=this.onFinalize)===null||r===void 0||r.call(this))}},e})(Gt);var So=yt(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var rt=(function(t){ve(e,t);function e(){var r=t.call(this)||this;return r.closed=!1,r.currentObservers=null,r.observers=[],r.isStopped=!1,r.hasError=!1,r.thrownError=null,r}return e.prototype.lift=function(r){var n=new xo(this,this);return n.operator=r,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new So},e.prototype.next=function(r){var n=this;St(function(){var o,s;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var a=xe(n.currentObservers),i=a.next();!i.done;i=a.next()){var c=i.value;c.next(r)}}catch(u){o={error:u}}finally{try{i&&!i.done&&(s=a.return)&&s.call(a)}finally{if(o)throw o.error}}}})},e.prototype.error=function(r){var n=this;St(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=r;for(var o=n.observers;o.length;)o.shift().error(r)}})},e.prototype.complete=function(){var r=this;St(function(){if(r._throwIfClosed(),!r.isStopped){r.isStopped=!0;for(var n=r.observers;n.length;)n.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var r;return((r=this.observers)===null||r===void 0?void 0:r.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(r){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,r)},e.prototype._subscribe=function(r){return this._throwIfClosed(),this._checkFinalizedStatuses(r),this._innerSubscribe(r)},e.prototype._innerSubscribe=function(r){var n=this,o=this,s=o.hasError,a=o.isStopped,i=o.observers;return s||a?an:(this.currentObservers=null,i.push(r),new Et(function(){n.currentObservers=null,Dt(i,r)}))},e.prototype._checkFinalizedStatuses=function(r){var n=this,o=n.hasError,s=n.thrownError,a=n.isStopped;o?r.error(s):a&&r.complete()},e.prototype.asObservable=function(){var r=new H;return r.source=this,r},e.create=function(r,n){return new xo(r,n)},e})(H);var xo=(function(t){ve(e,t);function e(r,n){var o=t.call(this)||this;return o.destination=r,o.source=n,o}return e.prototype.next=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.next)===null||o===void 0||o.call(n,r)},e.prototype.error=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.error)===null||o===void 0||o.call(n,r)},e.prototype.complete=function(){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.complete)===null||n===void 0||n.call(r)},e.prototype._subscribe=function(r){var n,o;return(o=(n=this.source)===null||n===void 0?void 0:n.subscribe(r))!==null&&o!==void 0?o:an},e})(rt);var fn={now:function(){return(fn.delegate||Date).now()},delegate:void 0};var pn=(function(t){ve(e,t);function e(r,n,o){r===void 0&&(r=1/0),n===void 0&&(n=1/0),o===void 0&&(o=fn);var s=t.call(this)||this;return s._bufferSize=r,s._windowTime=n,s._timestampProvider=o,s._buffer=[],s._infiniteTimeWindow=!0,s._infiniteTimeWindow=n===1/0,s._bufferSize=Math.max(1,r),s._windowTime=Math.max(1,n),s}return e.prototype.next=function(r){var n=this,o=n.isStopped,s=n._buffer,a=n._infiniteTimeWindow,i=n._timestampProvider,c=n._windowTime;o||(s.push(r),!a&&s.push(i.now()+c)),this._trimBuffer(),t.prototype.next.call(this,r)},e.prototype._subscribe=function(r){this._throwIfClosed(),this._trimBuffer();for(var n=this._innerSubscribe(r),o=this,s=o._infiniteTimeWindow,a=o._buffer,i=a.slice(),c=0;c<i.length&&!r.closed;c+=s?1:2)r.next(i[c]);return this._checkFinalizedStatuses(r),n},e.prototype._trimBuffer=function(){var r=this,n=r._bufferSize,o=r._timestampProvider,s=r._buffer,a=r._infiniteTimeWindow,i=(a?1:2)*n;if(n<1/0&&i<s.length&&s.splice(0,s.length-i),!a){for(var c=o.now(),u=0,p=1;p<s.length&&s[p]<=c;p+=2)u=p;u&&s.splice(0,u+1)}},e})(rt);var dr=new H(function(t){return t.complete()});function To(t){return t&&k(t.schedule)}function Ml(t){return t[t.length-1]}function wo(t){return To(Ml(t))?t.pop():void 0}var fr=(function(t){return t&&typeof t.length=="number"&&typeof t!="function"});function pr(t){return k(t?.then)}function mr(t){return k(t[xt])}function hr(t){return Symbol.asyncIterator&&k(t?.[Symbol.asyncIterator])}function gr(t){return new TypeError("You provided "+(t!==null&&typeof t=="object"?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Ll(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var _r=Ll();function vr(t){return k(t?.[_r])}function yr(t){return mo(this,arguments,function(){var r,n,o,s;return or(this,function(a){switch(a.label){case 0:r=t.getReader(),a.label=1;case 1:a.trys.push([1,,9,10]),a.label=2;case 2:return[4,et(r.read())];case 3:return n=a.sent(),o=n.value,s=n.done,s?[4,et(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,et(o)];case 6:return[4,a.sent()];case 7:return a.sent(),[3,2];case 8:return[3,10];case 9:return r.releaseLock(),[7];case 10:return[2]}})})}function Er(t){return k(t?.getReader)}function ee(t){if(t instanceof H)return t;if(t!=null){if(mr(t))return Dl(t);if(fr(t))return Ul(t);if(pr(t))return Gl(t);if(hr(t))return Ao(t);if(vr(t))return Fl(t);if(Er(t))return Hl(t)}throw gr(t)}function Dl(t){return new H(function(e){var r=t[xt]();if(k(r.subscribe))return r.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Ul(t){return new H(function(e){for(var r=0;r<t.length&&!e.closed;r++)e.next(t[r]);e.complete()})}function Gl(t){return new H(function(e){t.then(function(r){e.closed||(e.next(r),e.complete())},function(r){return e.error(r)}).then(null,ir)})}function Fl(t){return new H(function(e){var r,n;try{for(var o=xe(t),s=o.next();!s.done;s=o.next()){var a=s.value;if(e.next(a),e.closed)return}}catch(i){r={error:i}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}e.complete()})}function Ao(t){return new H(function(e){Vl(t,e).catch(function(r){return e.error(r)})})}function Hl(t){return Ao(yr(t))}function Vl(t,e){var r,n,o,s;return po(this,void 0,void 0,function(){var a,i;return or(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),r=ho(t),c.label=1;case 1:return[4,r.next()];case 2:if(n=c.sent(),!!n.done)return[3,4];if(a=n.value,e.next(a),e.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return i=c.sent(),o={error:i},[3,11];case 6:return c.trys.push([6,,9,10]),n&&!n.done&&(s=r.return)?[4,s.call(r)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function ue(t,e,r,n,o){n===void 0&&(n=0),o===void 0&&(o=!1);var s=e.schedule(function(){r(),o?t.add(this.schedule(null,n)):this.unsubscribe()},n);if(t.add(s),!o)return s}function br(t,e){return e===void 0&&(e=0),K(function(r,n){r.subscribe(te(n,function(o){return ue(n,t,function(){return n.next(o)},e)},function(){return ue(n,t,function(){return n.complete()},e)},function(o){return ue(n,t,function(){return n.error(o)},e)}))})}function Sr(t,e){return e===void 0&&(e=0),K(function(r,n){n.add(t.schedule(function(){return r.subscribe(n)},e))})}function Io(t,e){return ee(t).pipe(Sr(e),br(e))}function No(t,e){return ee(t).pipe(Sr(e),br(e))}function Co(t,e){return new H(function(r){var n=0;return e.schedule(function(){n===t.length?r.complete():(r.next(t[n++]),r.closed||this.schedule())})})}function ko(t,e){return new H(function(r){var n;return ue(r,e,function(){n=t[_r](),ue(r,e,function(){var o,s,a;try{o=n.next(),s=o.value,a=o.done}catch(i){r.error(i);return}a?r.complete():r.next(s)},0,!0)}),function(){return k(n?.return)&&n.return()}})}function xr(t,e){if(!t)throw new Error("Iterable cannot be null");return new H(function(r){ue(r,e,function(){var n=t[Symbol.asyncIterator]();ue(r,e,function(){n.next().then(function(o){o.done?r.complete():r.next(o.value)})},0,!0)})})}function Oo(t,e){return xr(yr(t),e)}function Ro(t,e){if(t!=null){if(mr(t))return Io(t,e);if(fr(t))return Co(t,e);if(pr(t))return No(t,e);if(hr(t))return xr(t,e);if(vr(t))return ko(t,e);if(Er(t))return Oo(t,e)}throw gr(t)}function Ft(t,e){return e?Ro(t,e):ee(t)}function j(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var r=wo(t);return Ft(t,r)}function B(t,e){var r=k(t)?t:function(){return t},n=function(o){return o.error(r())};return new H(e?function(o){return e.schedule(n,0,o)}:n)}var Po=yt(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function Tr(t,e){var r=typeof e=="object";return new Promise(function(n,o){var s=!1,a;t.subscribe({next:function(i){a=i,s=!0},error:o,complete:function(){s?n(a):r?n(e.defaultValue):o(new Po)}})})}function nt(t,e){return K(function(r,n){var o=0;r.subscribe(te(n,function(s){n.next(t.call(e,s,o++))}))})}function Mo(t,e,r,n,o,s,a,i){var c=[],u=0,p=0,f=!1,v=function(){f&&!c.length&&!u&&e.complete()},d=function(h){return u<n?m(h):c.push(h)},m=function(h){s&&e.next(h),u++;var y=!1;ee(r(h,p++)).subscribe(te(e,function(E){o?.(E),s?d(E):e.next(E)},function(){y=!0},void 0,function(){if(y)try{u--;for(var E=function(){var _=c.shift();a?ue(e,a,function(){return m(_)}):m(_)};c.length&&u<n;)E();v()}catch(_){e.error(_)}}))};return t.subscribe(te(e,d,function(){f=!0,v()})),function(){i?.()}}function oe(t,e,r){return r===void 0&&(r=1/0),k(e)?oe(function(n,o){return nt(function(s,a){return e(n,s,o,a)})(ee(t(n,o)))},r):(typeof e=="number"&&(r=e),K(function(n,o){return Mo(n,o,t,r)}))}function mn(t){return t===void 0&&(t=1/0),oe(Tt,t)}function hn(t){return new H(function(e){ee(t()).subscribe(e)})}function Ht(t){return K(function(e,r){var n=null,o=!1,s;n=e.subscribe(te(r,void 0,void 0,function(a){s=ee(t(a,Ht(t)(e))),n?(n.unsubscribe(),n=null,s.subscribe(r)):o=!0})),o&&(n.unsubscribe(),n=null,s.subscribe(r))})}function wr(t,e){return k(e)?oe(t,e,1):oe(t,1)}function gn(t){return K(function(e,r){var n=!1;e.subscribe(te(r,function(o){n=!0,r.next(o)},function(){n||r.next(t),r.complete()}))})}function ot(t){return K(function(e,r){try{e.subscribe(r)}finally{r.add(t)}})}function Ar(t){return K(function(e,r){ee(t).subscribe(te(r,function(){return r.complete()},Ut)),!r.closed&&e.subscribe(r)})}function _n(t,e,r){var n=k(t)||e||r?{next:t,error:e,complete:r}:t;return n?K(function(o,s){var a;(a=n.subscribe)===null||a===void 0||a.call(n);var i=!0;o.subscribe(te(s,function(c){var u;(u=n.next)===null||u===void 0||u.call(n,c),s.next(c)},function(){var c;i=!1,(c=n.complete)===null||c===void 0||c.call(n),s.complete()},function(c){var u;i=!1,(u=n.error)===null||u===void 0||u.call(n,c),s.error(c)},function(){var c,u;i&&((c=n.unsubscribe)===null||c===void 0||c.call(n)),(u=n.finalize)===null||u===void 0||u.call(n)}))}):Tt}function Lo(t){return` \r
5
- `.indexOf(t)>=0}function Ir(t){for(var e=["topLevel"],r=0,n,o,s,a=function(_){return e.push(_)},i=function(_){return e[e.length-1]=_},c=function(_){n==null&&(n=r,o=e.length,s=_)},u=function(_){_===s&&(n=void 0,o=void 0,s=void 0)},p=function(){return e.pop()},f=function(){return r--},v=function(_){if("0"<=_&&_<="9"){a("number");return}switch(_){case'"':a("string");return;case"-":a("numberNeedsDigit");return;case"t":a("true");return;case"f":a("false");return;case"n":a("null");return;case"[":a("arrayNeedsValue");return;case"{":a("objectNeedsKey");return}},d=t.length;r<d;r++){var m=t[r];switch(e[e.length-1]){case"topLevel":v(m);break;case"string":switch(m){case'"':p();break;case"\\":c("stringEscape"),a("stringEscaped");break}break;case"stringEscaped":m==="u"?a("stringUnicode"):(u("stringEscape"),p());break;case"stringUnicode":r-t.lastIndexOf("u",r)===4&&(u("stringEscape"),p());break;case"number":m==="."?i("numberNeedsDigit"):m==="e"||m==="E"?i("numberNeedsExponent"):(m<"0"||m>"9")&&(f(),p());break;case"numberNeedsDigit":i("number");break;case"numberNeedsExponent":i(m==="+"||m==="-"?"numberNeedsDigit":"number");break;case"true":case"false":case"null":(m<"a"||m>"z")&&(f(),p());break;case"arrayNeedsValue":m==="]"?p():Lo(m)||(u("collectionItem"),i("arrayNeedsComma"),v(m));break;case"arrayNeedsComma":m==="]"?p():m===","&&(c("collectionItem"),i("arrayNeedsValue"));break;case"objectNeedsKey":m==="}"?p():m==='"'&&(c("collectionItem"),i("objectNeedsColon"),a("string"));break;case"objectNeedsColon":m===":"&&i("objectNeedsValue");break;case"objectNeedsValue":Lo(m)||(u("collectionItem"),i("objectNeedsComma"),v(m));break;case"objectNeedsComma":m==="}"?p():m===","&&(c("collectionItem"),i("objectNeedsKey"));break}}o!=null&&(e.length=o);for(var h=[n!=null?t.slice(0,n):t],y=function(_){return h.push(_.slice(t.length-t.lastIndexOf(_[0])))},E=e.length-1;E>=0;E--)switch(e[E]){case"string":h.push('"');break;case"numberNeedsDigit":case"numberNeedsExponent":h.push("0");break;case"true":y("true");break;case"false":y("false");break;case"null":y("null");break;case"arrayNeedsValue":case"arrayNeedsComma":h.push("]");break;case"objectNeedsKey":case"objectNeedsColon":case"objectNeedsValue":case"objectNeedsComma":h.push("}");break}return h.join("")}var jl=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,vn=t=>{if(typeof t!="string")throw new TypeError("Invalid argument expected string");let e=t.match(jl);if(!e)throw new Error(`Invalid argument not valid semver ('${t}' received)`);return e.shift(),e},Do=t=>t==="*"||t==="x"||t==="X",Uo=t=>{let e=parseInt(t,10);return isNaN(e)?t:e},Bl=(t,e)=>typeof t!=typeof e?[String(t),String(e)]:[t,e],Wl=(t,e)=>{if(Do(t)||Do(e))return 0;let[r,n]=Bl(Uo(t),Uo(e));return r>n?1:r<n?-1:0},yn=(t,e)=>{for(let r=0;r<Math.max(t.length,e.length);r++){let n=Wl(t[r]||"0",e[r]||"0");if(n!==0)return n}return 0};var Nr=(t,e)=>{let r=vn(t),n=vn(e),o=r.pop(),s=n.pop(),a=yn(r,n);return a!==0?a:o&&s?yn(o.split("."),s.split(".")):o||s?o?-1:1:0};var M=t=>{if(typeof structuredClone=="function")return structuredClone(t);try{return JSON.parse(JSON.stringify(t))}catch{return Array.isArray(t)?[...t]:{...t}}};function Vt(){return Ae()}function Sn(t){if(Object.freeze(t),typeof t=="object"&&t)for(let e of Object.values(t))typeof e=="object"&&e&&!Object.isFrozen(e)&&Sn(e);return t}async function L(t,e,r,n){let o=typeof process<"u"&&process.env!==void 0,s=o&&!!process.env.VITEST_WORKER_ID,a=o&&!!process.env.VITEST_WORKER_ID,i=M(e),c=M(r),u=i,p=c,f;for(let v of t)try{a&&(Sn(u),Sn(p));let d=await n(v,u,p);if(d===void 0)continue;if(d.messages!==void 0&&d.messages!==u&&(u=M(d.messages)),d.state!==void 0&&d.state!==p&&(p=M(d.state)),f=d.stopPropagation,f===!0)break}catch(d){if(a&&d instanceof TypeError){if(s)throw d;console.error("AG-UI: Subscriber attempted to mutate frozen inputs in-place. Return mutations via AgentStateMutation instead of mutating directly.",d)}else s||console.error("Subscriber error:",d);continue}return{...u===i?{}:{messages:a&&Object.isFrozen(u)?M(u):u},...p===c?{}:{state:a&&Object.isFrozen(p)?M(p):p},...f===void 0?{}:{stopPropagation:f}}}function Cr(t){if(!t)return{enabled:!1,events:!1,lifecycle:!1,verbose:!1};if(t===!0)return{enabled:!0,events:!0,lifecycle:!0,verbose:!0};let e=t.events??!0,r=t.lifecycle??!0,n=t.verbose??!1;return{enabled:e||r,events:e,lifecycle:r,verbose:n}}function Tn(t){if(t instanceof xn)return t;if(t===!0)return new xn(Cr(!0))}var xn=class{constructor(t){this.config=t}event(t,e,r,n){this.config.events&&(this.config.verbose?console.debug(`[${t}] ${e}`,typeof r=="string"?r:JSON.stringify(r)):console.debug(`[${t}] ${e}`,n??r))}lifecycle(t,e,r){this.config.lifecycle&&(r?console.debug(`[${t}] ${e}`,r):console.debug(`[${t}] ${e}`))}get eventsEnabled(){return this.config.events}get lifecycleEnabled(){return this.config.lifecycle}get enabled(){return this.config.enabled}};function En(t){return t.enabled?new xn(t):void 0}function Xl(t,e,r){if(e){let o=t.find(a=>a.id===e);if(o?.role==="assistant")return o;o&&console.warn(`TOOL_CALL_START: parentMessageId '${e}' matches a '${o.role}' message, not assistant \u2014 falling back to toolCallId`);let s={id:o?r:e,role:"assistant",toolCalls:[]};return t.push(s),s}let n={id:r,role:"assistant",toolCalls:[]};return t.push(n),n}var jo=(t,e,r,n,o)=>{let s=Tn(o),a=M(r.messages),i=M(t.state),c={},u=f=>{f.messages!==void 0&&(a=f.messages,c.messages=f.messages),f.state!==void 0&&(i=f.state,c.state=f.state)},p=()=>{let f=M(c);return c={},f.messages!==void 0||f.state!==void 0?j(f):dr};return e.pipe(wr(async f=>{let v=await L(n,a,i,(d,m,h)=>d.onEvent?.({event:f,agent:r,input:t,messages:m,state:h}));if(u(v),v.stopPropagation===!0?s?.event("APPLY","Event dropped:",f,{type:f.type,reason:"stopPropagation by subscriber"}):s?.event("APPLY","Event applied:",f,{type:f.type,subscribers:n.length}),v.stopPropagation===!0)return p();switch(f.type){case g.TEXT_MESSAGE_START:{let d=await L(n,a,i,(m,h,y)=>m.onTextMessageStartEvent?.({event:f,messages:h,state:y,agent:r,input:t}));if(u(d),d.stopPropagation!==!0){let{messageId:m,role:h="assistant",name:y}=f;if(!a.find(E=>E.id===m)){let E={id:m,role:h,content:"",...y!==void 0&&{name:y}};a.push(E),u({messages:a})}}return p()}case g.TEXT_MESSAGE_CONTENT:{let{messageId:d,delta:m}=f,h=a.find(E=>E.id===d);if(!h)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${d}'`),p();let y=await L(n,a,i,(E,_,I)=>E.onTextMessageContentEvent?.({event:f,messages:_,state:I,agent:r,input:t,textMessageBuffer:typeof h.content=="string"?h.content:""}));return u(y),y.stopPropagation!==!0&&(h.content=`${typeof h.content=="string"?h.content:""}${m}`,u({messages:a})),p()}case g.TEXT_MESSAGE_END:{let{messageId:d}=f,m=a.find(h=>h.id===d);return m?(u(await L(n,a,i,(h,y,E)=>h.onTextMessageEndEvent?.({event:f,messages:y,state:E,agent:r,input:t,textMessageBuffer:typeof m.content=="string"?m.content:""}))),await Promise.all(n.map(h=>{h.onNewMessage?.({message:m,messages:a,state:i,agent:r,input:t})})),p()):(console.warn(`TEXT_MESSAGE_END: No message found with ID '${d}'`),p())}case g.TOOL_CALL_START:{let d=await L(n,a,i,(m,h,y)=>m.onToolCallStartEvent?.({event:f,messages:h,state:y,agent:r,input:t}));if(u(d),d.stopPropagation!==!0){let{toolCallId:m,toolCallName:h,parentMessageId:y}=f,E=Xl(a,y,m);E.toolCalls??(E.toolCalls=[]),E.toolCalls.push({id:m,type:"function",function:{name:h,arguments:""}}),u({messages:a})}return p()}case g.TOOL_CALL_ARGS:{let{toolCallId:d,delta:m}=f,h=a.find(_=>_.toolCalls?.some(I=>I.id===d));if(!h)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${d}'`),p();let y=h.toolCalls?.find(_=>_.id===d);if(!y)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${d}'`),p();let E=await L(n,a,i,(_,I,$)=>{let Z=y.function.arguments,De=y.function.name,pe={};try{pe=Ir(Z)}catch{}return _.onToolCallArgsEvent?.({event:f,messages:I,state:$,agent:r,input:t,toolCallBuffer:Z,toolCallName:De,partialToolCallArgs:pe})});return u(E),E.stopPropagation!==!0&&(y.function.arguments+=m,u({messages:a})),p()}case g.TOOL_CALL_END:{let{toolCallId:d}=f,m=a.find(y=>y.toolCalls?.some(E=>E.id===d));if(!m)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${d}'`),p();let h=m.toolCalls?.find(y=>y.id===d);return h?(u(await L(n,a,i,(y,E,_)=>{let I=h.function.arguments,$=h.function.name,Z={};try{Z=JSON.parse(I)}catch{}return y.onToolCallEndEvent?.({event:f,messages:E,state:_,agent:r,input:t,toolCallName:$,toolCallArgs:Z})})),await Promise.all(n.map(y=>{y.onNewToolCall?.({toolCall:h,messages:a,state:i,agent:r,input:t})})),p()):(console.warn(`TOOL_CALL_END: No tool call found with ID '${d}'`),p())}case g.TOOL_CALL_RESULT:{let d=await L(n,a,i,(m,h,y)=>m.onToolCallResultEvent?.({event:f,messages:h,state:y,agent:r,input:t}));if(u(d),d.stopPropagation!==!0){let{messageId:m,toolCallId:h,content:y,role:E}=f,_={id:m,toolCallId:h,role:E||"tool",content:y};a.push(_),await Promise.all(n.map(I=>{I.onNewMessage?.({message:_,messages:a,state:i,agent:r,input:t})})),u({messages:a})}return p()}case g.STATE_SNAPSHOT:{let d=await L(n,a,i,(m,h,y)=>m.onStateSnapshotEvent?.({event:f,messages:h,state:y,agent:r,input:t}));if(u(d),d.stopPropagation!==!0){let{snapshot:m}=f;i=m,u({state:i})}return p()}case g.STATE_DELTA:{let d=await L(n,a,i,(m,h,y)=>m.onStateDeltaEvent?.({event:f,messages:h,state:y,agent:r,input:t}));if(u(d),d.stopPropagation!==!0){let{delta:m}=f;try{i=Oe(i,m,!0,!1).newDocument,u({state:i})}catch(h){let y=h instanceof Error?h.message:String(h);console.warn(`Failed to apply state patch:
4
+ `):"",this.name="UnsubscriptionError",this.errors=r}});function Dt(t,e){if(t){var r=t.indexOf(e);0<=r&&t.splice(r,1)}}var Et=(function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,r,n,o,s;if(!this.closed){this.closed=!0;var a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var i=Te(a),c=i.next();!c.done;c=i.next()){var u=c.value;u.remove(this)}}catch(h){e={error:h}}finally{try{c&&!c.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}else a.remove(this);var p=this.initialTeardown;if(k(p))try{p()}catch(h){s=h instanceof sr?h.errors:[h]}var f=this._finalizers;if(f){this._finalizers=null;try{for(var v=Te(f),d=v.next();!d.done;d=v.next()){var m=d.value;try{_o(m)}catch(h){s=s??[],h instanceof sr?s=vt(vt([],_t(s)),_t(h.errors)):s.push(h)}}}catch(h){n={error:h}}finally{try{d&&!d.done&&(o=v.return)&&o.call(v)}finally{if(n)throw n.error}}}if(s)throw new sr(s)}},t.prototype.add=function(e){var r;if(e&&e!==this)if(this.closed)_o(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(r=this._finalizers)!==null&&r!==void 0?r:[]).push(e)}},t.prototype._hasParent=function(e){var r=this._parentage;return r===e||Array.isArray(r)&&r.includes(e)},t.prototype._addParent=function(e){var r=this._parentage;this._parentage=Array.isArray(r)?(r.push(e),r):r?[r,e]:e},t.prototype._removeParent=function(e){var r=this._parentage;r===e?this._parentage=null:Array.isArray(r)&&Dt(r,e)},t.prototype.remove=function(e){var r=this._finalizers;r&&Dt(r,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})();var ln=Et.EMPTY;function ar(t){return t instanceof Et||t&&"closed"in t&&k(t.remove)&&k(t.add)&&k(t.unsubscribe)}function _o(t){k(t)?t():t.unsubscribe()}var fe={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var bt={setTimeout:function(t,e){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];var o=bt.delegate;return o?.setTimeout?o.setTimeout.apply(o,vt([t,e],_t(r))):setTimeout.apply(void 0,vt([t,e],_t(r)))},clearTimeout:function(t){var e=bt.delegate;return(e?.clearTimeout||clearTimeout)(t)},delegate:void 0};function ir(t){bt.setTimeout(function(){var e=fe.onUnhandledError;if(e)e(t);else throw t})}function Ut(){}var vo=(function(){return un("C",void 0,void 0)})();function yo(t){return un("E",void 0,t)}function Eo(t){return un("N",t,void 0)}function un(t,e,r){return{kind:t,value:e,error:r}}var rt=null;function St(t){if(fe.useDeprecatedSynchronousErrorHandling){var e=!rt;if(e&&(rt={errorThrown:!1,error:null}),t(),e){var r=rt,n=r.errorThrown,o=r.error;if(rt=null,n)throw o}}else t()}function bo(t){fe.useDeprecatedSynchronousErrorHandling&&rt&&(rt.errorThrown=!0,rt.error=t)}var Gt=(function(t){ve(e,t);function e(r){var n=t.call(this)||this;return n.isStopped=!1,r?(n.destination=r,ar(r)&&r.add(n)):n.destination=Pl,n}return e.create=function(r,n,o){return new ur(r,n,o)},e.prototype.next=function(r){this.isStopped?dn(Eo(r),this):this._next(r)},e.prototype.error=function(r){this.isStopped?dn(yo(r),this):(this.isStopped=!0,this._error(r))},e.prototype.complete=function(){this.isStopped?dn(vo,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(r){this.destination.next(r)},e.prototype._error=function(r){try{this.destination.error(r)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(Et);var kl=Function.prototype.bind;function cn(t,e){return kl.call(t,e)}var Rl=(function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var r=this.partialObserver;if(r.next)try{r.next(e)}catch(n){lr(n)}},t.prototype.error=function(e){var r=this.partialObserver;if(r.error)try{r.error(e)}catch(n){lr(n)}else lr(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(r){lr(r)}},t})(),ur=(function(t){ve(e,t);function e(r,n,o){var s=t.call(this)||this,a;if(k(r)||!r)a={next:r??void 0,error:n??void 0,complete:o??void 0};else{var i;s&&fe.useDeprecatedNextContext?(i=Object.create(r),i.unsubscribe=function(){return s.unsubscribe()},a={next:r.next&&cn(r.next,i),error:r.error&&cn(r.error,i),complete:r.complete&&cn(r.complete,i)}):a=r}return s.destination=new Rl(a),s}return e})(Gt);function lr(t){fe.useDeprecatedSynchronousErrorHandling?bo(t):ir(t)}function Ol(t){throw t}function dn(t,e){var r=fe.onStoppedNotification;r&&bt.setTimeout(function(){return r(t,e)})}var Pl={closed:!0,next:Ut,error:Ol,complete:Ut};var xt=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Tt(t){return t}function cr(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return fn(t)}function fn(t){return t.length===0?Tt:t.length===1?t[0]:function(r){return t.reduce(function(n,o){return o(n)},r)}}var H=(function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var r=new t;return r.source=this,r.operator=e,r},t.prototype.subscribe=function(e,r,n){var o=this,s=Ll(e)?e:new ur(e,r,n);return St(function(){var a=o,i=a.operator,c=a.source;s.add(i?i.call(s,c):c?o._subscribe(s):o._trySubscribe(s))}),s},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(r){e.error(r)}},t.prototype.forEach=function(e,r){var n=this;return r=So(r),new r(function(o,s){var a=new ur({next:function(i){try{e(i)}catch(c){s(c),a.unsubscribe()}},error:s,complete:o});n.subscribe(a)})},t.prototype._subscribe=function(e){var r;return(r=this.source)===null||r===void 0?void 0:r.subscribe(e)},t.prototype[xt]=function(){return this},t.prototype.pipe=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return fn(e)(this)},t.prototype.toPromise=function(e){var r=this;return e=So(e),new e(function(n,o){var s;r.subscribe(function(a){return s=a},function(a){return o(a)},function(){return n(s)})})},t.create=function(e){return new t(e)},t})();function So(t){var e;return(e=t??fe.Promise)!==null&&e!==void 0?e:Promise}function Ml(t){return t&&k(t.next)&&k(t.error)&&k(t.complete)}function Ll(t){return t&&t instanceof Gt||Ml(t)&&ar(t)}function Dl(t){return k(t?.lift)}function K(t){return function(e){if(Dl(e))return e.lift(function(r){try{return t(r,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}function te(t,e,r,n,o){return new Ul(t,e,r,n,o)}var Ul=(function(t){ve(e,t);function e(r,n,o,s,a,i){var c=t.call(this,r)||this;return c.onFinalize=a,c.shouldUnsubscribe=i,c._next=n?function(u){try{n(u)}catch(p){r.error(p)}}:t.prototype._next,c._error=s?function(u){try{s(u)}catch(p){r.error(p)}finally{this.unsubscribe()}}:t.prototype._error,c._complete=o?function(){try{o()}catch(u){r.error(u)}finally{this.unsubscribe()}}:t.prototype._complete,c}return e.prototype.unsubscribe=function(){var r;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;t.prototype.unsubscribe.call(this),!n&&((r=this.onFinalize)===null||r===void 0||r.call(this))}},e})(Gt);var xo=yt(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var nt=(function(t){ve(e,t);function e(){var r=t.call(this)||this;return r.closed=!1,r.currentObservers=null,r.observers=[],r.isStopped=!1,r.hasError=!1,r.thrownError=null,r}return e.prototype.lift=function(r){var n=new To(this,this);return n.operator=r,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new xo},e.prototype.next=function(r){var n=this;St(function(){var o,s;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var a=Te(n.currentObservers),i=a.next();!i.done;i=a.next()){var c=i.value;c.next(r)}}catch(u){o={error:u}}finally{try{i&&!i.done&&(s=a.return)&&s.call(a)}finally{if(o)throw o.error}}}})},e.prototype.error=function(r){var n=this;St(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=r;for(var o=n.observers;o.length;)o.shift().error(r)}})},e.prototype.complete=function(){var r=this;St(function(){if(r._throwIfClosed(),!r.isStopped){r.isStopped=!0;for(var n=r.observers;n.length;)n.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var r;return((r=this.observers)===null||r===void 0?void 0:r.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(r){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,r)},e.prototype._subscribe=function(r){return this._throwIfClosed(),this._checkFinalizedStatuses(r),this._innerSubscribe(r)},e.prototype._innerSubscribe=function(r){var n=this,o=this,s=o.hasError,a=o.isStopped,i=o.observers;return s||a?ln:(this.currentObservers=null,i.push(r),new Et(function(){n.currentObservers=null,Dt(i,r)}))},e.prototype._checkFinalizedStatuses=function(r){var n=this,o=n.hasError,s=n.thrownError,a=n.isStopped;o?r.error(s):a&&r.complete()},e.prototype.asObservable=function(){var r=new H;return r.source=this,r},e.create=function(r,n){return new To(r,n)},e})(H);var To=(function(t){ve(e,t);function e(r,n){var o=t.call(this)||this;return o.destination=r,o.source=n,o}return e.prototype.next=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.next)===null||o===void 0||o.call(n,r)},e.prototype.error=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.error)===null||o===void 0||o.call(n,r)},e.prototype.complete=function(){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.complete)===null||n===void 0||n.call(r)},e.prototype._subscribe=function(r){var n,o;return(o=(n=this.source)===null||n===void 0?void 0:n.subscribe(r))!==null&&o!==void 0?o:ln},e})(nt);var pn={now:function(){return(pn.delegate||Date).now()},delegate:void 0};var mn=(function(t){ve(e,t);function e(r,n,o){r===void 0&&(r=1/0),n===void 0&&(n=1/0),o===void 0&&(o=pn);var s=t.call(this)||this;return s._bufferSize=r,s._windowTime=n,s._timestampProvider=o,s._buffer=[],s._infiniteTimeWindow=!0,s._infiniteTimeWindow=n===1/0,s._bufferSize=Math.max(1,r),s._windowTime=Math.max(1,n),s}return e.prototype.next=function(r){var n=this,o=n.isStopped,s=n._buffer,a=n._infiniteTimeWindow,i=n._timestampProvider,c=n._windowTime;o||(s.push(r),!a&&s.push(i.now()+c)),this._trimBuffer(),t.prototype.next.call(this,r)},e.prototype._subscribe=function(r){this._throwIfClosed(),this._trimBuffer();for(var n=this._innerSubscribe(r),o=this,s=o._infiniteTimeWindow,a=o._buffer,i=a.slice(),c=0;c<i.length&&!r.closed;c+=s?1:2)r.next(i[c]);return this._checkFinalizedStatuses(r),n},e.prototype._trimBuffer=function(){var r=this,n=r._bufferSize,o=r._timestampProvider,s=r._buffer,a=r._infiniteTimeWindow,i=(a?1:2)*n;if(n<1/0&&i<s.length&&s.splice(0,s.length-i),!a){for(var c=o.now(),u=0,p=1;p<s.length&&s[p]<=c;p+=2)u=p;u&&s.splice(0,u+1)}},e})(nt);var dr=new H(function(t){return t.complete()});function wo(t){return t&&k(t.schedule)}function Gl(t){return t[t.length-1]}function Ao(t){return wo(Gl(t))?t.pop():void 0}var fr=(function(t){return t&&typeof t.length=="number"&&typeof t!="function"});function pr(t){return k(t?.then)}function mr(t){return k(t[xt])}function hr(t){return Symbol.asyncIterator&&k(t?.[Symbol.asyncIterator])}function gr(t){return new TypeError("You provided "+(t!==null&&typeof t=="object"?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Fl(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var _r=Fl();function vr(t){return k(t?.[_r])}function yr(t){return ho(this,arguments,function(){var r,n,o,s;return or(this,function(a){switch(a.label){case 0:r=t.getReader(),a.label=1;case 1:a.trys.push([1,,9,10]),a.label=2;case 2:return[4,tt(r.read())];case 3:return n=a.sent(),o=n.value,s=n.done,s?[4,tt(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,tt(o)];case 6:return[4,a.sent()];case 7:return a.sent(),[3,2];case 8:return[3,10];case 9:return r.releaseLock(),[7];case 10:return[2]}})})}function Er(t){return k(t?.getReader)}function ee(t){if(t instanceof H)return t;if(t!=null){if(mr(t))return Hl(t);if(fr(t))return Vl(t);if(pr(t))return $l(t);if(hr(t))return Io(t);if(vr(t))return jl(t);if(Er(t))return Bl(t)}throw gr(t)}function Hl(t){return new H(function(e){var r=t[xt]();if(k(r.subscribe))return r.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Vl(t){return new H(function(e){for(var r=0;r<t.length&&!e.closed;r++)e.next(t[r]);e.complete()})}function $l(t){return new H(function(e){t.then(function(r){e.closed||(e.next(r),e.complete())},function(r){return e.error(r)}).then(null,ir)})}function jl(t){return new H(function(e){var r,n;try{for(var o=Te(t),s=o.next();!s.done;s=o.next()){var a=s.value;if(e.next(a),e.closed)return}}catch(i){r={error:i}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}e.complete()})}function Io(t){return new H(function(e){Wl(t,e).catch(function(r){return e.error(r)})})}function Bl(t){return Io(yr(t))}function Wl(t,e){var r,n,o,s;return mo(this,void 0,void 0,function(){var a,i;return or(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),r=go(t),c.label=1;case 1:return[4,r.next()];case 2:if(n=c.sent(),!!n.done)return[3,4];if(a=n.value,e.next(a),e.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return i=c.sent(),o={error:i},[3,11];case 6:return c.trys.push([6,,9,10]),n&&!n.done&&(s=r.return)?[4,s.call(r)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function ue(t,e,r,n,o){n===void 0&&(n=0),o===void 0&&(o=!1);var s=e.schedule(function(){r(),o?t.add(this.schedule(null,n)):this.unsubscribe()},n);if(t.add(s),!o)return s}function br(t,e){return e===void 0&&(e=0),K(function(r,n){r.subscribe(te(n,function(o){return ue(n,t,function(){return n.next(o)},e)},function(){return ue(n,t,function(){return n.complete()},e)},function(o){return ue(n,t,function(){return n.error(o)},e)}))})}function Sr(t,e){return e===void 0&&(e=0),K(function(r,n){n.add(t.schedule(function(){return r.subscribe(n)},e))})}function No(t,e){return ee(t).pipe(Sr(e),br(e))}function Co(t,e){return ee(t).pipe(Sr(e),br(e))}function ko(t,e){return new H(function(r){var n=0;return e.schedule(function(){n===t.length?r.complete():(r.next(t[n++]),r.closed||this.schedule())})})}function Ro(t,e){return new H(function(r){var n;return ue(r,e,function(){n=t[_r](),ue(r,e,function(){var o,s,a;try{o=n.next(),s=o.value,a=o.done}catch(i){r.error(i);return}a?r.complete():r.next(s)},0,!0)}),function(){return k(n?.return)&&n.return()}})}function xr(t,e){if(!t)throw new Error("Iterable cannot be null");return new H(function(r){ue(r,e,function(){var n=t[Symbol.asyncIterator]();ue(r,e,function(){n.next().then(function(o){o.done?r.complete():r.next(o.value)})},0,!0)})})}function Oo(t,e){return xr(yr(t),e)}function Po(t,e){if(t!=null){if(mr(t))return No(t,e);if(fr(t))return ko(t,e);if(pr(t))return Co(t,e);if(hr(t))return xr(t,e);if(vr(t))return Ro(t,e);if(Er(t))return Oo(t,e)}throw gr(t)}function Ft(t,e){return e?Po(t,e):ee(t)}function j(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var r=Ao(t);return Ft(t,r)}function B(t,e){var r=k(t)?t:function(){return t},n=function(o){return o.error(r())};return new H(e?function(o){return e.schedule(n,0,o)}:n)}var Mo=yt(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function Tr(t,e){var r=typeof e=="object";return new Promise(function(n,o){var s=!1,a;t.subscribe({next:function(i){a=i,s=!0},error:o,complete:function(){s?n(a):r?n(e.defaultValue):o(new Mo)}})})}function ot(t,e){return K(function(r,n){var o=0;r.subscribe(te(n,function(s){n.next(t.call(e,s,o++))}))})}function Lo(t,e,r,n,o,s,a,i){var c=[],u=0,p=0,f=!1,v=function(){f&&!c.length&&!u&&e.complete()},d=function(h){return u<n?m(h):c.push(h)},m=function(h){s&&e.next(h),u++;var y=!1;ee(r(h,p++)).subscribe(te(e,function(E){o?.(E),s?d(E):e.next(E)},function(){y=!0},void 0,function(){if(y)try{u--;for(var E=function(){var _=c.shift();a?ue(e,a,function(){return m(_)}):m(_)};c.length&&u<n;)E();v()}catch(_){e.error(_)}}))};return t.subscribe(te(e,d,function(){f=!0,v()})),function(){i?.()}}function oe(t,e,r){return r===void 0&&(r=1/0),k(e)?oe(function(n,o){return ot(function(s,a){return e(n,s,o,a)})(ee(t(n,o)))},r):(typeof e=="number"&&(r=e),K(function(n,o){return Lo(n,o,t,r)}))}function hn(t){return t===void 0&&(t=1/0),oe(Tt,t)}function gn(t){return new H(function(e){ee(t()).subscribe(e)})}function Ht(t){return K(function(e,r){var n=null,o=!1,s;n=e.subscribe(te(r,void 0,void 0,function(a){s=ee(t(a,Ht(t)(e))),n?(n.unsubscribe(),n=null,s.subscribe(r)):o=!0})),o&&(n.unsubscribe(),n=null,s.subscribe(r))})}function wr(t,e){return k(e)?oe(t,e,1):oe(t,1)}function _n(t){return K(function(e,r){var n=!1;e.subscribe(te(r,function(o){n=!0,r.next(o)},function(){n||r.next(t),r.complete()}))})}function st(t){return K(function(e,r){try{e.subscribe(r)}finally{r.add(t)}})}function Ar(t){return K(function(e,r){ee(t).subscribe(te(r,function(){return r.complete()},Ut)),!r.closed&&e.subscribe(r)})}function vn(t,e,r){var n=k(t)||e||r?{next:t,error:e,complete:r}:t;return n?K(function(o,s){var a;(a=n.subscribe)===null||a===void 0||a.call(n);var i=!0;o.subscribe(te(s,function(c){var u;(u=n.next)===null||u===void 0||u.call(n,c),s.next(c)},function(){var c;i=!1,(c=n.complete)===null||c===void 0||c.call(n),s.complete()},function(c){var u;i=!1,(u=n.error)===null||u===void 0||u.call(n,c),s.error(c)},function(){var c,u;i&&((c=n.unsubscribe)===null||c===void 0||c.call(n)),(u=n.finalize)===null||u===void 0||u.call(n)}))}):Tt}function Do(t){return` \r
5
+ `.indexOf(t)>=0}function Ir(t){for(var e=["topLevel"],r=0,n,o,s,a=function(_){return e.push(_)},i=function(_){return e[e.length-1]=_},c=function(_){n==null&&(n=r,o=e.length,s=_)},u=function(_){_===s&&(n=void 0,o=void 0,s=void 0)},p=function(){return e.pop()},f=function(){return r--},v=function(_){if("0"<=_&&_<="9"){a("number");return}switch(_){case'"':a("string");return;case"-":a("numberNeedsDigit");return;case"t":a("true");return;case"f":a("false");return;case"n":a("null");return;case"[":a("arrayNeedsValue");return;case"{":a("objectNeedsKey");return}},d=t.length;r<d;r++){var m=t[r];switch(e[e.length-1]){case"topLevel":v(m);break;case"string":switch(m){case'"':p();break;case"\\":c("stringEscape"),a("stringEscaped");break}break;case"stringEscaped":m==="u"?a("stringUnicode"):(u("stringEscape"),p());break;case"stringUnicode":r-t.lastIndexOf("u",r)===4&&(u("stringEscape"),p());break;case"number":m==="."?i("numberNeedsDigit"):m==="e"||m==="E"?i("numberNeedsExponent"):(m<"0"||m>"9")&&(f(),p());break;case"numberNeedsDigit":i("number");break;case"numberNeedsExponent":i(m==="+"||m==="-"?"numberNeedsDigit":"number");break;case"true":case"false":case"null":(m<"a"||m>"z")&&(f(),p());break;case"arrayNeedsValue":m==="]"?p():Do(m)||(u("collectionItem"),i("arrayNeedsComma"),v(m));break;case"arrayNeedsComma":m==="]"?p():m===","&&(c("collectionItem"),i("arrayNeedsValue"));break;case"objectNeedsKey":m==="}"?p():m==='"'&&(c("collectionItem"),i("objectNeedsColon"),a("string"));break;case"objectNeedsColon":m===":"&&i("objectNeedsValue");break;case"objectNeedsValue":Do(m)||(u("collectionItem"),i("objectNeedsComma"),v(m));break;case"objectNeedsComma":m==="}"?p():m===","&&(c("collectionItem"),i("objectNeedsKey"));break}}o!=null&&(e.length=o);for(var h=[n!=null?t.slice(0,n):t],y=function(_){return h.push(_.slice(t.length-t.lastIndexOf(_[0])))},E=e.length-1;E>=0;E--)switch(e[E]){case"string":h.push('"');break;case"numberNeedsDigit":case"numberNeedsExponent":h.push("0");break;case"true":y("true");break;case"false":y("false");break;case"null":y("null");break;case"arrayNeedsValue":case"arrayNeedsComma":h.push("]");break;case"objectNeedsKey":case"objectNeedsColon":case"objectNeedsValue":case"objectNeedsComma":h.push("}");break}return h.join("")}var zl=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,yn=t=>{if(typeof t!="string")throw new TypeError("Invalid argument expected string");let e=t.match(zl);if(!e)throw new Error(`Invalid argument not valid semver ('${t}' received)`);return e.shift(),e},Uo=t=>t==="*"||t==="x"||t==="X",Go=t=>{let e=parseInt(t,10);return isNaN(e)?t:e},Kl=(t,e)=>typeof t!=typeof e?[String(t),String(e)]:[t,e],Zl=(t,e)=>{if(Uo(t)||Uo(e))return 0;let[r,n]=Kl(Go(t),Go(e));return r>n?1:r<n?-1:0},En=(t,e)=>{for(let r=0;r<Math.max(t.length,e.length);r++){let n=Zl(t[r]||"0",e[r]||"0");if(n!==0)return n}return 0};var Nr=(t,e)=>{let r=yn(t),n=yn(e),o=r.pop(),s=n.pop(),a=En(r,n);return a!==0?a:o&&s?En(o.split("."),s.split(".")):o||s?o?-1:1:0};var M=t=>{if(typeof structuredClone=="function")return structuredClone(t);try{return JSON.parse(JSON.stringify(t))}catch{return Array.isArray(t)?[...t]:{...t}}};function Vt(){return Ie()}function xn(t){if(Object.freeze(t),typeof t=="object"&&t)for(let e of Object.values(t))typeof e=="object"&&e&&!Object.isFrozen(e)&&xn(e);return t}async function L(t,e,r,n){let o=typeof process<"u"&&process.env!==void 0,s=o&&!!process.env.VITEST_WORKER_ID,a=o&&!!process.env.VITEST_WORKER_ID,i=M(e),c=M(r),u=i,p=c,f;for(let v of t)try{a&&(xn(u),xn(p));let d=await n(v,u,p);if(d===void 0)continue;if(d.messages!==void 0&&d.messages!==u&&(u=M(d.messages)),d.state!==void 0&&d.state!==p&&(p=M(d.state)),f=d.stopPropagation,f===!0)break}catch(d){if(a&&d instanceof TypeError){if(s)throw d;console.error("AG-UI: Subscriber attempted to mutate frozen inputs in-place. Return mutations via AgentStateMutation instead of mutating directly.",d)}else s||console.error("Subscriber error:",d);continue}return{...u===i?{}:{messages:a&&Object.isFrozen(u)?M(u):u},...p===c?{}:{state:a&&Object.isFrozen(p)?M(p):p},...f===void 0?{}:{stopPropagation:f}}}function Cr(t){if(!t)return{enabled:!1,events:!1,lifecycle:!1,verbose:!1};if(t===!0)return{enabled:!0,events:!0,lifecycle:!0,verbose:!0};let e=t.events??!0,r=t.lifecycle??!0,n=t.verbose??!1;return{enabled:e||r,events:e,lifecycle:r,verbose:n}}function wn(t){if(t instanceof Tn)return t;if(t===!0)return new Tn(Cr(!0))}var Tn=class{constructor(t){this.config=t}event(t,e,r,n){this.config.events&&(this.config.verbose?console.debug(`[${t}] ${e}`,typeof r=="string"?r:JSON.stringify(r)):console.debug(`[${t}] ${e}`,n??r))}lifecycle(t,e,r){this.config.lifecycle&&(r?console.debug(`[${t}] ${e}`,r):console.debug(`[${t}] ${e}`))}get eventsEnabled(){return this.config.events}get lifecycleEnabled(){return this.config.lifecycle}get enabled(){return this.config.enabled}};function bn(t){return t.enabled?new Tn(t):void 0}function Yl(t,e,r){if(e){let o=t.find(a=>a.id===e);if(o?.role==="assistant")return o;o&&console.warn(`TOOL_CALL_START: parentMessageId '${e}' matches a '${o.role}' message, not assistant \u2014 falling back to toolCallId`);let s={id:o?r:e,role:"assistant",toolCalls:[]};return t.push(s),s}let n={id:r,role:"assistant",toolCalls:[]};return t.push(n),n}var Bo=(t,e,r,n,o)=>{let s=wn(o),a=M(r.messages),i=M(t.state),c={},u=f=>{f.messages!==void 0&&(a=f.messages,c.messages=f.messages),f.state!==void 0&&(i=f.state,c.state=f.state)},p=()=>{let f=M(c);return c={},f.messages!==void 0||f.state!==void 0?j(f):dr};return e.pipe(wr(async f=>{let v=await L(n,a,i,(d,m,h)=>d.onEvent?.({event:f,agent:r,input:t,messages:m,state:h}));if(u(v),v.stopPropagation===!0?s?.event("APPLY","Event dropped:",f,{type:f.type,reason:"stopPropagation by subscriber"}):s?.event("APPLY","Event applied:",f,{type:f.type,subscribers:n.length}),v.stopPropagation===!0)return p();switch(f.type){case g.TEXT_MESSAGE_START:{let d=await L(n,a,i,(m,h,y)=>m.onTextMessageStartEvent?.({event:f,messages:h,state:y,agent:r,input:t}));if(u(d),d.stopPropagation!==!0){let{messageId:m,role:h="assistant",name:y}=f;if(!a.find(E=>E.id===m)){let E={id:m,role:h,content:"",...y!==void 0&&{name:y}};a.push(E),u({messages:a})}}return p()}case g.TEXT_MESSAGE_CONTENT:{let{messageId:d,delta:m}=f,h=a.find(E=>E.id===d);if(!h)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${d}'`),p();let y=await L(n,a,i,(E,_,I)=>E.onTextMessageContentEvent?.({event:f,messages:_,state:I,agent:r,input:t,textMessageBuffer:typeof h.content=="string"?h.content:""}));return u(y),y.stopPropagation!==!0&&(h.content=`${typeof h.content=="string"?h.content:""}${m}`,u({messages:a})),p()}case g.TEXT_MESSAGE_END:{let{messageId:d}=f,m=a.find(h=>h.id===d);return m?(u(await L(n,a,i,(h,y,E)=>h.onTextMessageEndEvent?.({event:f,messages:y,state:E,agent:r,input:t,textMessageBuffer:typeof m.content=="string"?m.content:""}))),await Promise.all(n.map(h=>{h.onNewMessage?.({message:m,messages:a,state:i,agent:r,input:t})})),p()):(console.warn(`TEXT_MESSAGE_END: No message found with ID '${d}'`),p())}case g.TOOL_CALL_START:{let d=await L(n,a,i,(m,h,y)=>m.onToolCallStartEvent?.({event:f,messages:h,state:y,agent:r,input:t}));if(u(d),d.stopPropagation!==!0){let{toolCallId:m,toolCallName:h,parentMessageId:y}=f,E=Yl(a,y,m);E.toolCalls??(E.toolCalls=[]),E.toolCalls.push({id:m,type:"function",function:{name:h,arguments:""}}),u({messages:a})}return p()}case g.TOOL_CALL_ARGS:{let{toolCallId:d,delta:m}=f,h=a.find(_=>_.toolCalls?.some(I=>I.id===d));if(!h)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${d}'`),p();let y=h.toolCalls?.find(_=>_.id===d);if(!y)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${d}'`),p();let E=await L(n,a,i,(_,I,$)=>{let Z=y.function.arguments,Ue=y.function.name,pe={};try{pe=Ir(Z)}catch{}return _.onToolCallArgsEvent?.({event:f,messages:I,state:$,agent:r,input:t,toolCallBuffer:Z,toolCallName:Ue,partialToolCallArgs:pe})});return u(E),E.stopPropagation!==!0&&(y.function.arguments+=m,u({messages:a})),p()}case g.TOOL_CALL_END:{let{toolCallId:d}=f,m=a.find(y=>y.toolCalls?.some(E=>E.id===d));if(!m)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${d}'`),p();let h=m.toolCalls?.find(y=>y.id===d);return h?(u(await L(n,a,i,(y,E,_)=>{let I=h.function.arguments,$=h.function.name,Z={};try{Z=JSON.parse(I)}catch{}return y.onToolCallEndEvent?.({event:f,messages:E,state:_,agent:r,input:t,toolCallName:$,toolCallArgs:Z})})),await Promise.all(n.map(y=>{y.onNewToolCall?.({toolCall:h,messages:a,state:i,agent:r,input:t})})),p()):(console.warn(`TOOL_CALL_END: No tool call found with ID '${d}'`),p())}case g.TOOL_CALL_RESULT:{let d=await L(n,a,i,(m,h,y)=>m.onToolCallResultEvent?.({event:f,messages:h,state:y,agent:r,input:t}));if(u(d),d.stopPropagation!==!0){let{messageId:m,toolCallId:h,content:y,role:E}=f,_={id:m,toolCallId:h,role:E||"tool",content:y};a.push(_),await Promise.all(n.map(I=>{I.onNewMessage?.({message:_,messages:a,state:i,agent:r,input:t})})),u({messages:a})}return p()}case g.STATE_SNAPSHOT:{let d=await L(n,a,i,(m,h,y)=>m.onStateSnapshotEvent?.({event:f,messages:h,state:y,agent:r,input:t}));if(u(d),d.stopPropagation!==!0){let{snapshot:m}=f;i=m,u({state:i})}return p()}case g.STATE_DELTA:{let d=await L(n,a,i,(m,h,y)=>m.onStateDeltaEvent?.({event:f,messages:h,state:y,agent:r,input:t}));if(u(d),d.stopPropagation!==!0){let{delta:m}=f;try{i=Oe(i,m,!0,!1).newDocument,u({state:i})}catch(h){let y=h instanceof Error?h.message:String(h);console.warn(`Failed to apply state patch:
6
6
  Current state: ${JSON.stringify(i,null,2)}
7
7
  Patch operations: ${JSON.stringify(m,null,2)}
8
- Error: ${y}`)}}return p()}case g.MESSAGES_SNAPSHOT:{let d=await L(n,a,i,(m,h,y)=>m.onMessagesSnapshotEvent?.({event:f,messages:h,state:y,agent:r,input:t}));if(u(d),d.stopPropagation!==!0){let{messages:m}=f,h=new Map(m.map(_=>[_.id,_])),y=_=>_==="activity"||_==="reasoning";a=a.filter(_=>y(_.role)||h.has(_.id)).map(_=>y(_.role)?_:h.get(_.id));let E=new Set(a.map(_=>_.id));for(let _ of m)E.has(_.id)||a.push(_);u({messages:a})}return p()}case g.ACTIVITY_SNAPSHOT:{let d=f,m=a.findIndex(I=>I.id===d.messageId),h=m>=0?a[m]:void 0,y=h?.role==="activity"?h:void 0,E=d.replace??!0,_=await L(n,a,i,(I,$,Z)=>I.onActivitySnapshotEvent?.({event:d,messages:$,state:Z,agent:r,input:t,activityMessage:y,existingMessage:h}));if(u(_),_.stopPropagation!==!0){let I={id:d.messageId,role:"activity",activityType:d.activityType,content:M(d.content)},$;m===-1?(a.push(I),$=I):y?E&&(a[m]={...y,activityType:d.activityType,content:M(d.content)}):E&&(a[m]=I,$=I),u({messages:a}),$&&await Promise.all(n.map(Z=>Z.onNewMessage?.({message:$,messages:a,state:i,agent:r,input:t})))}return p()}case g.ACTIVITY_DELTA:{let d=f,m=a.findIndex(_=>_.id===d.messageId);if(m===-1)return p();let h=a[m];if(h.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${d.messageId}' is not an activity message`),p();let y=h,E=await L(n,a,i,(_,I,$)=>_.onActivityDeltaEvent?.({event:d,messages:I,state:$,agent:r,input:t,activityMessage:y}));if(u(E),E.stopPropagation!==!0)try{let _=M(y.content??{}),I=Oe(_,d.patch??[],!0,!1).newDocument;a[m]={...y,content:M(I),activityType:d.activityType},u({messages:a})}catch(_){let I=_ instanceof Error?_.message:String(_);console.warn(`Failed to apply activity patch for '${d.messageId}': ${I}`)}return p()}case g.RAW:return u(await L(n,a,i,(d,m,h)=>d.onRawEvent?.({event:f,messages:m,state:h,agent:r,input:t}))),p();case g.CUSTOM:return u(await L(n,a,i,(d,m,h)=>d.onCustomEvent?.({event:f,messages:m,state:h,agent:r,input:t}))),p();case g.RUN_STARTED:{let d=await L(n,a,i,(m,h,y)=>m.onRunStartedEvent?.({event:f,messages:h,state:y,agent:r,input:t}));if(u(d),d.stopPropagation!==!0){let m=f;if(m.input?.messages){for(let h of m.input.messages)a.find(y=>y.id===h.id)||a.push(h);u({messages:a})}}return p()}case g.RUN_FINISHED:return u(await L(n,a,i,(d,m,h)=>d.onRunFinishedEvent?.({event:f,messages:m,state:h,agent:r,input:t,result:f.result}))),p();case g.RUN_ERROR:return u(await L(n,a,i,(d,m,h)=>d.onRunErrorEvent?.({event:f,messages:m,state:h,agent:r,input:t}))),p();case g.STEP_STARTED:return u(await L(n,a,i,(d,m,h)=>d.onStepStartedEvent?.({event:f,messages:m,state:h,agent:r,input:t}))),p();case g.STEP_FINISHED:return u(await L(n,a,i,(d,m,h)=>d.onStepFinishedEvent?.({event:f,messages:m,state:h,agent:r,input:t}))),p();case g.TEXT_MESSAGE_CHUNK:throw Error("TEXT_MESSAGE_CHUNK must be tranformed before being applied");case g.TOOL_CALL_CHUNK:throw Error("TOOL_CALL_CHUNK must be tranformed before being applied");case g.THINKING_START:return p();case g.THINKING_END:return p();case g.THINKING_TEXT_MESSAGE_START:return p();case g.THINKING_TEXT_MESSAGE_CONTENT:return p();case g.THINKING_TEXT_MESSAGE_END:return p();case g.REASONING_START:return u(await L(n,a,i,(d,m,h)=>d.onReasoningStartEvent?.({event:f,messages:m,state:h,agent:r,input:t}))),p();case g.REASONING_MESSAGE_START:{let d=await L(n,a,i,(m,h,y)=>m.onReasoningMessageStartEvent?.({event:f,messages:h,state:y,agent:r,input:t}));if(u(d),d.stopPropagation!==!0){let{messageId:m}=f;if(!a.find(h=>h.id===m)){let h={id:m,role:"reasoning",content:""};a.push(h),u({messages:a})}}return p()}case g.REASONING_MESSAGE_CONTENT:{let{messageId:d,delta:m}=f,h=a.find(E=>E.id===d);if(!h)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${d}'`),p();let y=await L(n,a,i,(E,_,I)=>E.onReasoningMessageContentEvent?.({event:f,messages:_,state:I,agent:r,input:t,reasoningMessageBuffer:typeof h.content=="string"?h.content:""}));return u(y),y.stopPropagation!==!0&&(h.content=`${typeof h.content=="string"?h.content:""}${m}`,u({messages:a})),p()}case g.REASONING_MESSAGE_END:{let{messageId:d}=f,m=a.find(h=>h.id===d);return m?(u(await L(n,a,i,(h,y,E)=>h.onReasoningMessageEndEvent?.({event:f,messages:y,state:E,agent:r,input:t,reasoningMessageBuffer:typeof m.content=="string"?m.content:""}))),await Promise.all(n.map(h=>{h.onNewMessage?.({message:m,messages:a,state:i,agent:r,input:t})})),p()):(console.warn(`REASONING_MESSAGE_END: No message found with ID '${d}'`),p())}case g.REASONING_MESSAGE_CHUNK:throw Error("REASONING_MESSAGE_CHUNK must be transformed before being applied");case g.REASONING_END:return u(await L(n,a,i,(d,m,h)=>d.onReasoningEndEvent?.({event:f,messages:m,state:h,agent:r,input:t}))),p();case g.REASONING_ENCRYPTED_VALUE:{let{subtype:d,entityId:m,encryptedValue:h}=f,y=await L(n,a,i,(E,_,I)=>E.onReasoningEncryptedValueEvent?.({event:f,messages:_,state:I,agent:r,input:t}));if(u(y),y.stopPropagation!==!0){let E=!1;if(d==="tool-call"){for(let _ of a)if(_.role==="assistant"&&_.toolCalls){let I=_.toolCalls.find($=>$.id===m);if(I){I.encryptedValue=h,E=!0;break}}}else{let _=a.find(I=>I.id===m);_?.role!=="activity"&&_&&(_.encryptedValue=h,E=!0)}E&&(c.messages=a)}return p()}}return f.type,p()}),mn(),n.length>0?gn({}):f=>f)},bn=t=>e=>{let r=Tn(t),n=new Map,o=new Map,s=!1,a=!1,i=!1,c=new Map,u=!1,p=!1,f=!1,v=()=>{n.clear(),o.clear(),c.clear(),u=!1,p=!1,s=!1,a=!1,f=!0};return e.pipe(oe(d=>{let m=d.type;if(r?.event("VERIFY","Event:",d,{type:d.type}),a)return B(()=>new F(`Cannot send event type '${m}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(s&&m!==g.RUN_ERROR&&m!==g.RUN_STARTED)return B(()=>new F(`Cannot send event type '${m}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(i){if(m===g.RUN_STARTED){if(f&&!s)return B(()=>new F("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&&v()}}else if(i=!0,m!==g.RUN_STARTED&&m!==g.RUN_ERROR)return B(()=>new F("First event must be 'RUN_STARTED'"));switch(m){case g.TEXT_MESSAGE_START:{let h=d.messageId;return n.has(h)?B(()=>new F(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${h}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(n.set(h,!0),j(d))}case g.TEXT_MESSAGE_CONTENT:{let h=d.messageId;return n.has(h)?j(d):B(()=>new F(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${h}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case g.TEXT_MESSAGE_END:{let h=d.messageId;return n.has(h)?(n.delete(h),j(d)):B(()=>new F(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${h}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case g.TOOL_CALL_START:{let h=d.toolCallId;return o.has(h)?B(()=>new F(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${h}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(o.set(h,!0),j(d))}case g.TOOL_CALL_ARGS:{let h=d.toolCallId;return o.has(h)?j(d):B(()=>new F(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${h}'. Start a tool call with 'TOOL_CALL_START' first.`))}case g.TOOL_CALL_END:{let h=d.toolCallId;return o.has(h)?(o.delete(h),j(d)):B(()=>new F(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${h}'. A 'TOOL_CALL_START' event must be sent first.`))}case g.STEP_STARTED:{let h=d.stepName;return c.has(h)?B(()=>new F(`Step "${h}" is already active for 'STEP_STARTED'`)):(c.set(h,!0),j(d))}case g.STEP_FINISHED:{let h=d.stepName;return c.has(h)?(c.delete(h),j(d)):B(()=>new F(`Cannot send 'STEP_FINISHED' for step "${h}" that was not started`))}case g.RUN_STARTED:return f=!0,j(d);case g.RUN_FINISHED:if(c.size>0){let h=Array.from(c.keys()).join(", ");return B(()=>new F(`Cannot send 'RUN_FINISHED' while steps are still active: ${h}`))}if(n.size>0){let h=Array.from(n.keys()).join(", ");return B(()=>new F(`Cannot send 'RUN_FINISHED' while text messages are still active: ${h}`))}if(o.size>0){let h=Array.from(o.keys()).join(", ");return B(()=>new F(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${h}`))}return s=!0,j(d);case g.RUN_ERROR:return a=!0,j(d);case g.CUSTOM:return j(d);case g.THINKING_TEXT_MESSAGE_START:return u?p?B(()=>new F("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(p=!0,j(d)):B(()=>new F("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case g.THINKING_TEXT_MESSAGE_CONTENT:return p?j(d):B(()=>new F("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case g.THINKING_TEXT_MESSAGE_END:return p?(p=!1,j(d)):B(()=>new F("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case g.THINKING_START:return u?B(()=>new F("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(u=!0,j(d));case g.THINKING_END:return u?(u=!1,j(d)):B(()=>new F("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return j(d)}}))},ah=(function(t){return t.HEADERS="headers",t.DATA="data",t})({});var V=l.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),zl=l.enum(["LangGraphInterruptEvent","PredictState","Exit"]),Kl=l.object({type:l.literal(V.enum.TextMessageStart),messageId:l.string(),parentMessageId:l.string().optional(),role:l.string().optional()}),Zl=l.object({type:l.literal(V.enum.TextMessageContent),messageId:l.string(),content:l.string()}),Yl=l.object({type:l.literal(V.enum.TextMessageEnd),messageId:l.string()}),ql=l.object({type:l.literal(V.enum.ActionExecutionStart),actionExecutionId:l.string(),actionName:l.string(),parentMessageId:l.string().optional()}),Jl=l.object({type:l.literal(V.enum.ActionExecutionArgs),actionExecutionId:l.string(),args:l.string()}),Ql=l.object({type:l.literal(V.enum.ActionExecutionEnd),actionExecutionId:l.string()}),eu=l.object({type:l.literal(V.enum.ActionExecutionResult),actionName:l.string(),actionExecutionId:l.string(),result:l.string()}),tu=l.object({type:l.literal(V.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()}),ru=l.object({type:l.literal(V.enum.MetaEvent),name:zl,value:l.any()}),nu=l.object({type:l.literal(V.enum.RunError),message:l.string(),code:l.string().optional()});l.discriminatedUnion("type",[Kl,Zl,Yl,ql,Jl,Ql,eu,tu,ru,nu]),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 ou=t=>{if(typeof t=="string")return t;if(!Array.isArray(t))return;let e=t.filter(r=>r.type==="text").map(r=>r.text).filter(r=>r.length>0);if(e.length!==0)return e.join(`
9
- `)},su=(t,e,r)=>n=>{let o={},s=!0,a=!0,i="",c=null,u=null,p=[],f={},v=d=>{typeof d=="object"&&d&&("messages"in d&&delete d.messages,o=d)};return n.pipe(oe(d=>{switch(d.type){case g.TEXT_MESSAGE_START:{let m=d;return[{type:V.enum.TextMessageStart,messageId:m.messageId,role:m.role}]}case g.TEXT_MESSAGE_CONTENT:{let m=d;return[{type:V.enum.TextMessageContent,messageId:m.messageId,content:m.delta}]}case g.TEXT_MESSAGE_END:{let m=d;return[{type:V.enum.TextMessageEnd,messageId:m.messageId}]}case g.TOOL_CALL_START:{let m=d;return p.push({id:m.toolCallId,type:"function",function:{name:m.toolCallName,arguments:""}}),a=!0,f[m.toolCallId]=m.toolCallName,[{type:V.enum.ActionExecutionStart,actionExecutionId:m.toolCallId,actionName:m.toolCallName,parentMessageId:m.parentMessageId}]}case g.TOOL_CALL_ARGS:{let m=d,h=p.find(E=>E.id===m.toolCallId);if(!h)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${m.toolCallId}'`),[];h.function.arguments+=m.delta;let y=!1;if(u){let E=u.find(_=>_.tool==h.function.name);if(E)try{let _=JSON.parse(Ir(h.function.arguments));E.tool_argument&&E.tool_argument in _?(v({...o,[E.state_key]:_[E.tool_argument]}),y=!0):E.tool_argument||(v({...o,[E.state_key]:_}),y=!0)}catch{}}return[{type:V.enum.ActionExecutionArgs,actionExecutionId:m.toolCallId,args:m.delta},...y?[{type:V.enum.AgentStateMessage,threadId:t,agentName:r,nodeName:i,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:a}]:[]]}case g.TOOL_CALL_END:{let m=d;return[{type:V.enum.ActionExecutionEnd,actionExecutionId:m.toolCallId}]}case g.TOOL_CALL_RESULT:{let m=d;return[{type:V.enum.ActionExecutionResult,actionExecutionId:m.toolCallId,result:m.content,actionName:f[m.toolCallId]||"unknown"}]}case g.RAW:return[];case g.CUSTOM:{let m=d;switch(m.name){case"Exit":s=!1;break;case"PredictState":u=m.value;break}return[{type:V.enum.MetaEvent,name:m.name,value:m.value}]}case g.STATE_SNAPSHOT:return v(d.snapshot),[{type:V.enum.AgentStateMessage,threadId:t,agentName:r,nodeName:i,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:a}];case g.STATE_DELTA:{let m=d,h=Oe(o,m.delta,!0,!1);return h?(v(h.newDocument),[{type:V.enum.AgentStateMessage,threadId:t,agentName:r,nodeName:i,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:a}]):[]}case g.MESSAGES_SNAPSHOT:return c=d.messages,[{type:V.enum.AgentStateMessage,threadId:t,agentName:r,nodeName:i,runId:e,running:s,role:"assistant",state:JSON.stringify({...o,...c?{messages:c}:{}}),active:!0}];case g.RUN_STARTED:return[];case g.RUN_FINISHED:return c&&(o.messages=c),Object.keys(o).length===0?[]:[{type:V.enum.AgentStateMessage,threadId:t,agentName:r,nodeName:i,runId:e,running:s,role:"assistant",state:JSON.stringify({...o,...c?{messages:au(c)}:{}}),active:!1}];case g.RUN_ERROR:{let m=d;return[{type:V.enum.RunError,message:m.message,code:m.code}]}case g.STEP_STARTED:return i=d.stepName,p=[],u=null,[{type:V.enum.AgentStateMessage,threadId:t,agentName:r,nodeName:i,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:!0}];case g.STEP_FINISHED:return p=[],u=null,[{type:V.enum.AgentStateMessage,threadId:t,agentName:r,nodeName:i,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:!1}];default:return[]}}))};function au(t){let e=[];for(let r of t)if(r.role==="assistant"||r.role==="user"||r.role==="system"){let n=ou(r.content);if(n){let o={id:r.id,role:r.role,content:n};e.push(o)}if(r.role==="assistant"&&r.toolCalls&&r.toolCalls.length>0)for(let o of r.toolCalls){let s={id:o.id,name:o.function.name,arguments:JSON.parse(o.function.arguments),parentMessageId:r.id};e.push(s)}}else if(r.role==="tool"){let n="unknown";for(let s of t)if(s.role==="assistant"&&s.toolCalls?.length){for(let a of s.toolCalls)if(a.id===r.toolCallId){n=a.function.name;break}}let o={id:r.id,result:r.content,actionExecutionId:r.toolCallId,actionName:n};e.push(o)}return e}var kr=t=>e=>{let r=Tn(t),n,o,s,a,i=()=>{if(!n||a!=="text")throw Error("No text message to close");let f={type:g.TEXT_MESSAGE_END,messageId:n.messageId};return a=void 0,n=void 0,r?.event("TRANSFORM","TEXT_MESSAGE_END",f,{messageId:f.messageId}),f},c=()=>{if(!o||a!=="tool")throw Error("No tool call to close");let f={type:g.TOOL_CALL_END,toolCallId:o.toolCallId};return a=void 0,o=void 0,r?.event("TRANSFORM","TOOL_CALL_END",f,{toolCallId:f.toolCallId}),f},u=()=>{if(!s||a!=="reasoning")throw Error("No reasoning message to close");let f={type:g.REASONING_MESSAGE_END,messageId:s.messageId};return a=void 0,s=void 0,r?.event("TRANSFORM","REASONING_MESSAGE_END",f,{messageId:f.messageId}),f},p=()=>a==="text"?[i()]:a==="tool"?[c()]:a==="reasoning"?[u()]:[];return e.pipe(oe(f=>{switch(f.type){case g.TEXT_MESSAGE_START:case g.TEXT_MESSAGE_CONTENT:case g.TEXT_MESSAGE_END:case g.TOOL_CALL_START:case g.TOOL_CALL_ARGS:case g.TOOL_CALL_END:case g.TOOL_CALL_RESULT:case g.STATE_SNAPSHOT:case g.STATE_DELTA:case g.MESSAGES_SNAPSHOT:case g.CUSTOM:case g.RUN_STARTED:case g.RUN_FINISHED:case g.RUN_ERROR:case g.STEP_STARTED:case g.STEP_FINISHED:case g.THINKING_START:case g.THINKING_END:case g.THINKING_TEXT_MESSAGE_START:case g.THINKING_TEXT_MESSAGE_CONTENT:case g.THINKING_TEXT_MESSAGE_END:case g.REASONING_START:case g.REASONING_MESSAGE_START:case g.REASONING_MESSAGE_CONTENT:case g.REASONING_MESSAGE_END:case g.REASONING_END:return[...p(),f];case g.RAW:case g.ACTIVITY_SNAPSHOT:case g.ACTIVITY_DELTA:case g.REASONING_ENCRYPTED_VALUE:return[f];case g.TEXT_MESSAGE_CHUNK:let v=f,d=[];if((a!=="text"||v.messageId!==void 0&&v.messageId!==n?.messageId)&&d.push(...p()),a!=="text"){if(v.messageId===void 0)throw Error("First TEXT_MESSAGE_CHUNK must have a messageId");n={messageId:v.messageId,name:v.name},a="text";let _={type:g.TEXT_MESSAGE_START,messageId:v.messageId,role:v.role||"assistant",...v.name!==void 0&&{name:v.name}};d.push(_),r?.event("TRANSFORM","TEXT_MESSAGE_START",_,{messageId:v.messageId})}if(v.delta!==void 0){let _={type:g.TEXT_MESSAGE_CONTENT,messageId:n.messageId,delta:v.delta};d.push(_),r?.event("TRANSFORM","TEXT_MESSAGE_CONTENT",_,{messageId:n.messageId})}return d;case g.TOOL_CALL_CHUNK:let m=f,h=[];if((a!=="tool"||m.toolCallId!==void 0&&m.toolCallId!==o?.toolCallId)&&h.push(...p()),a!=="tool"){if(m.toolCallId===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallId");if(m.toolCallName===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallName");o={toolCallId:m.toolCallId,toolCallName:m.toolCallName,parentMessageId:m.parentMessageId},a="tool";let _={type:g.TOOL_CALL_START,toolCallId:m.toolCallId,toolCallName:m.toolCallName,parentMessageId:m.parentMessageId};h.push(_),r?.event("TRANSFORM","TOOL_CALL_START",_,{toolCallId:m.toolCallId,toolCallName:m.toolCallName})}if(m.delta!==void 0){let _={type:g.TOOL_CALL_ARGS,toolCallId:o.toolCallId,delta:m.delta};h.push(_),r?.event("TRANSFORM","TOOL_CALL_ARGS",_,{toolCallId:o.toolCallId})}return h;case g.REASONING_MESSAGE_CHUNK:let y=f,E=[];if((a!=="reasoning"||y.messageId&&y.messageId!==s?.messageId)&&E.push(...p()),a!=="reasoning"){if(y.messageId===void 0)throw Error("First REASONING_MESSAGE_CHUNK must have a messageId");s={messageId:y.messageId},a="reasoning";let _={type:g.REASONING_MESSAGE_START,messageId:y.messageId};E.push(_),r?.event("TRANSFORM","REASONING_MESSAGE_START",_,{messageId:y.messageId})}if(y.delta!==void 0){let _={type:g.REASONING_MESSAGE_CONTENT,messageId:s.messageId,delta:y.delta};E.push(_),r?.event("TRANSFORM","REASONING_MESSAGE_CONTENT",_,{messageId:s.messageId})}return E}return f.type,[]}),ot(()=>{p()}))},wn=class{runNext(t,e){return e.run(t).pipe(kr(!1))}runNextWithState(t,e){let r=M(t.messages||[]),n=M(t.state||{}),o=new pn;return jo(t,o,e,[]).subscribe(s=>{s.messages!==void 0&&(r=s.messages),s.state!==void 0&&(n=s.state)}),this.runNext(t,e).pipe(wr(async s=>(o.next(s),await new Promise(a=>setTimeout(a,0)),{event:s,messages:M(r),state:M(n)})))}},iu=class extends wn{constructor(t){super(),this.fn=t}run(t,e){return this.fn(t,e)}};function lu(t){let e=t.content;if(Array.isArray(e)){let r=e.filter(n=>typeof n=="object"&&!!n&&"type"in n&&n.type==="text"&&typeof n.text=="string").map(n=>n.text).join("");return{...t,content:r}}return typeof e=="string"?t:{...t,content:""}}var uu=class extends wn{run(t,e){let{parentRunId:r,...n}=t,o={...n,messages:n.messages.map(lu)};return this.runNext(o,e)}},Go="THINKING_START",Fo="THINKING_END",Ho="THINKING_TEXT_MESSAGE_START",Vo="THINKING_TEXT_MESSAGE_CONTENT",$o="THINKING_TEXT_MESSAGE_END",cu=class extends wn{constructor(...t){super(...t),this.currentReasoningId=null,this.currentMessageId=null}warnAboutTransformation(t,e){typeof process<"u"&&process.env!==void 0&&process.env.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is converting ${t} to ${e}. To remove this warning, upgrade your AG-UI integration package (e.g. @ag-ui/langgraph). To surpress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(t,e){return this.currentReasoningId=null,this.currentMessageId=null,this.runNext(t,e).pipe(nt(r=>this.transformEvent(r)))}transformEvent(t){switch(t.type){case Go:{this.currentReasoningId=Vt();let{title:e,...r}=t;return this.warnAboutTransformation(Go,g.REASONING_START),{...r,type:g.REASONING_START,messageId:this.currentReasoningId}}case Ho:return this.currentMessageId=Vt(),this.warnAboutTransformation(Ho,g.REASONING_MESSAGE_START),{...t,type:g.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:"assistant"};case Vo:{let{delta:e,...r}=t;return this.warnAboutTransformation(Vo,g.REASONING_MESSAGE_CONTENT),{...r,type:g.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??Vt(),delta:e}}case $o:{let e=this.currentMessageId??Vt();return this.warnAboutTransformation($o,g.REASONING_MESSAGE_END),{...t,type:g.REASONING_MESSAGE_END,messageId:e}}case Fo:{let e=this.currentReasoningId??Vt();return this.warnAboutTransformation(Fo,g.REASONING_END),{...t,type:g.REASONING_END,messageId:e}}default:return t}}},du="0.0.52",Or=class{get maxVersion(){return du}get debug(){return this._debug}set debug(t){this._debug=Cr(t),this._debugLogger=En(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(t){typeof t=="boolean"?this._debugLogger=t?En(Cr(!0)):void 0:this._debugLogger=t}constructor({agentId:t,description:e,threadId:r,initialMessages:n,initialState:o,debug:s}={}){this.subscribers=[],this.isRunning=!1,this.middlewares=[],this.agentId=t,this.description=e??"",this.threadId=r??Ae(),this.messages=M(n??[]),this.state=M(o??{}),this._debug=Cr(s),this._debugLogger=En(this._debug),Nr(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new uu),Nr(this.maxVersion,"0.0.45")<=0&&this.middlewares.unshift(new cu)}subscribe(t){return this.subscribers.push(t),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(e=>e!==t)}}}use(...t){let e=t.map(r=>typeof r=="function"?new iu(r):r);return this.middlewares.push(...e),this}async runAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??Ae();let r=this.prepareRunAgentInput(t);this.debugLogger?.lifecycle("LIFECYCLE","Run started:",{agentId:this.agentId,threadId:this.threadId});let n,o=new Set(this.messages.map(c=>c.id)),s=[{onRunFinishedEvent:c=>{n=c.result}},...this.subscribers,e??{}];await this.onInitialize(r,s),this.activeRunDetach$=new rt;let a;this.activeRunCompletionPromise=new Promise(c=>{a=c}),await Tr(cr(()=>this.middlewares.length===0?this.run(r):this.middlewares.reduceRight((c,u)=>({run:p=>u.run(p,c),get messages(){return c.messages},get state(){return c.state}}),this).run(r),kr(this.debugLogger),bn(this.debugLogger),c=>c.pipe(Ar(this.activeRunDetach$)),c=>this.apply(r,c,s),c=>this.processApplyEvents(r,c,s),Ht(c=>(this.debugLogger?.lifecycle("LIFECYCLE","Run errored:",{agentId:this.agentId,error:c instanceof Error?c.message:String(c)}),this.isRunning=!1,this.onError(r,c,s))),ot(()=>{this.debugLogger?.lifecycle("LIFECYCLE","Run finished:",{agentId:this.agentId,threadId:this.threadId}),this.isRunning=!1,this.onFinalize(r,s),a?.(),a=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(j(null)));let i=M(this.messages).filter(c=>!o.has(c.id));return{result:n,newMessages:i}}finally{this.isRunning=!1}}connect(t){throw new Qr}async connectAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??Ae();let r=this.prepareRunAgentInput(t),n,o=new Set(this.messages.map(c=>c.id)),s=[{onRunFinishedEvent:c=>{n=c.result}},...this.subscribers,e??{}];await this.onInitialize(r,s),this.activeRunDetach$=new rt;let a;this.activeRunCompletionPromise=new Promise(c=>{a=c}),await Tr(cr(()=>hn(()=>this.connect(r)),kr(this.debugLogger),bn(this.debugLogger),c=>c.pipe(Ar(this.activeRunDetach$)),c=>this.apply(r,c,s),c=>this.processApplyEvents(r,c,s),Ht(c=>(this.isRunning=!1,c instanceof Qr?dr:this.onError(r,c,s))),ot(()=>{this.isRunning=!1,this.onFinalize(r,s),a?.(),a=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(j(null)),{defaultValue:void 0});let i=M(this.messages).filter(c=>!o.has(c.id));return{result:n,newMessages:i}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let t=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await t}apply(t,e,r){return jo(t,e,this,r,this.debugLogger)}processApplyEvents(t,e,r){return e.pipe(_n(n=>{n.messages&&(this.messages=n.messages,r.forEach(o=>{o.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),n.state&&(this.state=n.state,r.forEach(o=>{o.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))}))}prepareRunAgentInput(t){let e=M(this.messages).filter(r=>r.role!=="activity");return{threadId:this.threadId,runId:t?.runId||Ae(),tools:M(t?.tools??[]),context:M(t?.context??[]),forwardedProps:M(t?.forwardedProps??{}),state:M(this.state),messages:e}}async onInitialize(t,e){let r=await L(e,this.messages,this.state,(n,o,s)=>n.onRunInitialized?.({messages:o,state:s,agent:this,input:t}));(r.messages!==void 0||r.state!==void 0)&&(r.messages&&(this.messages=r.messages,t.messages=r.messages,e.forEach(n=>{n.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),r.state&&(this.state=r.state,t.state=r.state,e.forEach(n=>{n.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}onError(t,e,r){return Ft(L(r,this.messages,this.state,(n,o,s)=>n.onRunFailed?.({error:e,messages:o,state:s,agent:this,input:t}))).pipe(nt(n=>{let o=n;if((o.messages!==void 0||o.state!==void 0)&&(o.messages!==void 0&&(this.messages=o.messages,r.forEach(s=>{s.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),o.state!==void 0&&(this.state=o.state,r.forEach(s=>{s.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))),o.stopPropagation!==!0){let s=String(e);if(!(e.name==="AbortError"||e.message==="Fetch is aborted"||e.message==="signal is aborted without reason"||e.message==="component unmounted"||s==="component unmounted"))throw console.error("Agent execution failed:",e),e}return{}}))}async onFinalize(t,e){let r=await L(e,this.messages,this.state,(n,o,s)=>n.onRunFinalized?.({messages:o,state:s,agent:this,input:t}));(r.messages!==void 0||r.state!==void 0)&&(r.messages!==void 0&&(this.messages=r.messages,e.forEach(n=>{n.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),r.state!==void 0&&(this.state=r.state,e.forEach(n=>{n.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}clone(){let t=Object.create(Object.getPrototypeOf(this));return t.agentId=this.agentId,t.description=this.description,t.threadId=this.threadId,t.messages=M(this.messages),t.state=M(this.state),t._debug=this._debug,t._debugLogger=this._debugLogger,t.isRunning=this.isRunning,t.subscribers=[...this.subscribers],t.middlewares=[...this.middlewares],t}addMessage(t){this.messages.push(t),(async()=>{for(let e of this.subscribers)await e.onNewMessage?.({message:t,messages:this.messages,state:this.state,agent:this});if(t.role==="assistant"&&t.toolCalls)for(let e of t.toolCalls)for(let r of this.subscribers)await r.onNewToolCall?.({toolCall:e,messages:this.messages,state:this.state,agent:this});for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}addMessages(t){this.messages.push(...t),(async()=>{for(let e of t){for(let r of this.subscribers)await r.onNewMessage?.({message:e,messages:this.messages,state:this.state,agent:this});if(e.role==="assistant"&&e.toolCalls)for(let r of e.toolCalls)for(let n of this.subscribers)await n.onNewToolCall?.({toolCall:r,messages:this.messages,state:this.state,agent:this})}for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setMessages(t){this.messages=M(t),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(t){this.state=M(t),(async()=>{for(let e of this.subscribers)await e.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(t){this.agentId=this.agentId??Ae();let e=this.prepareRunAgentInput(t);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((r,n)=>({run:o=>n.run(o,r),get messages(){return r.messages},get state(){return r.state}}),this).run(e)).pipe(kr(this.debugLogger),bn(this.debugLogger),su(this.threadId,e.runId,this.agentId),r=>r.pipe(nt(n=>(this.debugLogger?.event("LEGACY","Event:",n,{type:n.type}),n))))}};var Bo=1,Rr="0.1.0",An="X-CSRF-Token",Wo="X-Surogates-Widget-Version",Xo="/v1/website/sessions",zo=t=>`/v1/website/sessions/${t}/messages`,Ko=(t,e)=>`/v1/website/sessions/${t}/events?after=${e}`,Zo=t=>`/v1/website/sessions/${t}/end`,D={USER_MESSAGE:"user.message",LLM_REQUEST:"llm.request",LLM_RESPONSE:"llm.response",LLM_THINKING:"llm.thinking",LLM_DELTA:"llm.delta",TOOL_CALL:"tool.call",TOOL_RESULT:"tool.result",SANDBOX_PROVISION:"sandbox.provision",SANDBOX_EXECUTE:"sandbox.execute",SANDBOX_RESULT:"sandbox.result",SANDBOX_DESTROY:"sandbox.destroy",SESSION_START:"session.start",SESSION_PAUSE:"session.pause",SESSION_RESUME:"session.resume",SESSION_COMPLETE:"session.complete",SESSION_FAIL:"session.fail",SESSION_DONE:"session.done",CONTEXT_COMPACT:"context.compact",MEMORY_UPDATE:"memory.update",EXPERT_DELEGATION:"expert.delegation",EXPERT_RESULT:"expert.result",EXPERT_FAILURE:"expert.failure",POLICY_DENIED:"policy.denied",POLICY_ALLOWED:"policy.allowed",HARNESS_CRASH:"harness.crash"};var Re=class extends Error{constructor(e,r){super(e),this.name="SurogatesError",r?.status!==void 0&&(this.status=r.status),r?.detail!==void 0&&(this.detail=r.detail),r?.cause!==void 0&&(this.cause=r.cause)}},fe=class extends Re{constructor(e,r){super(e,r),this.name="SurogatesAuthError"}},Pe=class extends Re{constructor(e,r){super(e,r),this.name="SurogatesRateLimitError",r?.retryAfter!==void 0&&(this.retryAfter=r.retryAfter)}},Me=class extends Re{constructor(e,r){super(e,r),this.name="SurogatesProtocolError"}},st=class extends Re{constructor(e,r){super(e,r),this.name="SurogatesNetworkError"}};function Pr(t,e){if(!e)return t;let r=t.includes("?")?"&":"?";return`${t}${r}agent_id=${encodeURIComponent(e)}`}async function In(t,e){let r;try{r=await fetch(t,{...e,credentials:"include",headers:{...e.headers,[Wo]:Rr}})}catch(n){throw new st("Network request failed",{cause:n})}return r}async function fu(t){try{let e=await t.json();return typeof e.detail=="string"?e.detail:void 0}catch{return}}async function Yo(t,e){let r=await fu(t);if(t.status===401||t.status===403)throw new fe(`${e} rejected (${t.status})`,{status:t.status,...r!==void 0&&{detail:r}});if(t.status===429){let n=t.headers.get("Retry-After"),o=n?Number(n):void 0;throw new Pe(`${e} rate-limited`,{status:t.status,...o!==void 0&&Number.isFinite(o)&&{retryAfter:o},...r!==void 0&&{detail:r}})}throw t.status>=500?new st(`${e} failed (${t.status}${r?`: ${r}`:""})`):new Me(`${e} failed (${t.status})`,{status:t.status,...r!==void 0&&{detail:r}})}async function qo(t,e,r){let n=await In(t+Pr(Xo,r),{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});n.ok||await Yo(n,"Bootstrap");let o;try{o=await n.json()}catch(s){throw new Me("Bootstrap returned non-JSON body",{cause:s})}if(!o||typeof o.session_id!="string"||typeof o.csrf_token!="string")throw new Me("Bootstrap response missing required fields");return{sessionId:o.session_id,csrfToken:o.csrf_token,expiresAt:Number(o.expires_at)||0,agentName:o.agent_name??""}}async function Nn(t,e,r,n,o){let s=await In(t+Pr(zo(e),o),{method:"POST",headers:{"Content-Type":"application/json",[An]:r},body:JSON.stringify({content:n})});s.ok||await Yo(s,"Send message");let a=await s.json().catch(()=>({}));return{eventId:Number(a.event_id??0)}}async function Jo(t,e,r,n){try{await In(t+Pr(Zo(e),n),{method:"POST",headers:{[An]:r}})}catch{}}function Qo(t,e,r,n){let o=t+Pr(Ko(e,r),n);return new EventSource(o,{withCredentials:!0})}var pu=new Set(["stop","end_turn","length"]),mu=new Set(["tool_calls","function_call","tool_use"]),at=class{constructor(){this.pendingToolCalls=new Set;this._turnComplete=!1}get isTurnComplete(){return this._turnComplete}translate(e){switch(e.type){case D.LLM_DELTA:return this.handleLlmDelta(e);case D.LLM_RESPONSE:return this.handleLlmResponse(e);case D.LLM_THINKING:return this.handleLlmThinking(e);case D.TOOL_CALL:return this.handleToolCall(e);case D.TOOL_RESULT:return this.handleToolResult(e);case D.POLICY_DENIED:return this.handlePolicyDenied(e);case D.EXPERT_DELEGATION:return this.handleExpertDelegation(e);case D.EXPERT_RESULT:return this.handleExpertResult(e);case D.EXPERT_FAILURE:return this.asCustom(e);case D.SESSION_FAIL:case D.HARNESS_CRASH:return this.handleTerminalFailure(e);case D.SESSION_DONE:case D.SESSION_COMPLETE:return this._turnComplete=!0,[];case D.USER_MESSAGE:case D.LLM_REQUEST:case D.SESSION_START:case D.SESSION_PAUSE:case D.SESSION_RESUME:case D.SANDBOX_PROVISION:case D.SANDBOX_EXECUTE:case D.SANDBOX_RESULT:case D.SANDBOX_DESTROY:case D.POLICY_ALLOWED:return[];default:return this.asCustom(e)}}handleLlmDelta(e){let r=e.data??{},n=r.delta??r.content??"";if(!n)return[];let o=this.currentMessageId??r.message_id??this.mintMessageId(e.id);return this.currentMessageId=o,[{type:g.TEXT_MESSAGE_CHUNK,messageId:o,role:"assistant",delta:n}]}handleLlmResponse(e){let r=e.data??{},n=[];if(!this.currentMessageId&&r.content){let i=r.message_id??r.id??this.mintMessageId(e.id);n.push({type:g.TEXT_MESSAGE_CHUNK,messageId:i,role:"assistant",delta:r.content})}this.currentMessageId=void 0;let o=Array.isArray(r.tool_calls)?r.tool_calls:[],s=r.finish_reason??r.stop_reason??"";return mu.has(s)||o.length===0&&(s===""||pu.has(s))&&this.pendingToolCalls.size===0&&(this._turnComplete=!0),n}handleLlmThinking(e){let r=e.data??{},n=r.delta??r.content??"";if(!n)return[];let o=this.currentReasoningId??r.message_id??this.mintMessageId(e.id),s=this.currentReasoningId!==o;this.currentReasoningId=o;let a=[];return s&&(a.push({type:g.REASONING_START,messageId:o}),a.push({type:g.REASONING_MESSAGE_START,messageId:o,role:"reasoning"})),a.push({type:g.REASONING_MESSAGE_CONTENT,messageId:o,delta:n}),a}handleToolCall(e){let r=e.data??{},n=r.tool_call_id??`tc-${e.id}`,o=r.name??"unknown_tool";this.currentMessageId=void 0,this.currentReasoningId=void 0,this.pendingToolCalls.add(n);let s=typeof r.arguments=="string"?r.arguments:JSON.stringify(r.arguments??{});return[{type:g.TOOL_CALL_CHUNK,toolCallId:n,toolCallName:o,delta:s}]}handleToolResult(e){let r=e.data??{},n=r.tool_call_id??`tc-${e.id}`,o=r.content??"";return this.pendingToolCalls.delete(n),[{type:g.TOOL_CALL_RESULT,messageId:`tr-${e.id}`,toolCallId:n,content:o,role:"tool"}]}handlePolicyDenied(e){let r=e.data??{};return[{type:g.CUSTOM,name:D.POLICY_DENIED,value:{tool:r.tool,reason:r.reason}}]}handleExpertDelegation(e){let n=(e.data??{}).expert_name??"expert";return[{type:g.STEP_STARTED,stepName:`expert:${n}`}]}handleExpertResult(e){let n=(e.data??{}).expert_name??"expert";return[{type:g.STEP_FINISHED,stepName:`expert:${n}`}]}handleTerminalFailure(e){this._turnComplete=!0;let r=e.data??{},n=r.error??r.message??`${e.type} fired`;return[{type:g.RUN_ERROR,message:n,code:e.type}]}asCustom(e){return[{type:g.CUSTOM,name:e.type,value:e.data}]}mintMessageId(e){return`msg-${e}`}};var hu=Object.values(D),gu=250,wt=class extends Or{constructor(r){super(r);this.cursor=0;if(!r.apiUrl)throw new F('WebsiteAgent: "apiUrl" is required.');if(!r.publishableKey)throw new F('WebsiteAgent: "publishableKey" is required.');this.apiUrl=r.apiUrl.replace(/\/+$/,""),this.publishableKey=r.publishableKey}async ensureBootstrapped(){return this.bootstrapResult?this.bootstrapResult:(this.bootstrapResult=await qo(this.apiUrl,this.publishableKey,this.agentId),this.bootstrapResult)}async end(){let r=this.bootstrapResult;r&&(this.bootstrapResult=void 0,this.cursor=0,await Jo(this.apiUrl,r.sessionId,r.csrfToken,this.agentId))}run(r){return new H(n=>{let o={terminated:!1,source:void 0,drainTimer:void 0};return this.driveRun(r,n,o).catch(s=>{o.terminated||(o.terminated=!0,n.error(s))}),()=>{o.terminated=!0,o.drainTimer===void 0&&(Mr(o.source),o.source=void 0)}})}async driveRun(r,n,o){if(!o.terminated){n.next({type:g.RUN_STARTED,threadId:r.threadId,runId:r.runId});try{let s=this.extractUserText(r.messages),a=await this.ensureBootstrapped();this.replaceStreamSource(o,a.sessionId,this.cursor,new at,n,r),await this.sendWithCookieRecovery(a,s,i=>{this.replaceStreamSource(o,i.sessionId,0,new at,n,r)})}catch(s){if(o.terminated)return;o.terminated=!0;let a=s instanceof Error?s.message:String(s),i=s instanceof fe?"auth":"error";n.next({type:g.RUN_ERROR,message:a,code:i}),Mr(o.source),o.source=void 0,n.complete()}}}replaceStreamSource(r,n,o,s,a,i){Mr(r.source);let c=Qo(this.apiUrl,n,o,this.agentId);r.source=c,this.attachStreamListeners(c,s,a,i,r)}async sendWithCookieRecovery(r,n,o){try{await Nn(this.apiUrl,r.sessionId,r.csrfToken,n,this.agentId);return}catch(s){if(!(s instanceof fe))throw s;this.bootstrapResult=void 0,this.cursor=0;let a=await this.ensureBootstrapped();o(a),await Nn(this.apiUrl,a.sessionId,a.csrfToken,n,this.agentId)}}attachStreamListeners(r,n,o,s,a){let i=()=>{a.drainTimer!==void 0&&globalThis.clearTimeout(a.drainTimer),a.drainTimer=globalThis.setTimeout(()=>{a.drainTimer=void 0,Mr(r)},gu)},c=()=>{a.terminated||(a.terminated=!0,o.next({type:g.RUN_FINISHED,threadId:s.threadId,runId:s.runId}),i(),o.complete())},u=(p,f,v)=>{let d;try{d=JSON.parse(f)}catch{d=f}let m={id:Number(v)||0,type:p,data:d};if(m.id>this.cursor&&(this.cursor=m.id),a.terminated)return;let h=n.translate(m);for(let y of h)o.next(y);n.isTurnComplete&&c()};for(let p of hu)r.addEventListener(p,f=>{u(p,f.data,f.lastEventId)});r.onerror=()=>{r.readyState===2&&(a.terminated||(a.terminated=!0,o.next({type:g.RUN_ERROR,message:"SSE connection closed",code:"sse_closed"}),o.complete()))}}extractUserText(r){for(let n=r.length-1;n>=0;n--){let o=r[n];if(!o||o.role!=="user")continue;let s=o.content;if(typeof s=="string"&&s.trim().length>0)return s}throw new F("WebsiteAgent: no user message with string content found in input.messages.")}};function Mr(t){if(t){try{t.onerror=null}catch{}t.close()}}var $r,U,os,_u,Le,es,ss,as,Cn,Dr,$t,is,Pn,kn,On,vu,Fr={},Hr=[],yu=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,jr=Array.isArray;function Te(t,e){for(var r in e)t[r]=e[r];return t}function Mn(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Eu(t,e,r){var n,o,s,a={};for(s in e)s=="key"?n=e[s]:s=="ref"?o=e[s]:a[s]=e[s];if(arguments.length>2&&(a.children=arguments.length>3?$r.call(arguments,2):r),typeof t=="function"&&t.defaultProps!=null)for(s in t.defaultProps)a[s]===void 0&&(a[s]=t.defaultProps[s]);return Ur(t,a,n,o,null)}function Ur(t,e,r,n,o){var s={type:t,props:e,key:r,ref:n,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++os,__i:-1,__u:0};return o==null&&U.vnode!=null&&U.vnode(s),s}function It(t){return t.children}function Gr(t,e){this.props=t,this.context=e}function At(t,e){if(e==null)return t.__?At(t.__,t.__i+1):null;for(var r;e<t.__k.length;e++)if((r=t.__k[e])!=null&&r.__e!=null)return r.__e;return typeof t.type=="function"?At(t):null}function bu(t){if(t.__P&&t.__d){var e=t.__v,r=e.__e,n=[],o=[],s=Te({},e);s.__v=e.__v+1,U.vnode&&U.vnode(s),Ln(t.__P,s,e,t.__n,t.__P.namespaceURI,32&e.__u?[r]:null,n,r??At(e),!!(32&e.__u),o),s.__v=e.__v,s.__.__k[s.__i]=s,ds(n,s,o),e.__e=e.__=null,s.__e!=r&&ls(s)}}function ls(t){if((t=t.__)!=null&&t.__c!=null)return t.__e=t.__c.base=null,t.__k.some(function(e){if(e!=null&&e.__e!=null)return t.__e=t.__c.base=e.__e}),ls(t)}function ts(t){(!t.__d&&(t.__d=!0)&&Le.push(t)&&!Vr.__r++||es!=U.debounceRendering)&&((es=U.debounceRendering)||ss)(Vr)}function Vr(){try{for(var t,e=1;Le.length;)Le.length>e&&Le.sort(as),t=Le.shift(),e=Le.length,bu(t)}finally{Le.length=Vr.__r=0}}function us(t,e,r,n,o,s,a,i,c,u,p){var f,v,d,m,h,y,E,_=n&&n.__k||Hr,I=e.length;for(c=Su(r,e,_,c,I),f=0;f<I;f++)(d=r.__k[f])!=null&&(v=d.__i!=-1&&_[d.__i]||Fr,d.__i=f,y=Ln(t,d,v,o,s,a,i,c,u,p),m=d.__e,d.ref&&v.ref!=d.ref&&(v.ref&&Dn(v.ref,null,d),p.push(d.ref,d.__c||m,d)),h==null&&m!=null&&(h=m),(E=!!(4&d.__u))||v.__k===d.__k?(c=cs(d,c,t,E),E&&v.__e&&(v.__e=null)):typeof d.type=="function"&&y!==void 0?c=y:m&&(c=m.nextSibling),d.__u&=-7);return r.__e=h,c}function Su(t,e,r,n,o){var s,a,i,c,u,p=r.length,f=p,v=0;for(t.__k=new Array(o),s=0;s<o;s++)(a=e[s])!=null&&typeof a!="boolean"&&typeof a!="function"?(typeof a=="string"||typeof a=="number"||typeof a=="bigint"||a.constructor==String?a=t.__k[s]=Ur(null,a,null,null,null):jr(a)?a=t.__k[s]=Ur(It,{children:a},null,null,null):a.constructor===void 0&&a.__b>0?a=t.__k[s]=Ur(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):t.__k[s]=a,c=s+v,a.__=t,a.__b=t.__b+1,i=null,(u=a.__i=xu(a,r,c,f))!=-1&&(f--,(i=r[u])&&(i.__u|=2)),i==null||i.__v==null?(u==-1&&(o>p?v--:o<p&&v++),typeof a.type!="function"&&(a.__u|=4)):u!=c&&(u==c-1?v--:u==c+1?v++:(u>c?v--:v++,a.__u|=4))):t.__k[s]=null;if(f)for(s=0;s<p;s++)(i=r[s])!=null&&(2&i.__u)==0&&(i.__e==n&&(n=At(i)),ps(i,i));return n}function cs(t,e,r,n){var o,s;if(typeof t.type=="function"){for(o=t.__k,s=0;o&&s<o.length;s++)o[s]&&(o[s].__=t,e=cs(o[s],e,r,n));return e}t.__e!=e&&(n&&(e&&t.type&&!e.parentNode&&(e=At(t)),r.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function xu(t,e,r,n){var o,s,a,i=t.key,c=t.type,u=e[r],p=u!=null&&(2&u.__u)==0;if(u===null&&i==null||p&&i==u.key&&c==u.type)return r;if(n>(p?1:0)){for(o=r-1,s=r+1;o>=0||s<e.length;)if((u=e[a=o>=0?o--:s++])!=null&&(2&u.__u)==0&&i==u.key&&c==u.type)return a}return-1}function rs(t,e,r){e[0]=="-"?t.setProperty(e,r??""):t[e]=r==null?"":typeof r!="number"||yu.test(e)?r:r+"px"}function Lr(t,e,r,n,o){var s,a;e:if(e=="style")if(typeof r=="string")t.style.cssText=r;else{if(typeof n=="string"&&(t.style.cssText=n=""),n)for(e in n)r&&e in r||rs(t.style,e,"");if(r)for(e in r)n&&r[e]==n[e]||rs(t.style,e,r[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(is,"$1")),a=e.toLowerCase(),e=a in t||e=="onFocusOut"||e=="onFocusIn"?a.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+s]=r,r?n?r[$t]=n[$t]:(r[$t]=Pn,t.addEventListener(e,s?On:kn,s)):t.removeEventListener(e,s?On:kn,s);else{if(o=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=r??"";break e}catch{}typeof r=="function"||(r==null||r===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&r==1?"":r))}}function ns(t){return function(e){if(this.l){var r=this.l[e.type+t];if(e[Dr]==null)e[Dr]=Pn++;else if(e[Dr]<r[$t])return;return r(U.event?U.event(e):e)}}}function Ln(t,e,r,n,o,s,a,i,c,u){var p,f,v,d,m,h,y,E,_,I,$,Z,De,pe,Ct,se=e.type;if(e.constructor!==void 0)return null;128&r.__u&&(c=!!(32&r.__u),s=[i=e.__e=r.__e]),(p=U.__b)&&p(e);e:if(typeof se=="function")try{if(E=e.props,_=se.prototype&&se.prototype.render,I=(p=se.contextType)&&n[p.__c],$=p?I?I.props.value:p.__:n,r.__c?y=(f=e.__c=r.__c).__=f.__E:(_?e.__c=f=new se(E,$):(e.__c=f=new Gr(E,$),f.constructor=se,f.render=wu),I&&I.sub(f),f.state||(f.state={}),f.__n=n,v=f.__d=!0,f.__h=[],f._sb=[]),_&&f.__s==null&&(f.__s=f.state),_&&se.getDerivedStateFromProps!=null&&(f.__s==f.state&&(f.__s=Te({},f.__s)),Te(f.__s,se.getDerivedStateFromProps(E,f.__s))),d=f.props,m=f.state,f.__v=e,v)_&&se.getDerivedStateFromProps==null&&f.componentWillMount!=null&&f.componentWillMount(),_&&f.componentDidMount!=null&&f.__h.push(f.componentDidMount);else{if(_&&se.getDerivedStateFromProps==null&&E!==d&&f.componentWillReceiveProps!=null&&f.componentWillReceiveProps(E,$),e.__v==r.__v||!f.__e&&f.shouldComponentUpdate!=null&&f.shouldComponentUpdate(E,f.__s,$)===!1){e.__v!=r.__v&&(f.props=E,f.state=f.__s,f.__d=!1),e.__e=r.__e,e.__k=r.__k,e.__k.some(function(we){we&&(we.__=e)}),Hr.push.apply(f.__h,f._sb),f._sb=[],f.__h.length&&a.push(f);break e}f.componentWillUpdate!=null&&f.componentWillUpdate(E,f.__s,$),_&&f.componentDidUpdate!=null&&f.__h.push(function(){f.componentDidUpdate(d,m,h)})}if(f.context=$,f.props=E,f.__P=t,f.__e=!1,Z=U.__r,De=0,_)f.state=f.__s,f.__d=!1,Z&&Z(e),p=f.render(f.props,f.state,f.context),Hr.push.apply(f.__h,f._sb),f._sb=[];else do f.__d=!1,Z&&Z(e),p=f.render(f.props,f.state,f.context),f.state=f.__s;while(f.__d&&++De<25);f.state=f.__s,f.getChildContext!=null&&(n=Te(Te({},n),f.getChildContext())),_&&!v&&f.getSnapshotBeforeUpdate!=null&&(h=f.getSnapshotBeforeUpdate(d,m)),pe=p!=null&&p.type===It&&p.key==null?fs(p.props.children):p,i=us(t,jr(pe)?pe:[pe],e,r,n,o,s,a,i,c,u),f.base=e.__e,e.__u&=-161,f.__h.length&&a.push(f),y&&(f.__E=f.__=null)}catch(we){if(e.__v=null,c||s!=null)if(we.then){for(e.__u|=c?160:128;i&&i.nodeType==8&&i.nextSibling;)i=i.nextSibling;s[s.indexOf(i)]=null,e.__e=i}else{for(Ct=s.length;Ct--;)Mn(s[Ct]);Rn(e)}else e.__e=r.__e,e.__k=r.__k,we.then||Rn(e);U.__e(we,e,r)}else s==null&&e.__v==r.__v?(e.__k=r.__k,e.__e=r.__e):i=e.__e=Tu(r.__e,e,r,n,o,s,a,c,u);return(p=U.diffed)&&p(e),128&e.__u?void 0:i}function Rn(t){t&&(t.__c&&(t.__c.__e=!0),t.__k&&t.__k.some(Rn))}function ds(t,e,r){for(var n=0;n<r.length;n++)Dn(r[n],r[++n],r[++n]);U.__c&&U.__c(e,t),t.some(function(o){try{t=o.__h,o.__h=[],t.some(function(s){s.call(o)})}catch(s){U.__e(s,o.__v)}})}function fs(t){return typeof t!="object"||t==null||t.__b>0?t:jr(t)?t.map(fs):t.constructor!==void 0?null:Te({},t)}function Tu(t,e,r,n,o,s,a,i,c){var u,p,f,v,d,m,h,y=r.props||Fr,E=e.props,_=e.type;if(_=="svg"?o="http://www.w3.org/2000/svg":_=="math"?o="http://www.w3.org/1998/Math/MathML":o||(o="http://www.w3.org/1999/xhtml"),s!=null){for(u=0;u<s.length;u++)if((d=s[u])&&"setAttribute"in d==!!_&&(_?d.localName==_:d.nodeType==3)){t=d,s[u]=null;break}}if(t==null){if(_==null)return document.createTextNode(E);t=document.createElementNS(o,_,E.is&&E),i&&(U.__m&&U.__m(e,s),i=!1),s=null}if(_==null)y===E||i&&t.data==E||(t.data=E);else{if(s=_=="textarea"&&E.defaultValue!=null?null:s&&$r.call(t.childNodes),!i&&s!=null)for(y={},u=0;u<t.attributes.length;u++)y[(d=t.attributes[u]).name]=d.value;for(u in y)d=y[u],u=="dangerouslySetInnerHTML"?f=d:u=="children"||u in E||u=="value"&&"defaultValue"in E||u=="checked"&&"defaultChecked"in E||Lr(t,u,null,d,o);for(u in E)d=E[u],u=="children"?v=d:u=="dangerouslySetInnerHTML"?p=d:u=="value"?m=d:u=="checked"?h=d:i&&typeof d!="function"||y[u]===d||Lr(t,u,d,y[u],o);if(p)i||f&&(p.__html==f.__html||p.__html==t.innerHTML)||(t.innerHTML=p.__html),e.__k=[];else if(f&&(t.innerHTML=""),us(e.type=="template"?t.content:t,jr(v)?v:[v],e,r,n,_=="foreignObject"?"http://www.w3.org/1999/xhtml":o,s,a,s?s[0]:r.__k&&At(r,0),i,c),s!=null)for(u=s.length;u--;)Mn(s[u]);i&&_!="textarea"||(u="value",_=="progress"&&m==null?t.removeAttribute("value"):m!=null&&(m!==t[u]||_=="progress"&&!m||_=="option"&&m!=y[u])&&Lr(t,u,m,y[u],o),u="checked",h!=null&&h!=t[u]&&Lr(t,u,h,y[u],o))}return t}function Dn(t,e,r){try{if(typeof t=="function"){var n=typeof t.__u=="function";n&&t.__u(),n&&e==null||(t.__u=t(e))}else t.current=e}catch(o){U.__e(o,r)}}function ps(t,e,r){var n,o;if(U.unmount&&U.unmount(t),(n=t.ref)&&(n.current&&n.current!=t.__e||Dn(n,null,e)),(n=t.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(s){U.__e(s,e)}n.base=n.__P=null}if(n=t.__k)for(o=0;o<n.length;o++)n[o]&&ps(n[o],e,r||typeof t.type!="function");r||Mn(t.__e),t.__c=t.__=t.__e=void 0}function wu(t,e,r){return this.constructor(t,r)}function Un(t,e,r){var n,o,s,a;e==document&&(e=document.documentElement),U.__&&U.__(t,e),o=(n=typeof r=="function")?null:r&&r.__k||e.__k,s=[],a=[],Ln(e,t=(!n&&r||e).__k=Eu(It,null,[t]),o||Fr,Fr,e.namespaceURI,!n&&r?[r]:o?null:e.firstChild?$r.call(e.childNodes):null,s,!n&&r?r:o?o.__e:e.firstChild,n,a),ds(s,t,a)}$r=Hr.slice,U={__e:function(t,e,r,n){for(var o,s,a;e=e.__;)if((o=e.__c)&&!o.__)try{if((s=o.constructor)&&s.getDerivedStateFromError!=null&&(o.setState(s.getDerivedStateFromError(t)),a=o.__d),o.componentDidCatch!=null&&(o.componentDidCatch(t,n||{}),a=o.__d),a)return o.__E=o}catch(i){t=i}throw t}},os=0,_u=function(t){return t!=null&&t.constructor===void 0},Gr.prototype.setState=function(t,e){var r;r=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Te({},this.state),typeof t=="function"&&(t=t(Te({},r),this.props)),t&&Te(r,t),t!=null&&this.__v&&(e&&this._sb.push(e),ts(this))},Gr.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),ts(this))},Gr.prototype.render=It,Le=[],ss=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,as=function(t,e){return t.__v.__b-e.__v.__b},Vr.__r=0,Cn=Math.random().toString(8),Dr="__d"+Cn,$t="__a"+Cn,is=/(PointerCapture)$|Capture$/i,Pn=0,kn=ns(!1),On=ns(!0),vu=0;var ms=`
8
+ Error: ${y}`)}}return p()}case g.MESSAGES_SNAPSHOT:{let d=await L(n,a,i,(m,h,y)=>m.onMessagesSnapshotEvent?.({event:f,messages:h,state:y,agent:r,input:t}));if(u(d),d.stopPropagation!==!0){let{messages:m}=f,h=new Map(m.map(_=>[_.id,_])),y=_=>_==="activity"||_==="reasoning";a=a.filter(_=>y(_.role)||h.has(_.id)).map(_=>y(_.role)?_:h.get(_.id));let E=new Set(a.map(_=>_.id));for(let _ of m)E.has(_.id)||a.push(_);u({messages:a})}return p()}case g.ACTIVITY_SNAPSHOT:{let d=f,m=a.findIndex(I=>I.id===d.messageId),h=m>=0?a[m]:void 0,y=h?.role==="activity"?h:void 0,E=d.replace??!0,_=await L(n,a,i,(I,$,Z)=>I.onActivitySnapshotEvent?.({event:d,messages:$,state:Z,agent:r,input:t,activityMessage:y,existingMessage:h}));if(u(_),_.stopPropagation!==!0){let I={id:d.messageId,role:"activity",activityType:d.activityType,content:M(d.content)},$;m===-1?(a.push(I),$=I):y?E&&(a[m]={...y,activityType:d.activityType,content:M(d.content)}):E&&(a[m]=I,$=I),u({messages:a}),$&&await Promise.all(n.map(Z=>Z.onNewMessage?.({message:$,messages:a,state:i,agent:r,input:t})))}return p()}case g.ACTIVITY_DELTA:{let d=f,m=a.findIndex(_=>_.id===d.messageId);if(m===-1)return p();let h=a[m];if(h.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${d.messageId}' is not an activity message`),p();let y=h,E=await L(n,a,i,(_,I,$)=>_.onActivityDeltaEvent?.({event:d,messages:I,state:$,agent:r,input:t,activityMessage:y}));if(u(E),E.stopPropagation!==!0)try{let _=M(y.content??{}),I=Oe(_,d.patch??[],!0,!1).newDocument;a[m]={...y,content:M(I),activityType:d.activityType},u({messages:a})}catch(_){let I=_ instanceof Error?_.message:String(_);console.warn(`Failed to apply activity patch for '${d.messageId}': ${I}`)}return p()}case g.RAW:return u(await L(n,a,i,(d,m,h)=>d.onRawEvent?.({event:f,messages:m,state:h,agent:r,input:t}))),p();case g.CUSTOM:return u(await L(n,a,i,(d,m,h)=>d.onCustomEvent?.({event:f,messages:m,state:h,agent:r,input:t}))),p();case g.RUN_STARTED:{let d=await L(n,a,i,(m,h,y)=>m.onRunStartedEvent?.({event:f,messages:h,state:y,agent:r,input:t}));if(u(d),d.stopPropagation!==!0){let m=f;if(m.input?.messages){for(let h of m.input.messages)a.find(y=>y.id===h.id)||a.push(h);u({messages:a})}}return p()}case g.RUN_FINISHED:return u(await L(n,a,i,(d,m,h)=>d.onRunFinishedEvent?.({event:f,messages:m,state:h,agent:r,input:t,result:f.result}))),p();case g.RUN_ERROR:return u(await L(n,a,i,(d,m,h)=>d.onRunErrorEvent?.({event:f,messages:m,state:h,agent:r,input:t}))),p();case g.STEP_STARTED:return u(await L(n,a,i,(d,m,h)=>d.onStepStartedEvent?.({event:f,messages:m,state:h,agent:r,input:t}))),p();case g.STEP_FINISHED:return u(await L(n,a,i,(d,m,h)=>d.onStepFinishedEvent?.({event:f,messages:m,state:h,agent:r,input:t}))),p();case g.TEXT_MESSAGE_CHUNK:throw Error("TEXT_MESSAGE_CHUNK must be tranformed before being applied");case g.TOOL_CALL_CHUNK:throw Error("TOOL_CALL_CHUNK must be tranformed before being applied");case g.THINKING_START:return p();case g.THINKING_END:return p();case g.THINKING_TEXT_MESSAGE_START:return p();case g.THINKING_TEXT_MESSAGE_CONTENT:return p();case g.THINKING_TEXT_MESSAGE_END:return p();case g.REASONING_START:return u(await L(n,a,i,(d,m,h)=>d.onReasoningStartEvent?.({event:f,messages:m,state:h,agent:r,input:t}))),p();case g.REASONING_MESSAGE_START:{let d=await L(n,a,i,(m,h,y)=>m.onReasoningMessageStartEvent?.({event:f,messages:h,state:y,agent:r,input:t}));if(u(d),d.stopPropagation!==!0){let{messageId:m}=f;if(!a.find(h=>h.id===m)){let h={id:m,role:"reasoning",content:""};a.push(h),u({messages:a})}}return p()}case g.REASONING_MESSAGE_CONTENT:{let{messageId:d,delta:m}=f,h=a.find(E=>E.id===d);if(!h)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${d}'`),p();let y=await L(n,a,i,(E,_,I)=>E.onReasoningMessageContentEvent?.({event:f,messages:_,state:I,agent:r,input:t,reasoningMessageBuffer:typeof h.content=="string"?h.content:""}));return u(y),y.stopPropagation!==!0&&(h.content=`${typeof h.content=="string"?h.content:""}${m}`,u({messages:a})),p()}case g.REASONING_MESSAGE_END:{let{messageId:d}=f,m=a.find(h=>h.id===d);return m?(u(await L(n,a,i,(h,y,E)=>h.onReasoningMessageEndEvent?.({event:f,messages:y,state:E,agent:r,input:t,reasoningMessageBuffer:typeof m.content=="string"?m.content:""}))),await Promise.all(n.map(h=>{h.onNewMessage?.({message:m,messages:a,state:i,agent:r,input:t})})),p()):(console.warn(`REASONING_MESSAGE_END: No message found with ID '${d}'`),p())}case g.REASONING_MESSAGE_CHUNK:throw Error("REASONING_MESSAGE_CHUNK must be transformed before being applied");case g.REASONING_END:return u(await L(n,a,i,(d,m,h)=>d.onReasoningEndEvent?.({event:f,messages:m,state:h,agent:r,input:t}))),p();case g.REASONING_ENCRYPTED_VALUE:{let{subtype:d,entityId:m,encryptedValue:h}=f,y=await L(n,a,i,(E,_,I)=>E.onReasoningEncryptedValueEvent?.({event:f,messages:_,state:I,agent:r,input:t}));if(u(y),y.stopPropagation!==!0){let E=!1;if(d==="tool-call"){for(let _ of a)if(_.role==="assistant"&&_.toolCalls){let I=_.toolCalls.find($=>$.id===m);if(I){I.encryptedValue=h,E=!0;break}}}else{let _=a.find(I=>I.id===m);_?.role!=="activity"&&_&&(_.encryptedValue=h,E=!0)}E&&(c.messages=a)}return p()}}return f.type,p()}),hn(),n.length>0?_n({}):f=>f)},Sn=t=>e=>{let r=wn(t),n=new Map,o=new Map,s=!1,a=!1,i=!1,c=new Map,u=!1,p=!1,f=!1,v=()=>{n.clear(),o.clear(),c.clear(),u=!1,p=!1,s=!1,a=!1,f=!0};return e.pipe(oe(d=>{let m=d.type;if(r?.event("VERIFY","Event:",d,{type:d.type}),a)return B(()=>new F(`Cannot send event type '${m}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(s&&m!==g.RUN_ERROR&&m!==g.RUN_STARTED)return B(()=>new F(`Cannot send event type '${m}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(i){if(m===g.RUN_STARTED){if(f&&!s)return B(()=>new F("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&&v()}}else if(i=!0,m!==g.RUN_STARTED&&m!==g.RUN_ERROR)return B(()=>new F("First event must be 'RUN_STARTED'"));switch(m){case g.TEXT_MESSAGE_START:{let h=d.messageId;return n.has(h)?B(()=>new F(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${h}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(n.set(h,!0),j(d))}case g.TEXT_MESSAGE_CONTENT:{let h=d.messageId;return n.has(h)?j(d):B(()=>new F(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${h}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case g.TEXT_MESSAGE_END:{let h=d.messageId;return n.has(h)?(n.delete(h),j(d)):B(()=>new F(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${h}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case g.TOOL_CALL_START:{let h=d.toolCallId;return o.has(h)?B(()=>new F(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${h}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(o.set(h,!0),j(d))}case g.TOOL_CALL_ARGS:{let h=d.toolCallId;return o.has(h)?j(d):B(()=>new F(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${h}'. Start a tool call with 'TOOL_CALL_START' first.`))}case g.TOOL_CALL_END:{let h=d.toolCallId;return o.has(h)?(o.delete(h),j(d)):B(()=>new F(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${h}'. A 'TOOL_CALL_START' event must be sent first.`))}case g.STEP_STARTED:{let h=d.stepName;return c.has(h)?B(()=>new F(`Step "${h}" is already active for 'STEP_STARTED'`)):(c.set(h,!0),j(d))}case g.STEP_FINISHED:{let h=d.stepName;return c.has(h)?(c.delete(h),j(d)):B(()=>new F(`Cannot send 'STEP_FINISHED' for step "${h}" that was not started`))}case g.RUN_STARTED:return f=!0,j(d);case g.RUN_FINISHED:if(c.size>0){let h=Array.from(c.keys()).join(", ");return B(()=>new F(`Cannot send 'RUN_FINISHED' while steps are still active: ${h}`))}if(n.size>0){let h=Array.from(n.keys()).join(", ");return B(()=>new F(`Cannot send 'RUN_FINISHED' while text messages are still active: ${h}`))}if(o.size>0){let h=Array.from(o.keys()).join(", ");return B(()=>new F(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${h}`))}return s=!0,j(d);case g.RUN_ERROR:return a=!0,j(d);case g.CUSTOM:return j(d);case g.THINKING_TEXT_MESSAGE_START:return u?p?B(()=>new F("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(p=!0,j(d)):B(()=>new F("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case g.THINKING_TEXT_MESSAGE_CONTENT:return p?j(d):B(()=>new F("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case g.THINKING_TEXT_MESSAGE_END:return p?(p=!1,j(d)):B(()=>new F("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case g.THINKING_START:return u?B(()=>new F("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(u=!0,j(d));case g.THINKING_END:return u?(u=!1,j(d)):B(()=>new F("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return j(d)}}))},ch=(function(t){return t.HEADERS="headers",t.DATA="data",t})({});var V=l.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),ql=l.enum(["LangGraphInterruptEvent","PredictState","Exit"]),Jl=l.object({type:l.literal(V.enum.TextMessageStart),messageId:l.string(),parentMessageId:l.string().optional(),role:l.string().optional()}),Ql=l.object({type:l.literal(V.enum.TextMessageContent),messageId:l.string(),content:l.string()}),eu=l.object({type:l.literal(V.enum.TextMessageEnd),messageId:l.string()}),tu=l.object({type:l.literal(V.enum.ActionExecutionStart),actionExecutionId:l.string(),actionName:l.string(),parentMessageId:l.string().optional()}),ru=l.object({type:l.literal(V.enum.ActionExecutionArgs),actionExecutionId:l.string(),args:l.string()}),nu=l.object({type:l.literal(V.enum.ActionExecutionEnd),actionExecutionId:l.string()}),ou=l.object({type:l.literal(V.enum.ActionExecutionResult),actionName:l.string(),actionExecutionId:l.string(),result:l.string()}),su=l.object({type:l.literal(V.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()}),au=l.object({type:l.literal(V.enum.MetaEvent),name:ql,value:l.any()}),iu=l.object({type:l.literal(V.enum.RunError),message:l.string(),code:l.string().optional()});l.discriminatedUnion("type",[Jl,Ql,eu,tu,ru,nu,ou,su,au,iu]),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 lu=t=>{if(typeof t=="string")return t;if(!Array.isArray(t))return;let e=t.filter(r=>r.type==="text").map(r=>r.text).filter(r=>r.length>0);if(e.length!==0)return e.join(`
9
+ `)},uu=(t,e,r)=>n=>{let o={},s=!0,a=!0,i="",c=null,u=null,p=[],f={},v=d=>{typeof d=="object"&&d&&("messages"in d&&delete d.messages,o=d)};return n.pipe(oe(d=>{switch(d.type){case g.TEXT_MESSAGE_START:{let m=d;return[{type:V.enum.TextMessageStart,messageId:m.messageId,role:m.role}]}case g.TEXT_MESSAGE_CONTENT:{let m=d;return[{type:V.enum.TextMessageContent,messageId:m.messageId,content:m.delta}]}case g.TEXT_MESSAGE_END:{let m=d;return[{type:V.enum.TextMessageEnd,messageId:m.messageId}]}case g.TOOL_CALL_START:{let m=d;return p.push({id:m.toolCallId,type:"function",function:{name:m.toolCallName,arguments:""}}),a=!0,f[m.toolCallId]=m.toolCallName,[{type:V.enum.ActionExecutionStart,actionExecutionId:m.toolCallId,actionName:m.toolCallName,parentMessageId:m.parentMessageId}]}case g.TOOL_CALL_ARGS:{let m=d,h=p.find(E=>E.id===m.toolCallId);if(!h)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${m.toolCallId}'`),[];h.function.arguments+=m.delta;let y=!1;if(u){let E=u.find(_=>_.tool==h.function.name);if(E)try{let _=JSON.parse(Ir(h.function.arguments));E.tool_argument&&E.tool_argument in _?(v({...o,[E.state_key]:_[E.tool_argument]}),y=!0):E.tool_argument||(v({...o,[E.state_key]:_}),y=!0)}catch{}}return[{type:V.enum.ActionExecutionArgs,actionExecutionId:m.toolCallId,args:m.delta},...y?[{type:V.enum.AgentStateMessage,threadId:t,agentName:r,nodeName:i,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:a}]:[]]}case g.TOOL_CALL_END:{let m=d;return[{type:V.enum.ActionExecutionEnd,actionExecutionId:m.toolCallId}]}case g.TOOL_CALL_RESULT:{let m=d;return[{type:V.enum.ActionExecutionResult,actionExecutionId:m.toolCallId,result:m.content,actionName:f[m.toolCallId]||"unknown"}]}case g.RAW:return[];case g.CUSTOM:{let m=d;switch(m.name){case"Exit":s=!1;break;case"PredictState":u=m.value;break}return[{type:V.enum.MetaEvent,name:m.name,value:m.value}]}case g.STATE_SNAPSHOT:return v(d.snapshot),[{type:V.enum.AgentStateMessage,threadId:t,agentName:r,nodeName:i,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:a}];case g.STATE_DELTA:{let m=d,h=Oe(o,m.delta,!0,!1);return h?(v(h.newDocument),[{type:V.enum.AgentStateMessage,threadId:t,agentName:r,nodeName:i,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:a}]):[]}case g.MESSAGES_SNAPSHOT:return c=d.messages,[{type:V.enum.AgentStateMessage,threadId:t,agentName:r,nodeName:i,runId:e,running:s,role:"assistant",state:JSON.stringify({...o,...c?{messages:c}:{}}),active:!0}];case g.RUN_STARTED:return[];case g.RUN_FINISHED:return c&&(o.messages=c),Object.keys(o).length===0?[]:[{type:V.enum.AgentStateMessage,threadId:t,agentName:r,nodeName:i,runId:e,running:s,role:"assistant",state:JSON.stringify({...o,...c?{messages:cu(c)}:{}}),active:!1}];case g.RUN_ERROR:{let m=d;return[{type:V.enum.RunError,message:m.message,code:m.code}]}case g.STEP_STARTED:return i=d.stepName,p=[],u=null,[{type:V.enum.AgentStateMessage,threadId:t,agentName:r,nodeName:i,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:!0}];case g.STEP_FINISHED:return p=[],u=null,[{type:V.enum.AgentStateMessage,threadId:t,agentName:r,nodeName:i,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:!1}];default:return[]}}))};function cu(t){let e=[];for(let r of t)if(r.role==="assistant"||r.role==="user"||r.role==="system"){let n=lu(r.content);if(n){let o={id:r.id,role:r.role,content:n};e.push(o)}if(r.role==="assistant"&&r.toolCalls&&r.toolCalls.length>0)for(let o of r.toolCalls){let s={id:o.id,name:o.function.name,arguments:JSON.parse(o.function.arguments),parentMessageId:r.id};e.push(s)}}else if(r.role==="tool"){let n="unknown";for(let s of t)if(s.role==="assistant"&&s.toolCalls?.length){for(let a of s.toolCalls)if(a.id===r.toolCallId){n=a.function.name;break}}let o={id:r.id,result:r.content,actionExecutionId:r.toolCallId,actionName:n};e.push(o)}return e}var kr=t=>e=>{let r=wn(t),n,o,s,a,i=()=>{if(!n||a!=="text")throw Error("No text message to close");let f={type:g.TEXT_MESSAGE_END,messageId:n.messageId};return a=void 0,n=void 0,r?.event("TRANSFORM","TEXT_MESSAGE_END",f,{messageId:f.messageId}),f},c=()=>{if(!o||a!=="tool")throw Error("No tool call to close");let f={type:g.TOOL_CALL_END,toolCallId:o.toolCallId};return a=void 0,o=void 0,r?.event("TRANSFORM","TOOL_CALL_END",f,{toolCallId:f.toolCallId}),f},u=()=>{if(!s||a!=="reasoning")throw Error("No reasoning message to close");let f={type:g.REASONING_MESSAGE_END,messageId:s.messageId};return a=void 0,s=void 0,r?.event("TRANSFORM","REASONING_MESSAGE_END",f,{messageId:f.messageId}),f},p=()=>a==="text"?[i()]:a==="tool"?[c()]:a==="reasoning"?[u()]:[];return e.pipe(oe(f=>{switch(f.type){case g.TEXT_MESSAGE_START:case g.TEXT_MESSAGE_CONTENT:case g.TEXT_MESSAGE_END:case g.TOOL_CALL_START:case g.TOOL_CALL_ARGS:case g.TOOL_CALL_END:case g.TOOL_CALL_RESULT:case g.STATE_SNAPSHOT:case g.STATE_DELTA:case g.MESSAGES_SNAPSHOT:case g.CUSTOM:case g.RUN_STARTED:case g.RUN_FINISHED:case g.RUN_ERROR:case g.STEP_STARTED:case g.STEP_FINISHED:case g.THINKING_START:case g.THINKING_END:case g.THINKING_TEXT_MESSAGE_START:case g.THINKING_TEXT_MESSAGE_CONTENT:case g.THINKING_TEXT_MESSAGE_END:case g.REASONING_START:case g.REASONING_MESSAGE_START:case g.REASONING_MESSAGE_CONTENT:case g.REASONING_MESSAGE_END:case g.REASONING_END:return[...p(),f];case g.RAW:case g.ACTIVITY_SNAPSHOT:case g.ACTIVITY_DELTA:case g.REASONING_ENCRYPTED_VALUE:return[f];case g.TEXT_MESSAGE_CHUNK:let v=f,d=[];if((a!=="text"||v.messageId!==void 0&&v.messageId!==n?.messageId)&&d.push(...p()),a!=="text"){if(v.messageId===void 0)throw Error("First TEXT_MESSAGE_CHUNK must have a messageId");n={messageId:v.messageId,name:v.name},a="text";let _={type:g.TEXT_MESSAGE_START,messageId:v.messageId,role:v.role||"assistant",...v.name!==void 0&&{name:v.name}};d.push(_),r?.event("TRANSFORM","TEXT_MESSAGE_START",_,{messageId:v.messageId})}if(v.delta!==void 0){let _={type:g.TEXT_MESSAGE_CONTENT,messageId:n.messageId,delta:v.delta};d.push(_),r?.event("TRANSFORM","TEXT_MESSAGE_CONTENT",_,{messageId:n.messageId})}return d;case g.TOOL_CALL_CHUNK:let m=f,h=[];if((a!=="tool"||m.toolCallId!==void 0&&m.toolCallId!==o?.toolCallId)&&h.push(...p()),a!=="tool"){if(m.toolCallId===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallId");if(m.toolCallName===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallName");o={toolCallId:m.toolCallId,toolCallName:m.toolCallName,parentMessageId:m.parentMessageId},a="tool";let _={type:g.TOOL_CALL_START,toolCallId:m.toolCallId,toolCallName:m.toolCallName,parentMessageId:m.parentMessageId};h.push(_),r?.event("TRANSFORM","TOOL_CALL_START",_,{toolCallId:m.toolCallId,toolCallName:m.toolCallName})}if(m.delta!==void 0){let _={type:g.TOOL_CALL_ARGS,toolCallId:o.toolCallId,delta:m.delta};h.push(_),r?.event("TRANSFORM","TOOL_CALL_ARGS",_,{toolCallId:o.toolCallId})}return h;case g.REASONING_MESSAGE_CHUNK:let y=f,E=[];if((a!=="reasoning"||y.messageId&&y.messageId!==s?.messageId)&&E.push(...p()),a!=="reasoning"){if(y.messageId===void 0)throw Error("First REASONING_MESSAGE_CHUNK must have a messageId");s={messageId:y.messageId},a="reasoning";let _={type:g.REASONING_MESSAGE_START,messageId:y.messageId};E.push(_),r?.event("TRANSFORM","REASONING_MESSAGE_START",_,{messageId:y.messageId})}if(y.delta!==void 0){let _={type:g.REASONING_MESSAGE_CONTENT,messageId:s.messageId,delta:y.delta};E.push(_),r?.event("TRANSFORM","REASONING_MESSAGE_CONTENT",_,{messageId:s.messageId})}return E}return f.type,[]}),st(()=>{p()}))},An=class{runNext(t,e){return e.run(t).pipe(kr(!1))}runNextWithState(t,e){let r=M(t.messages||[]),n=M(t.state||{}),o=new mn;return Bo(t,o,e,[]).subscribe(s=>{s.messages!==void 0&&(r=s.messages),s.state!==void 0&&(n=s.state)}),this.runNext(t,e).pipe(wr(async s=>(o.next(s),await new Promise(a=>setTimeout(a,0)),{event:s,messages:M(r),state:M(n)})))}},du=class extends An{constructor(t){super(),this.fn=t}run(t,e){return this.fn(t,e)}};function fu(t){let e=t.content;if(Array.isArray(e)){let r=e.filter(n=>typeof n=="object"&&!!n&&"type"in n&&n.type==="text"&&typeof n.text=="string").map(n=>n.text).join("");return{...t,content:r}}return typeof e=="string"?t:{...t,content:""}}var pu=class extends An{run(t,e){let{parentRunId:r,...n}=t,o={...n,messages:n.messages.map(fu)};return this.runNext(o,e)}},Fo="THINKING_START",Ho="THINKING_END",Vo="THINKING_TEXT_MESSAGE_START",$o="THINKING_TEXT_MESSAGE_CONTENT",jo="THINKING_TEXT_MESSAGE_END",mu=class extends An{constructor(...t){super(...t),this.currentReasoningId=null,this.currentMessageId=null}warnAboutTransformation(t,e){typeof process<"u"&&process.env!==void 0&&process.env.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is converting ${t} to ${e}. To remove this warning, upgrade your AG-UI integration package (e.g. @ag-ui/langgraph). To surpress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(t,e){return this.currentReasoningId=null,this.currentMessageId=null,this.runNext(t,e).pipe(ot(r=>this.transformEvent(r)))}transformEvent(t){switch(t.type){case Fo:{this.currentReasoningId=Vt();let{title:e,...r}=t;return this.warnAboutTransformation(Fo,g.REASONING_START),{...r,type:g.REASONING_START,messageId:this.currentReasoningId}}case Vo:return this.currentMessageId=Vt(),this.warnAboutTransformation(Vo,g.REASONING_MESSAGE_START),{...t,type:g.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:"assistant"};case $o:{let{delta:e,...r}=t;return this.warnAboutTransformation($o,g.REASONING_MESSAGE_CONTENT),{...r,type:g.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??Vt(),delta:e}}case jo:{let e=this.currentMessageId??Vt();return this.warnAboutTransformation(jo,g.REASONING_MESSAGE_END),{...t,type:g.REASONING_MESSAGE_END,messageId:e}}case Ho:{let e=this.currentReasoningId??Vt();return this.warnAboutTransformation(Ho,g.REASONING_END),{...t,type:g.REASONING_END,messageId:e}}default:return t}}},hu="0.0.52",Rr=class{get maxVersion(){return hu}get debug(){return this._debug}set debug(t){this._debug=Cr(t),this._debugLogger=bn(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(t){typeof t=="boolean"?this._debugLogger=t?bn(Cr(!0)):void 0:this._debugLogger=t}constructor({agentId:t,description:e,threadId:r,initialMessages:n,initialState:o,debug:s}={}){this.subscribers=[],this.isRunning=!1,this.middlewares=[],this.agentId=t,this.description=e??"",this.threadId=r??Ie(),this.messages=M(n??[]),this.state=M(o??{}),this._debug=Cr(s),this._debugLogger=bn(this._debug),Nr(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new pu),Nr(this.maxVersion,"0.0.45")<=0&&this.middlewares.unshift(new mu)}subscribe(t){return this.subscribers.push(t),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(e=>e!==t)}}}use(...t){let e=t.map(r=>typeof r=="function"?new du(r):r);return this.middlewares.push(...e),this}async runAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??Ie();let r=this.prepareRunAgentInput(t);this.debugLogger?.lifecycle("LIFECYCLE","Run started:",{agentId:this.agentId,threadId:this.threadId});let n,o=new Set(this.messages.map(c=>c.id)),s=[{onRunFinishedEvent:c=>{n=c.result}},...this.subscribers,e??{}];await this.onInitialize(r,s),this.activeRunDetach$=new nt;let a;this.activeRunCompletionPromise=new Promise(c=>{a=c}),await Tr(cr(()=>this.middlewares.length===0?this.run(r):this.middlewares.reduceRight((c,u)=>({run:p=>u.run(p,c),get messages(){return c.messages},get state(){return c.state}}),this).run(r),kr(this.debugLogger),Sn(this.debugLogger),c=>c.pipe(Ar(this.activeRunDetach$)),c=>this.apply(r,c,s),c=>this.processApplyEvents(r,c,s),Ht(c=>(this.debugLogger?.lifecycle("LIFECYCLE","Run errored:",{agentId:this.agentId,error:c instanceof Error?c.message:String(c)}),this.isRunning=!1,this.onError(r,c,s))),st(()=>{this.debugLogger?.lifecycle("LIFECYCLE","Run finished:",{agentId:this.agentId,threadId:this.threadId}),this.isRunning=!1,this.onFinalize(r,s),a?.(),a=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(j(null)));let i=M(this.messages).filter(c=>!o.has(c.id));return{result:n,newMessages:i}}finally{this.isRunning=!1}}connect(t){throw new en}async connectAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??Ie();let r=this.prepareRunAgentInput(t),n,o=new Set(this.messages.map(c=>c.id)),s=[{onRunFinishedEvent:c=>{n=c.result}},...this.subscribers,e??{}];await this.onInitialize(r,s),this.activeRunDetach$=new nt;let a;this.activeRunCompletionPromise=new Promise(c=>{a=c}),await Tr(cr(()=>gn(()=>this.connect(r)),kr(this.debugLogger),Sn(this.debugLogger),c=>c.pipe(Ar(this.activeRunDetach$)),c=>this.apply(r,c,s),c=>this.processApplyEvents(r,c,s),Ht(c=>(this.isRunning=!1,c instanceof en?dr:this.onError(r,c,s))),st(()=>{this.isRunning=!1,this.onFinalize(r,s),a?.(),a=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(j(null)),{defaultValue:void 0});let i=M(this.messages).filter(c=>!o.has(c.id));return{result:n,newMessages:i}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let t=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await t}apply(t,e,r){return Bo(t,e,this,r,this.debugLogger)}processApplyEvents(t,e,r){return e.pipe(vn(n=>{n.messages&&(this.messages=n.messages,r.forEach(o=>{o.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),n.state&&(this.state=n.state,r.forEach(o=>{o.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))}))}prepareRunAgentInput(t){let e=M(this.messages).filter(r=>r.role!=="activity");return{threadId:this.threadId,runId:t?.runId||Ie(),tools:M(t?.tools??[]),context:M(t?.context??[]),forwardedProps:M(t?.forwardedProps??{}),state:M(this.state),messages:e}}async onInitialize(t,e){let r=await L(e,this.messages,this.state,(n,o,s)=>n.onRunInitialized?.({messages:o,state:s,agent:this,input:t}));(r.messages!==void 0||r.state!==void 0)&&(r.messages&&(this.messages=r.messages,t.messages=r.messages,e.forEach(n=>{n.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),r.state&&(this.state=r.state,t.state=r.state,e.forEach(n=>{n.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}onError(t,e,r){return Ft(L(r,this.messages,this.state,(n,o,s)=>n.onRunFailed?.({error:e,messages:o,state:s,agent:this,input:t}))).pipe(ot(n=>{let o=n;if((o.messages!==void 0||o.state!==void 0)&&(o.messages!==void 0&&(this.messages=o.messages,r.forEach(s=>{s.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),o.state!==void 0&&(this.state=o.state,r.forEach(s=>{s.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))),o.stopPropagation!==!0){let s=String(e);if(!(e.name==="AbortError"||e.message==="Fetch is aborted"||e.message==="signal is aborted without reason"||e.message==="component unmounted"||s==="component unmounted"))throw console.error("Agent execution failed:",e),e}return{}}))}async onFinalize(t,e){let r=await L(e,this.messages,this.state,(n,o,s)=>n.onRunFinalized?.({messages:o,state:s,agent:this,input:t}));(r.messages!==void 0||r.state!==void 0)&&(r.messages!==void 0&&(this.messages=r.messages,e.forEach(n=>{n.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),r.state!==void 0&&(this.state=r.state,e.forEach(n=>{n.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}clone(){let t=Object.create(Object.getPrototypeOf(this));return t.agentId=this.agentId,t.description=this.description,t.threadId=this.threadId,t.messages=M(this.messages),t.state=M(this.state),t._debug=this._debug,t._debugLogger=this._debugLogger,t.isRunning=this.isRunning,t.subscribers=[...this.subscribers],t.middlewares=[...this.middlewares],t}addMessage(t){this.messages.push(t),(async()=>{for(let e of this.subscribers)await e.onNewMessage?.({message:t,messages:this.messages,state:this.state,agent:this});if(t.role==="assistant"&&t.toolCalls)for(let e of t.toolCalls)for(let r of this.subscribers)await r.onNewToolCall?.({toolCall:e,messages:this.messages,state:this.state,agent:this});for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}addMessages(t){this.messages.push(...t),(async()=>{for(let e of t){for(let r of this.subscribers)await r.onNewMessage?.({message:e,messages:this.messages,state:this.state,agent:this});if(e.role==="assistant"&&e.toolCalls)for(let r of e.toolCalls)for(let n of this.subscribers)await n.onNewToolCall?.({toolCall:r,messages:this.messages,state:this.state,agent:this})}for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setMessages(t){this.messages=M(t),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(t){this.state=M(t),(async()=>{for(let e of this.subscribers)await e.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(t){this.agentId=this.agentId??Ie();let e=this.prepareRunAgentInput(t);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((r,n)=>({run:o=>n.run(o,r),get messages(){return r.messages},get state(){return r.state}}),this).run(e)).pipe(kr(this.debugLogger),Sn(this.debugLogger),uu(this.threadId,e.runId,this.agentId),r=>r.pipe(ot(n=>(this.debugLogger?.event("LEGACY","Event:",n,{type:n.type}),n))))}};var Wo=1,Or="0.1.0",In="X-CSRF-Token",Xo="X-Surogates-Widget-Version",zo="/v1/website/sessions",Ko=t=>`/v1/website/sessions/${t}/messages`,Zo=(t,e)=>`/v1/website/sessions/${t}/events?after=${e}`,Yo=t=>`/v1/website/sessions/${t}/end`,qo=t=>`/api/widget/p/${encodeURIComponent(t)}`,Jo="https://api.surogate.ai",D={USER_MESSAGE:"user.message",LLM_REQUEST:"llm.request",LLM_RESPONSE:"llm.response",LLM_THINKING:"llm.thinking",LLM_DELTA:"llm.delta",TOOL_CALL:"tool.call",TOOL_RESULT:"tool.result",SANDBOX_PROVISION:"sandbox.provision",SANDBOX_EXECUTE:"sandbox.execute",SANDBOX_RESULT:"sandbox.result",SANDBOX_DESTROY:"sandbox.destroy",SESSION_START:"session.start",SESSION_PAUSE:"session.pause",SESSION_RESUME:"session.resume",SESSION_COMPLETE:"session.complete",SESSION_FAIL:"session.fail",SESSION_DONE:"session.done",CONTEXT_COMPACT:"context.compact",MEMORY_UPDATE:"memory.update",EXPERT_DELEGATION:"expert.delegation",EXPERT_RESULT:"expert.result",EXPERT_FAILURE:"expert.failure",POLICY_DENIED:"policy.denied",POLICY_ALLOWED:"policy.allowed",HARNESS_CRASH:"harness.crash"};var Pe=class extends Error{constructor(e,r){super(e),this.name="SurogatesError",r?.status!==void 0&&(this.status=r.status),r?.detail!==void 0&&(this.detail=r.detail),r?.cause!==void 0&&(this.cause=r.cause)}},ce=class extends Pe{constructor(e,r){super(e,r),this.name="SurogatesAuthError"}},Me=class extends Pe{constructor(e,r){super(e,r),this.name="SurogatesRateLimitError",r?.retryAfter!==void 0&&(this.retryAfter=r.retryAfter)}},ye=class extends Pe{constructor(e,r){super(e,r),this.name="SurogatesProtocolError"}},Le=class extends Pe{constructor(e,r){super(e,r),this.name="SurogatesNetworkError"}};async function Qo(t,e,r=fetch){let n=t.replace(/\/+$/,"")+qo(e),o;try{o=await r(n,{method:"GET"})}catch(a){throw new Le("Widget pairing request failed",{cause:a})}if(!o.ok)throw new ce("Unknown or inactive widget key",{status:o.status});let s;try{s=await o.json()}catch(a){throw new ye("Pairing returned a non-JSON body",{cause:a})}if(typeof s?.agent_id!="string"||typeof s?.api_web_url!="string")throw new ye("Pairing response missing agent_id / api_web_url");return{agentId:s.agent_id,apiWebUrl:s.api_web_url}}function Pr(t,e){if(!e)return t;let r=t.includes("?")?"&":"?";return`${t}${r}agent_id=${encodeURIComponent(e)}`}async function Nn(t,e){let r;try{r=await fetch(t,{...e,credentials:"include",headers:{...e.headers,[Xo]:Or}})}catch(n){throw new Le("Network request failed",{cause:n})}return r}async function gu(t){try{let e=await t.json();return typeof e.detail=="string"?e.detail:void 0}catch{return}}async function es(t,e){let r=await gu(t);if(t.status===401||t.status===403)throw new ce(`${e} rejected (${t.status})`,{status:t.status,...r!==void 0&&{detail:r}});if(t.status===429){let n=t.headers.get("Retry-After"),o=n?Number(n):void 0;throw new Me(`${e} rate-limited`,{status:t.status,...o!==void 0&&Number.isFinite(o)&&{retryAfter:o},...r!==void 0&&{detail:r}})}throw t.status>=500?new Le(`${e} failed (${t.status}${r?`: ${r}`:""})`):new ye(`${e} failed (${t.status})`,{status:t.status,...r!==void 0&&{detail:r}})}async function ts(t,e,r){let n=await Nn(t+Pr(zo,r),{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});n.ok||await es(n,"Bootstrap");let o;try{o=await n.json()}catch(s){throw new ye("Bootstrap returned non-JSON body",{cause:s})}if(!o||typeof o.session_id!="string"||typeof o.csrf_token!="string")throw new ye("Bootstrap response missing required fields");return{sessionId:o.session_id,csrfToken:o.csrf_token,expiresAt:Number(o.expires_at)||0,agentName:o.agent_name??""}}async function Cn(t,e,r,n,o){let s=await Nn(t+Pr(Ko(e),o),{method:"POST",headers:{"Content-Type":"application/json",[In]:r},body:JSON.stringify({content:n})});s.ok||await es(s,"Send message");let a=await s.json().catch(()=>({}));return{eventId:Number(a.event_id??0)}}async function rs(t,e,r,n){try{await Nn(t+Pr(Yo(e),n),{method:"POST",headers:{[In]:r}})}catch{}}function ns(t,e,r,n){let o=t+Pr(Zo(e,r),n);return new EventSource(o,{withCredentials:!0})}var _u=new Set(["stop","end_turn","length"]),vu=new Set(["tool_calls","function_call","tool_use"]),at=class{constructor(){this.pendingToolCalls=new Set;this._turnComplete=!1}get isTurnComplete(){return this._turnComplete}translate(e){switch(e.type){case D.LLM_DELTA:return this.handleLlmDelta(e);case D.LLM_RESPONSE:return this.handleLlmResponse(e);case D.LLM_THINKING:return this.handleLlmThinking(e);case D.TOOL_CALL:return this.handleToolCall(e);case D.TOOL_RESULT:return this.handleToolResult(e);case D.POLICY_DENIED:return this.handlePolicyDenied(e);case D.EXPERT_DELEGATION:return this.handleExpertDelegation(e);case D.EXPERT_RESULT:return this.handleExpertResult(e);case D.EXPERT_FAILURE:return this.asCustom(e);case D.SESSION_FAIL:case D.HARNESS_CRASH:return this.handleTerminalFailure(e);case D.SESSION_DONE:case D.SESSION_COMPLETE:return this._turnComplete=!0,[];case D.USER_MESSAGE:case D.LLM_REQUEST:case D.SESSION_START:case D.SESSION_PAUSE:case D.SESSION_RESUME:case D.SANDBOX_PROVISION:case D.SANDBOX_EXECUTE:case D.SANDBOX_RESULT:case D.SANDBOX_DESTROY:case D.POLICY_ALLOWED:return[];default:return this.asCustom(e)}}handleLlmDelta(e){let r=e.data??{},n=r.delta??r.content??"";if(!n)return[];let o=this.currentMessageId??r.message_id??this.mintMessageId(e.id);return this.currentMessageId=o,[{type:g.TEXT_MESSAGE_CHUNK,messageId:o,role:"assistant",delta:n}]}handleLlmResponse(e){let r=e.data??{},n=[];if(!this.currentMessageId&&r.content){let i=r.message_id??r.id??this.mintMessageId(e.id);n.push({type:g.TEXT_MESSAGE_CHUNK,messageId:i,role:"assistant",delta:r.content})}this.currentMessageId=void 0;let o=Array.isArray(r.tool_calls)?r.tool_calls:[],s=r.finish_reason??r.stop_reason??"";return vu.has(s)||o.length===0&&(s===""||_u.has(s))&&this.pendingToolCalls.size===0&&(this._turnComplete=!0),n}handleLlmThinking(e){let r=e.data??{},n=r.delta??r.content??"";if(!n)return[];let o=this.currentReasoningId??r.message_id??this.mintMessageId(e.id),s=this.currentReasoningId!==o;this.currentReasoningId=o;let a=[];return s&&(a.push({type:g.REASONING_START,messageId:o}),a.push({type:g.REASONING_MESSAGE_START,messageId:o,role:"reasoning"})),a.push({type:g.REASONING_MESSAGE_CONTENT,messageId:o,delta:n}),a}handleToolCall(e){let r=e.data??{},n=r.tool_call_id??`tc-${e.id}`,o=r.name??"unknown_tool";this.currentMessageId=void 0,this.currentReasoningId=void 0,this.pendingToolCalls.add(n);let s=typeof r.arguments=="string"?r.arguments:JSON.stringify(r.arguments??{});return[{type:g.TOOL_CALL_CHUNK,toolCallId:n,toolCallName:o,delta:s}]}handleToolResult(e){let r=e.data??{},n=r.tool_call_id??`tc-${e.id}`,o=r.content??"";return this.pendingToolCalls.delete(n),[{type:g.TOOL_CALL_RESULT,messageId:`tr-${e.id}`,toolCallId:n,content:o,role:"tool"}]}handlePolicyDenied(e){let r=e.data??{};return[{type:g.CUSTOM,name:D.POLICY_DENIED,value:{tool:r.tool,reason:r.reason}}]}handleExpertDelegation(e){let n=(e.data??{}).expert_name??"expert";return[{type:g.STEP_STARTED,stepName:`expert:${n}`}]}handleExpertResult(e){let n=(e.data??{}).expert_name??"expert";return[{type:g.STEP_FINISHED,stepName:`expert:${n}`}]}handleTerminalFailure(e){this._turnComplete=!0;let r=e.data??{},n=r.error??r.message??`${e.type} fired`;return[{type:g.RUN_ERROR,message:n,code:e.type}]}asCustom(e){return[{type:g.CUSTOM,name:e.type,value:e.data}]}mintMessageId(e){return`msg-${e}`}};var yu=Object.values(D),Eu=250,wt=class extends Rr{constructor(r){super(r);this.cursor=0;if(!r.apiUrl)throw new F('WebsiteAgent: "apiUrl" is required.');if(!r.publishableKey)throw new F('WebsiteAgent: "publishableKey" is required.');this.apiUrl=r.apiUrl.replace(/\/+$/,""),this.publishableKey=r.publishableKey}async ensureBootstrapped(){return this.bootstrapResult?this.bootstrapResult:(this.bootstrapResult=await ts(this.apiUrl,this.publishableKey,this.agentId),this.bootstrapResult)}async end(){let r=this.bootstrapResult;r&&(this.bootstrapResult=void 0,this.cursor=0,await rs(this.apiUrl,r.sessionId,r.csrfToken,this.agentId))}run(r){return new H(n=>{let o={terminated:!1,source:void 0,drainTimer:void 0};return this.driveRun(r,n,o).catch(s=>{o.terminated||(o.terminated=!0,n.error(s))}),()=>{o.terminated=!0,o.drainTimer===void 0&&(Mr(o.source),o.source=void 0)}})}async driveRun(r,n,o){if(!o.terminated){n.next({type:g.RUN_STARTED,threadId:r.threadId,runId:r.runId});try{let s=this.extractUserText(r.messages),a=await this.ensureBootstrapped();this.replaceStreamSource(o,a.sessionId,this.cursor,new at,n,r),await this.sendWithCookieRecovery(a,s,i=>{this.replaceStreamSource(o,i.sessionId,0,new at,n,r)})}catch(s){if(o.terminated)return;o.terminated=!0;let a=s instanceof Error?s.message:String(s),i=s instanceof ce?"auth":"error";n.next({type:g.RUN_ERROR,message:a,code:i}),Mr(o.source),o.source=void 0,n.complete()}}}replaceStreamSource(r,n,o,s,a,i){Mr(r.source);let c=ns(this.apiUrl,n,o,this.agentId);r.source=c,this.attachStreamListeners(c,s,a,i,r)}async sendWithCookieRecovery(r,n,o){try{await Cn(this.apiUrl,r.sessionId,r.csrfToken,n,this.agentId);return}catch(s){if(!(s instanceof ce))throw s;this.bootstrapResult=void 0,this.cursor=0;let a=await this.ensureBootstrapped();o(a),await Cn(this.apiUrl,a.sessionId,a.csrfToken,n,this.agentId)}}attachStreamListeners(r,n,o,s,a){let i=()=>{a.drainTimer!==void 0&&globalThis.clearTimeout(a.drainTimer),a.drainTimer=globalThis.setTimeout(()=>{a.drainTimer=void 0,Mr(r)},Eu)},c=()=>{a.terminated||(a.terminated=!0,o.next({type:g.RUN_FINISHED,threadId:s.threadId,runId:s.runId}),i(),o.complete())},u=(p,f,v)=>{let d;try{d=JSON.parse(f)}catch{d=f}let m={id:Number(v)||0,type:p,data:d};if(m.id>this.cursor&&(this.cursor=m.id),a.terminated)return;let h=n.translate(m);for(let y of h)o.next(y);n.isTurnComplete&&c()};for(let p of yu)r.addEventListener(p,f=>{u(p,f.data,f.lastEventId)});r.onerror=()=>{r.readyState===2&&(a.terminated||(a.terminated=!0,o.next({type:g.RUN_ERROR,message:"SSE connection closed",code:"sse_closed"}),o.complete()))}}extractUserText(r){for(let n=r.length-1;n>=0;n--){let o=r[n];if(!o||o.role!=="user")continue;let s=o.content;if(typeof s=="string"&&s.trim().length>0)return s}throw new F("WebsiteAgent: no user message with string content found in input.messages.")}};function Mr(t){if(t){try{t.onerror=null}catch{}t.close()}}var $r,U,ls,bu,De,os,us,cs,kn,Dr,$t,ds,Mn,Rn,On,Su,Fr={},Hr=[],xu=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,jr=Array.isArray;function we(t,e){for(var r in e)t[r]=e[r];return t}function Ln(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Tu(t,e,r){var n,o,s,a={};for(s in e)s=="key"?n=e[s]:s=="ref"?o=e[s]:a[s]=e[s];if(arguments.length>2&&(a.children=arguments.length>3?$r.call(arguments,2):r),typeof t=="function"&&t.defaultProps!=null)for(s in t.defaultProps)a[s]===void 0&&(a[s]=t.defaultProps[s]);return Ur(t,a,n,o,null)}function Ur(t,e,r,n,o){var s={type:t,props:e,key:r,ref:n,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++ls,__i:-1,__u:0};return o==null&&U.vnode!=null&&U.vnode(s),s}function It(t){return t.children}function Gr(t,e){this.props=t,this.context=e}function At(t,e){if(e==null)return t.__?At(t.__,t.__i+1):null;for(var r;e<t.__k.length;e++)if((r=t.__k[e])!=null&&r.__e!=null)return r.__e;return typeof t.type=="function"?At(t):null}function wu(t){if(t.__P&&t.__d){var e=t.__v,r=e.__e,n=[],o=[],s=we({},e);s.__v=e.__v+1,U.vnode&&U.vnode(s),Dn(t.__P,s,e,t.__n,t.__P.namespaceURI,32&e.__u?[r]:null,n,r??At(e),!!(32&e.__u),o),s.__v=e.__v,s.__.__k[s.__i]=s,hs(n,s,o),e.__e=e.__=null,s.__e!=r&&fs(s)}}function fs(t){if((t=t.__)!=null&&t.__c!=null)return t.__e=t.__c.base=null,t.__k.some(function(e){if(e!=null&&e.__e!=null)return t.__e=t.__c.base=e.__e}),fs(t)}function ss(t){(!t.__d&&(t.__d=!0)&&De.push(t)&&!Vr.__r++||os!=U.debounceRendering)&&((os=U.debounceRendering)||us)(Vr)}function Vr(){try{for(var t,e=1;De.length;)De.length>e&&De.sort(cs),t=De.shift(),e=De.length,wu(t)}finally{De.length=Vr.__r=0}}function ps(t,e,r,n,o,s,a,i,c,u,p){var f,v,d,m,h,y,E,_=n&&n.__k||Hr,I=e.length;for(c=Au(r,e,_,c,I),f=0;f<I;f++)(d=r.__k[f])!=null&&(v=d.__i!=-1&&_[d.__i]||Fr,d.__i=f,y=Dn(t,d,v,o,s,a,i,c,u,p),m=d.__e,d.ref&&v.ref!=d.ref&&(v.ref&&Un(v.ref,null,d),p.push(d.ref,d.__c||m,d)),h==null&&m!=null&&(h=m),(E=!!(4&d.__u))||v.__k===d.__k?(c=ms(d,c,t,E),E&&v.__e&&(v.__e=null)):typeof d.type=="function"&&y!==void 0?c=y:m&&(c=m.nextSibling),d.__u&=-7);return r.__e=h,c}function Au(t,e,r,n,o){var s,a,i,c,u,p=r.length,f=p,v=0;for(t.__k=new Array(o),s=0;s<o;s++)(a=e[s])!=null&&typeof a!="boolean"&&typeof a!="function"?(typeof a=="string"||typeof a=="number"||typeof a=="bigint"||a.constructor==String?a=t.__k[s]=Ur(null,a,null,null,null):jr(a)?a=t.__k[s]=Ur(It,{children:a},null,null,null):a.constructor===void 0&&a.__b>0?a=t.__k[s]=Ur(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):t.__k[s]=a,c=s+v,a.__=t,a.__b=t.__b+1,i=null,(u=a.__i=Iu(a,r,c,f))!=-1&&(f--,(i=r[u])&&(i.__u|=2)),i==null||i.__v==null?(u==-1&&(o>p?v--:o<p&&v++),typeof a.type!="function"&&(a.__u|=4)):u!=c&&(u==c-1?v--:u==c+1?v++:(u>c?v--:v++,a.__u|=4))):t.__k[s]=null;if(f)for(s=0;s<p;s++)(i=r[s])!=null&&(2&i.__u)==0&&(i.__e==n&&(n=At(i)),_s(i,i));return n}function ms(t,e,r,n){var o,s;if(typeof t.type=="function"){for(o=t.__k,s=0;o&&s<o.length;s++)o[s]&&(o[s].__=t,e=ms(o[s],e,r,n));return e}t.__e!=e&&(n&&(e&&t.type&&!e.parentNode&&(e=At(t)),r.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Iu(t,e,r,n){var o,s,a,i=t.key,c=t.type,u=e[r],p=u!=null&&(2&u.__u)==0;if(u===null&&i==null||p&&i==u.key&&c==u.type)return r;if(n>(p?1:0)){for(o=r-1,s=r+1;o>=0||s<e.length;)if((u=e[a=o>=0?o--:s++])!=null&&(2&u.__u)==0&&i==u.key&&c==u.type)return a}return-1}function as(t,e,r){e[0]=="-"?t.setProperty(e,r??""):t[e]=r==null?"":typeof r!="number"||xu.test(e)?r:r+"px"}function Lr(t,e,r,n,o){var s,a;e:if(e=="style")if(typeof r=="string")t.style.cssText=r;else{if(typeof n=="string"&&(t.style.cssText=n=""),n)for(e in n)r&&e in r||as(t.style,e,"");if(r)for(e in r)n&&r[e]==n[e]||as(t.style,e,r[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(ds,"$1")),a=e.toLowerCase(),e=a in t||e=="onFocusOut"||e=="onFocusIn"?a.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+s]=r,r?n?r[$t]=n[$t]:(r[$t]=Mn,t.addEventListener(e,s?On:Rn,s)):t.removeEventListener(e,s?On:Rn,s);else{if(o=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=r??"";break e}catch{}typeof r=="function"||(r==null||r===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&r==1?"":r))}}function is(t){return function(e){if(this.l){var r=this.l[e.type+t];if(e[Dr]==null)e[Dr]=Mn++;else if(e[Dr]<r[$t])return;return r(U.event?U.event(e):e)}}}function Dn(t,e,r,n,o,s,a,i,c,u){var p,f,v,d,m,h,y,E,_,I,$,Z,Ue,pe,Ct,se=e.type;if(e.constructor!==void 0)return null;128&r.__u&&(c=!!(32&r.__u),s=[i=e.__e=r.__e]),(p=U.__b)&&p(e);e:if(typeof se=="function")try{if(E=e.props,_=se.prototype&&se.prototype.render,I=(p=se.contextType)&&n[p.__c],$=p?I?I.props.value:p.__:n,r.__c?y=(f=e.__c=r.__c).__=f.__E:(_?e.__c=f=new se(E,$):(e.__c=f=new Gr(E,$),f.constructor=se,f.render=Cu),I&&I.sub(f),f.state||(f.state={}),f.__n=n,v=f.__d=!0,f.__h=[],f._sb=[]),_&&f.__s==null&&(f.__s=f.state),_&&se.getDerivedStateFromProps!=null&&(f.__s==f.state&&(f.__s=we({},f.__s)),we(f.__s,se.getDerivedStateFromProps(E,f.__s))),d=f.props,m=f.state,f.__v=e,v)_&&se.getDerivedStateFromProps==null&&f.componentWillMount!=null&&f.componentWillMount(),_&&f.componentDidMount!=null&&f.__h.push(f.componentDidMount);else{if(_&&se.getDerivedStateFromProps==null&&E!==d&&f.componentWillReceiveProps!=null&&f.componentWillReceiveProps(E,$),e.__v==r.__v||!f.__e&&f.shouldComponentUpdate!=null&&f.shouldComponentUpdate(E,f.__s,$)===!1){e.__v!=r.__v&&(f.props=E,f.state=f.__s,f.__d=!1),e.__e=r.__e,e.__k=r.__k,e.__k.some(function(Ae){Ae&&(Ae.__=e)}),Hr.push.apply(f.__h,f._sb),f._sb=[],f.__h.length&&a.push(f);break e}f.componentWillUpdate!=null&&f.componentWillUpdate(E,f.__s,$),_&&f.componentDidUpdate!=null&&f.__h.push(function(){f.componentDidUpdate(d,m,h)})}if(f.context=$,f.props=E,f.__P=t,f.__e=!1,Z=U.__r,Ue=0,_)f.state=f.__s,f.__d=!1,Z&&Z(e),p=f.render(f.props,f.state,f.context),Hr.push.apply(f.__h,f._sb),f._sb=[];else do f.__d=!1,Z&&Z(e),p=f.render(f.props,f.state,f.context),f.state=f.__s;while(f.__d&&++Ue<25);f.state=f.__s,f.getChildContext!=null&&(n=we(we({},n),f.getChildContext())),_&&!v&&f.getSnapshotBeforeUpdate!=null&&(h=f.getSnapshotBeforeUpdate(d,m)),pe=p!=null&&p.type===It&&p.key==null?gs(p.props.children):p,i=ps(t,jr(pe)?pe:[pe],e,r,n,o,s,a,i,c,u),f.base=e.__e,e.__u&=-161,f.__h.length&&a.push(f),y&&(f.__E=f.__=null)}catch(Ae){if(e.__v=null,c||s!=null)if(Ae.then){for(e.__u|=c?160:128;i&&i.nodeType==8&&i.nextSibling;)i=i.nextSibling;s[s.indexOf(i)]=null,e.__e=i}else{for(Ct=s.length;Ct--;)Ln(s[Ct]);Pn(e)}else e.__e=r.__e,e.__k=r.__k,Ae.then||Pn(e);U.__e(Ae,e,r)}else s==null&&e.__v==r.__v?(e.__k=r.__k,e.__e=r.__e):i=e.__e=Nu(r.__e,e,r,n,o,s,a,c,u);return(p=U.diffed)&&p(e),128&e.__u?void 0:i}function Pn(t){t&&(t.__c&&(t.__c.__e=!0),t.__k&&t.__k.some(Pn))}function hs(t,e,r){for(var n=0;n<r.length;n++)Un(r[n],r[++n],r[++n]);U.__c&&U.__c(e,t),t.some(function(o){try{t=o.__h,o.__h=[],t.some(function(s){s.call(o)})}catch(s){U.__e(s,o.__v)}})}function gs(t){return typeof t!="object"||t==null||t.__b>0?t:jr(t)?t.map(gs):t.constructor!==void 0?null:we({},t)}function Nu(t,e,r,n,o,s,a,i,c){var u,p,f,v,d,m,h,y=r.props||Fr,E=e.props,_=e.type;if(_=="svg"?o="http://www.w3.org/2000/svg":_=="math"?o="http://www.w3.org/1998/Math/MathML":o||(o="http://www.w3.org/1999/xhtml"),s!=null){for(u=0;u<s.length;u++)if((d=s[u])&&"setAttribute"in d==!!_&&(_?d.localName==_:d.nodeType==3)){t=d,s[u]=null;break}}if(t==null){if(_==null)return document.createTextNode(E);t=document.createElementNS(o,_,E.is&&E),i&&(U.__m&&U.__m(e,s),i=!1),s=null}if(_==null)y===E||i&&t.data==E||(t.data=E);else{if(s=_=="textarea"&&E.defaultValue!=null?null:s&&$r.call(t.childNodes),!i&&s!=null)for(y={},u=0;u<t.attributes.length;u++)y[(d=t.attributes[u]).name]=d.value;for(u in y)d=y[u],u=="dangerouslySetInnerHTML"?f=d:u=="children"||u in E||u=="value"&&"defaultValue"in E||u=="checked"&&"defaultChecked"in E||Lr(t,u,null,d,o);for(u in E)d=E[u],u=="children"?v=d:u=="dangerouslySetInnerHTML"?p=d:u=="value"?m=d:u=="checked"?h=d:i&&typeof d!="function"||y[u]===d||Lr(t,u,d,y[u],o);if(p)i||f&&(p.__html==f.__html||p.__html==t.innerHTML)||(t.innerHTML=p.__html),e.__k=[];else if(f&&(t.innerHTML=""),ps(e.type=="template"?t.content:t,jr(v)?v:[v],e,r,n,_=="foreignObject"?"http://www.w3.org/1999/xhtml":o,s,a,s?s[0]:r.__k&&At(r,0),i,c),s!=null)for(u=s.length;u--;)Ln(s[u]);i&&_!="textarea"||(u="value",_=="progress"&&m==null?t.removeAttribute("value"):m!=null&&(m!==t[u]||_=="progress"&&!m||_=="option"&&m!=y[u])&&Lr(t,u,m,y[u],o),u="checked",h!=null&&h!=t[u]&&Lr(t,u,h,y[u],o))}return t}function Un(t,e,r){try{if(typeof t=="function"){var n=typeof t.__u=="function";n&&t.__u(),n&&e==null||(t.__u=t(e))}else t.current=e}catch(o){U.__e(o,r)}}function _s(t,e,r){var n,o;if(U.unmount&&U.unmount(t),(n=t.ref)&&(n.current&&n.current!=t.__e||Un(n,null,e)),(n=t.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(s){U.__e(s,e)}n.base=n.__P=null}if(n=t.__k)for(o=0;o<n.length;o++)n[o]&&_s(n[o],e,r||typeof t.type!="function");r||Ln(t.__e),t.__c=t.__=t.__e=void 0}function Cu(t,e,r){return this.constructor(t,r)}function Gn(t,e,r){var n,o,s,a;e==document&&(e=document.documentElement),U.__&&U.__(t,e),o=(n=typeof r=="function")?null:r&&r.__k||e.__k,s=[],a=[],Dn(e,t=(!n&&r||e).__k=Tu(It,null,[t]),o||Fr,Fr,e.namespaceURI,!n&&r?[r]:o?null:e.firstChild?$r.call(e.childNodes):null,s,!n&&r?r:o?o.__e:e.firstChild,n,a),hs(s,t,a)}$r=Hr.slice,U={__e:function(t,e,r,n){for(var o,s,a;e=e.__;)if((o=e.__c)&&!o.__)try{if((s=o.constructor)&&s.getDerivedStateFromError!=null&&(o.setState(s.getDerivedStateFromError(t)),a=o.__d),o.componentDidCatch!=null&&(o.componentDidCatch(t,n||{}),a=o.__d),a)return o.__E=o}catch(i){t=i}throw t}},ls=0,bu=function(t){return t!=null&&t.constructor===void 0},Gr.prototype.setState=function(t,e){var r;r=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=we({},this.state),typeof t=="function"&&(t=t(we({},r),this.props)),t&&we(r,t),t!=null&&this.__v&&(e&&this._sb.push(e),ss(this))},Gr.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),ss(this))},Gr.prototype.render=It,De=[],us=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,cs=function(t,e){return t.__v.__b-e.__v.__b},Vr.__r=0,kn=Math.random().toString(8),Dr="__d"+kn,$t="__a"+kn,ds=/(PointerCapture)$|Capture$/i,Mn=0,Rn=is(!1),On=is(!0),Su=0;var vs=`
10
10
  :host { all: initial; }
11
11
  * { box-sizing: border-box; }
12
12
 
@@ -99,6 +99,7 @@ Error: ${y}`)}}return p()}case g.MESSAGES_SNAPSHOT:{let d=await L(n,a,i,(m,h,y)=
99
99
  border-radius: 6px;
100
100
  }
101
101
  .surg-close:hover { opacity: 1; background: rgba(255, 255, 255, 0.18); }
102
+ .surg-close svg { width: 18px; height: 18px; }
102
103
 
103
104
  .surg-messages {
104
105
  flex: 1;
@@ -216,9 +217,11 @@ Error: ${y}`)}}return p()}case g.MESSAGES_SNAPSHOT:{let d=await L(n,a,i,(m,h,y)=
216
217
  padding: 0 0 8px;
217
218
  background: #ffffff;
218
219
  }
219
- `;var jt,X,Gn,hs,Wr=0,xs=[],z=U,gs=z.__b,_s=z.__r,vs=z.diffed,ys=z.__c,Es=z.unmount,bs=z.__;function Hn(t,e){z.__h&&z.__h(X,t,Wr||e),Wr=0;var r=X.__H||(X.__H={__:[],__h:[]});return t>=r.__.length&&r.__.push({}),r.__[t]}function it(t){return Wr=1,Au(ws,t)}function Au(t,e,r){var n=Hn(jt++,2);if(n.t=t,!n.__c&&(n.__=[r?r(e):ws(void 0,e),function(i){var c=n.__N?n.__N[0]:n.__[0],u=n.t(c,i);c!==u&&(n.__N=[u,n.__[1]],n.__c.setState({}))}],n.__c=X,!X.__f)){var o=function(i,c,u){if(!n.__c.__H)return!0;var p=n.__c.__H.__.filter(function(v){return v.__c});if(p.every(function(v){return!v.__N}))return!s||s.call(this,i,c,u);var f=n.__c.props!==i;return p.some(function(v){if(v.__N){var d=v.__[0];v.__=v.__N,v.__N=void 0,d!==v.__[0]&&(f=!0)}}),s&&s.call(this,i,c,u)||f};X.__f=!0;var s=X.shouldComponentUpdate,a=X.componentWillUpdate;X.componentWillUpdate=function(i,c,u){if(this.__e){var p=s;s=void 0,o(i,c,u),s=p}a&&a.call(this,i,c,u)},X.shouldComponentUpdate=o}return n.__N||n.__}function Nt(t,e){var r=Hn(jt++,3);!z.__s&&Ts(r.__H,e)&&(r.__=t,r.u=e,X.__H.__h.push(r))}function Vn(t){return Wr=5,Iu(function(){return{current:t}},[])}function Iu(t,e){var r=Hn(jt++,7);return Ts(r.__H,e)&&(r.__=t(),r.__H=e,r.__h=t),r.__}function Nu(){for(var t;t=xs.shift();){var e=t.__H;if(t.__P&&e)try{e.__h.some(Br),e.__h.some(Fn),e.__h=[]}catch(r){e.__h=[],z.__e(r,t.__v)}}}z.__b=function(t){X=null,gs&&gs(t)},z.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),bs&&bs(t,e)},z.__r=function(t){_s&&_s(t),jt=0;var e=(X=t.__c).__H;e&&(Gn===X?(e.__h=[],X.__h=[],e.__.some(function(r){r.__N&&(r.__=r.__N),r.u=r.__N=void 0})):(e.__h.some(Br),e.__h.some(Fn),e.__h=[],jt=0)),Gn=X},z.diffed=function(t){vs&&vs(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(xs.push(e)!==1&&hs===z.requestAnimationFrame||((hs=z.requestAnimationFrame)||Cu)(Nu)),e.__H.__.some(function(r){r.u&&(r.__H=r.u),r.u=void 0})),Gn=X=null},z.__c=function(t,e){e.some(function(r){try{r.__h.some(Br),r.__h=r.__h.filter(function(n){return!n.__||Fn(n)})}catch(n){e.some(function(o){o.__h&&(o.__h=[])}),e=[],z.__e(n,r.__v)}}),ys&&ys(t,e)},z.unmount=function(t){Es&&Es(t);var e,r=t.__c;r&&r.__H&&(r.__H.__.some(function(n){try{Br(n)}catch(o){e=o}}),r.__H=void 0,e&&z.__e(e,r.__v))};var Ss=typeof requestAnimationFrame=="function";function Cu(t){var e,r=function(){clearTimeout(n),Ss&&cancelAnimationFrame(e),setTimeout(t)},n=setTimeout(r,35);Ss&&(e=requestAnimationFrame(r))}function Br(t){var e=X,r=t.__c;typeof r=="function"&&(t.__c=void 0,r()),X=e}function Fn(t){var e=X;t.__c=t.__(),X=e}function Ts(t,e){return!t||t.length!==e.length||e.some(function(r,n){return r!==t[n]})}function ws(t,e){return typeof e=="function"?e(t):e}var ku={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function $n(t){return t.replace(/[&<>"']/g,e=>ku[e]??e)}function Ou(t){let e=t.trim();if(/^(https?:|mailto:)/i.test(e))return e}function As(t){let e=t;return e=e.replace(/`([^`]+)`/g,(r,n)=>`<code>${n}</code>`),e=e.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(r,n,o)=>{let s=Ou(o);return s?`<a href="${s}" target="_blank" rel="noopener noreferrer">${n}</a>`:`${n}`}),e=e.replace(/\*\*([^*]+)\*\*/g,(r,n)=>`<strong>${n}</strong>`),e=e.replace(/(^|[^*])\*([^*\n]+)\*/g,(r,n,o)=>`${n}<em>${o}</em>`),e}function jn(t){let e=t.split(/```/),r=[];return e.forEach((n,o)=>{if(o%2===1){let i=n.replace(/^[^\n]*\n/,c=>n.includes(`
220
- `)?"":c);r.push(`<pre><code>${$n(i.replace(/\n$/,""))}</code></pre>`);return}let a=n.split(/\n{2,}/);for(let i of a){let c=i.split(`
221
- `).filter(v=>v.trim().length>0);if(c.length===0)continue;let u=c.every(v=>/^\s*[-*]\s+/.test(v)),p=c.every(v=>/^\s*\d+\.\s+/.test(v));if(u||p){let v=c.map(d=>d.replace(/^\s*(?:[-*]|\d+\.)\s+/,"")).map(d=>`<li>${As($n(d))}</li>`).join("");r.push(p?`<ol>${v}</ol>`:`<ul>${v}</ul>`);continue}let f=c.map(v=>As($n(v))).join("<br>");r.push(`<p>${f}</p>`)}}),r.join("")}var Ru=/<next_action([^>]*)>([\s\S]*?)<\/next_action>\s*/gi,Pu=/(?:^|\n)\s*<(?:n(?:e(?:x(?:t(?:_(?:a(?:c(?:t(?:i(?:o(?:n[\s\S]*)?)?)?)?)?)?)?)?)?)?)?$/i;function Is(t){if(!t)return t;let e=t.replace(Ru,"").trimEnd(),r=Pu.exec(e);return r?e.slice(0,r.index).trimEnd():e}var Mu=0;function R(t,e,r,n,o,s){e||(e={});var a,i,c=e;if("ref"in c)for(i in c={},e)i=="ref"?a=e[i]:c[i]=e[i];var u={type:t,props:c,key:r,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Mu,__i:-1,__u:0,__source:o,__self:s};if(typeof t=="function"&&(a=t.defaultProps))for(i in a)c[i]===void 0&&(c[i]=a[i]);return U.vnode&&U.vnode(u),u}var Lu="Typically replies instantly",Du="Hi! \u{1F44B} How can I help you today?";function Cs(){return`u-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`}function Bn(t){let e=[];for(let r of t){if(r.role!=="user"&&r.role!=="assistant")continue;let n=typeof r.content=="string"?r.content:"";e.push({id:r.id??Cs(),role:r.role,content:n})}return e}function Ns(t){if(t instanceof fe)return"This chat isn\u2019t accepting messages from this site yet. The site owner needs to allow this origin.";if(t instanceof Pe)return"You\u2019re sending messages too quickly. Please wait a moment and try again.";if(t&&typeof t=="object"){let e=t.code;if(e==="auth")return"This chat isn\u2019t accepting messages from this site yet. The site owner needs to allow this origin.";if(e==="sse_closed")return"Connection lost. Please send your message again.";let r=t.message;if(r&&r.length<160)return r}return"Something went wrong. Please try again."}var Uu=R("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:R("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})}),Gu=R("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[R("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),R("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),Fu=R("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[R("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),R("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]});function ks({agent:t,config:e,registerOpenControl:r,onOpenChange:n}){let o=!!e.inline,[s,a]=it(o||!!e.openByDefault),[i,c]=it(()=>Bn(t.messages)),[u,p]=it(!1),[f,v]=it(null),[d,m]=it(""),[h,y]=it(""),E=e.title||h||"Assistant",_=Vn(null),I=Vn(!1);Nt(()=>r(a),[r]),Nt(()=>n?.(s),[s,n]),Nt(()=>{let G=t.subscribe({onMessagesChanged:()=>c(Bn(t.messages)),onRunStartedEvent:()=>{p(!0),v(null)},onRunFinishedEvent:()=>p(!1),onRunErrorEvent:({event:Ms})=>{p(!1),v(Ns(Ms))}});return()=>G.unsubscribe()},[t]),Nt(()=>{!s||I.current||(I.current=!0,t.ensureBootstrapped().then(G=>{G.agentName&&y(G.agentName)}).catch(G=>{I.current=!1,v(Ns(G))}))},[s,t]),Nt(()=>{let G=_.current;G&&(G.scrollTop=G.scrollHeight)},[i,u]);let $=()=>{let G=d.trim();!G||u||(m(""),t.addMessage({id:Cs(),role:"user",content:G}),c(Bn(t.messages)),t.runAgent().catch(()=>{}))},Z=G=>{G.key==="Enter"&&!G.shiftKey&&(G.preventDefault(),$())},De=e.subtitle??Lu,pe=e.welcomeMessage??Du,Ct=i.some(G=>G.role==="assistant"),se=!!pe&&!Ct,we=u&&i[i.length-1]?.role!=="assistant";if(!o&&!s)return R("button",{type:"button",class:`surg-launcher surg-pos-${e.position??"bottom-right"}`,"aria-label":"Open chat",onClick:()=>a(!0),children:e.logoUrl?R("img",{class:"surg-launcher-logo",src:e.logoUrl,alt:""}):Uu});let Ps=o?"surg-panel surg-inline":`surg-panel surg-pos-${e.position??"bottom-right"}`;return R("div",{class:Ps,role:"dialog","aria-label":E,children:[R("div",{class:"surg-header",children:[R("div",{class:"surg-header-id",children:[e.logoUrl&&R("img",{class:"surg-logo",src:e.logoUrl,alt:""}),R("div",{class:"surg-header-text",children:[R("span",{class:"surg-title",children:E}),De&&R("span",{class:"surg-subtitle",children:De})]})]}),!o&&R("button",{type:"button",class:"surg-close","aria-label":"Close chat",onClick:()=>a(!1),children:Gu})]}),R("div",{class:"surg-messages",ref:_,children:[se&&R("div",{class:"surg-bubble surg-assistant",dangerouslySetInnerHTML:{__html:jn(pe)}}),i.map(G=>G.role==="assistant"?R("div",{class:"surg-bubble surg-assistant",dangerouslySetInnerHTML:{__html:jn(Is(G.content))}},G.id):R("div",{class:"surg-bubble surg-user",children:G.content},G.id)),we&&R("div",{class:"surg-bubble surg-assistant surg-typing",children:[R("span",{}),R("span",{}),R("span",{})]})]}),f&&R("div",{class:"surg-error",children:f}),R("div",{class:"surg-composer",children:[R("textarea",{class:"surg-input",rows:1,placeholder:"Type a message\u2026",value:d,disabled:u,onInput:G=>m(G.target.value),onKeyDown:Z}),R("button",{type:"button",class:"surg-send","aria-label":"Send",disabled:u||!d.trim(),onClick:$,children:Fu})]}),R("div",{class:"surg-powered",children:"Powered by Surogate"})]})}var Os="#4f46e5";function Hu(t){let e=t.replace("#",""),r=e.length===3?e.split("").map(i=>i+i).join(""):e;if(r.length!==6||/[^0-9a-f]/i.test(r))return"#ffffff";let n=parseInt(r.slice(0,2),16),o=parseInt(r.slice(2,4),16),s=parseInt(r.slice(4,6),16);return(.299*n+.587*o+.114*s)/255>.62?"#0f172a":"#ffffff"}function Rs(t){if(!t||!t.apiUrl||!t.publishableKey)throw new Error('SurogatesWidget.mount: "apiUrl" and "publishableKey" are required.');let e=t.accentColor??Os,r=!1,n=document.createElement("div");n.setAttribute("data-surogates-widget","");let o=n.attachShadow({mode:"open"}),s=document.createElement("style");s.textContent=ms,o.appendChild(s);let a=document.createElement("div");a.className="surg-root",o.appendChild(a);let i=E=>{let _=E??Os;a.style.setProperty("--surg-accent",_),a.style.setProperty("--surg-accent-fg",Hu(_))};i(e);let c=()=>(t.target??document.body)?.appendChild(n);t.target||document.body?c():document.addEventListener("DOMContentLoaded",()=>{r||c()},{once:!0});let u=new wt(t),p,f=t.inline||!!t.openByDefault,v=E=>{p=E},d=E=>{f=E},m=t,h=()=>{Un(R(ks,{agent:u,config:m,registerOpenControl:v,onOpenChange:d}),a)};h();let y=()=>{u.end()};return window.addEventListener("beforeunload",y),{agent:u,open:()=>p?.(!0),close:()=>p?.(!1),toggle:()=>p?.(!f),update:E=>{r||(m={...m,...E},"accentColor"in E&&i(m.accentColor),h())},destroy:()=>{r||(r=!0,window.removeEventListener("beforeunload",y),u.end(),Un(null,a),n.remove())}}}return Fs(Vu);})();
220
+ .surg-powered a { color: inherit; font-weight: 500; text-decoration: none; }
221
+ .surg-powered a:hover { text-decoration: underline; }
222
+ `;var jt,X,Fn,ys,Wr=0,Is=[],z=U,Es=z.__b,bs=z.__r,Ss=z.diffed,xs=z.__c,Ts=z.unmount,ws=z.__;function Vn(t,e){z.__h&&z.__h(X,t,Wr||e),Wr=0;var r=X.__H||(X.__H={__:[],__h:[]});return t>=r.__.length&&r.__.push({}),r.__[t]}function it(t){return Wr=1,ku(Cs,t)}function ku(t,e,r){var n=Vn(jt++,2);if(n.t=t,!n.__c&&(n.__=[r?r(e):Cs(void 0,e),function(i){var c=n.__N?n.__N[0]:n.__[0],u=n.t(c,i);c!==u&&(n.__N=[u,n.__[1]],n.__c.setState({}))}],n.__c=X,!X.__f)){var o=function(i,c,u){if(!n.__c.__H)return!0;var p=n.__c.__H.__.filter(function(v){return v.__c});if(p.every(function(v){return!v.__N}))return!s||s.call(this,i,c,u);var f=n.__c.props!==i;return p.some(function(v){if(v.__N){var d=v.__[0];v.__=v.__N,v.__N=void 0,d!==v.__[0]&&(f=!0)}}),s&&s.call(this,i,c,u)||f};X.__f=!0;var s=X.shouldComponentUpdate,a=X.componentWillUpdate;X.componentWillUpdate=function(i,c,u){if(this.__e){var p=s;s=void 0,o(i,c,u),s=p}a&&a.call(this,i,c,u)},X.shouldComponentUpdate=o}return n.__N||n.__}function Nt(t,e){var r=Vn(jt++,3);!z.__s&&Ns(r.__H,e)&&(r.__=t,r.u=e,X.__H.__h.push(r))}function $n(t){return Wr=5,Ru(function(){return{current:t}},[])}function Ru(t,e){var r=Vn(jt++,7);return Ns(r.__H,e)&&(r.__=t(),r.__H=e,r.__h=t),r.__}function Ou(){for(var t;t=Is.shift();){var e=t.__H;if(t.__P&&e)try{e.__h.some(Br),e.__h.some(Hn),e.__h=[]}catch(r){e.__h=[],z.__e(r,t.__v)}}}z.__b=function(t){X=null,Es&&Es(t)},z.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),ws&&ws(t,e)},z.__r=function(t){bs&&bs(t),jt=0;var e=(X=t.__c).__H;e&&(Fn===X?(e.__h=[],X.__h=[],e.__.some(function(r){r.__N&&(r.__=r.__N),r.u=r.__N=void 0})):(e.__h.some(Br),e.__h.some(Hn),e.__h=[],jt=0)),Fn=X},z.diffed=function(t){Ss&&Ss(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Is.push(e)!==1&&ys===z.requestAnimationFrame||((ys=z.requestAnimationFrame)||Pu)(Ou)),e.__H.__.some(function(r){r.u&&(r.__H=r.u),r.u=void 0})),Fn=X=null},z.__c=function(t,e){e.some(function(r){try{r.__h.some(Br),r.__h=r.__h.filter(function(n){return!n.__||Hn(n)})}catch(n){e.some(function(o){o.__h&&(o.__h=[])}),e=[],z.__e(n,r.__v)}}),xs&&xs(t,e)},z.unmount=function(t){Ts&&Ts(t);var e,r=t.__c;r&&r.__H&&(r.__H.__.some(function(n){try{Br(n)}catch(o){e=o}}),r.__H=void 0,e&&z.__e(e,r.__v))};var As=typeof requestAnimationFrame=="function";function Pu(t){var e,r=function(){clearTimeout(n),As&&cancelAnimationFrame(e),setTimeout(t)},n=setTimeout(r,35);As&&(e=requestAnimationFrame(r))}function Br(t){var e=X,r=t.__c;typeof r=="function"&&(t.__c=void 0,r()),X=e}function Hn(t){var e=X;t.__c=t.__(),X=e}function Ns(t,e){return!t||t.length!==e.length||e.some(function(r,n){return r!==t[n]})}function Cs(t,e){return typeof e=="function"?e(t):e}var Mu={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function jn(t){return t.replace(/[&<>"']/g,e=>Mu[e]??e)}function Lu(t){let e=t.trim();if(/^(https?:|mailto:)/i.test(e))return e}function ks(t){let e=t;return e=e.replace(/`([^`]+)`/g,(r,n)=>`<code>${n}</code>`),e=e.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(r,n,o)=>{let s=Lu(o);return s?`<a href="${s}" target="_blank" rel="noopener noreferrer">${n}</a>`:`${n}`}),e=e.replace(/\*\*([^*]+)\*\*/g,(r,n)=>`<strong>${n}</strong>`),e=e.replace(/(^|[^*])\*([^*\n]+)\*/g,(r,n,o)=>`${n}<em>${o}</em>`),e}function Bn(t){let e=t.split(/```/),r=[];return e.forEach((n,o)=>{if(o%2===1){let i=n.replace(/^[^\n]*\n/,c=>n.includes(`
223
+ `)?"":c);r.push(`<pre><code>${jn(i.replace(/\n$/,""))}</code></pre>`);return}let a=n.split(/\n{2,}/);for(let i of a){let c=i.split(`
224
+ `).filter(v=>v.trim().length>0);if(c.length===0)continue;let u=c.every(v=>/^\s*[-*]\s+/.test(v)),p=c.every(v=>/^\s*\d+\.\s+/.test(v));if(u||p){let v=c.map(d=>d.replace(/^\s*(?:[-*]|\d+\.)\s+/,"")).map(d=>`<li>${ks(jn(d))}</li>`).join("");r.push(p?`<ol>${v}</ol>`:`<ul>${v}</ul>`);continue}let f=c.map(v=>ks(jn(v))).join("<br>");r.push(`<p>${f}</p>`)}}),r.join("")}var Du=/<next_action([^>]*)>([\s\S]*?)<\/next_action>\s*/gi,Uu=/(?:^|\n)\s*<(?:n(?:e(?:x(?:t(?:_(?:a(?:c(?:t(?:i(?:o(?:n[\s\S]*)?)?)?)?)?)?)?)?)?)?)?$/i;function Rs(t){if(!t)return t;let e=t.replace(Du,"").trimEnd(),r=Uu.exec(e);return r?e.slice(0,r.index).trimEnd():e}var Gu=0;function O(t,e,r,n,o,s){e||(e={});var a,i,c=e;if("ref"in c)for(i in c={},e)i=="ref"?a=e[i]:c[i]=e[i];var u={type:t,props:c,key:r,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Gu,__i:-1,__u:0,__source:o,__self:s};if(typeof t=="function"&&(a=t.defaultProps))for(i in a)c[i]===void 0&&(c[i]=a[i]);return U.vnode&&U.vnode(u),u}var Fu="Typically replies instantly",Hu="Hi! \u{1F44B} How can I help you today?";function Ps(){return`u-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`}function Wn(t){let e=[];for(let r of t){if(r.role!=="user"&&r.role!=="assistant")continue;let n=typeof r.content=="string"?r.content:"";e.push({id:r.id??Ps(),role:r.role,content:n})}return e}function Os(t){if(t instanceof ce)return"This chat isn\u2019t accepting messages from this site yet. The site owner needs to allow this origin.";if(t instanceof Me)return"You\u2019re sending messages too quickly. Please wait a moment and try again.";if(t&&typeof t=="object"){let e=t.code;if(e==="auth")return"This chat isn\u2019t accepting messages from this site yet. The site owner needs to allow this origin.";if(e==="sse_closed")return"Connection lost. Please send your message again.";let r=t.message;if(r&&r.length<160)return r}return"Something went wrong. Please try again."}var Vu=O("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:O("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})}),$u=O("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[O("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),O("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),ju=O("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[O("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),O("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]});function Ms({agent:t,config:e,registerOpenControl:r,onOpenChange:n}){let o=!!e.inline,[s,a]=it(o||!!e.openByDefault),[i,c]=it(()=>Wn(t.messages)),[u,p]=it(!1),[f,v]=it(null),[d,m]=it(""),[h,y]=it(""),E=e.title||h||"Assistant",_=$n(null),I=$n(!1);Nt(()=>r(a),[r]),Nt(()=>n?.(s),[s,n]),Nt(()=>{let G=t.subscribe({onMessagesChanged:()=>c(Wn(t.messages)),onRunStartedEvent:()=>{p(!0),v(null)},onRunFinishedEvent:()=>p(!1),onRunErrorEvent:({event:Gs})=>{p(!1),v(Os(Gs))}});return()=>G.unsubscribe()},[t]),Nt(()=>{!s||I.current||(I.current=!0,t.ensureBootstrapped().then(G=>{G.agentName&&y(G.agentName)}).catch(G=>{I.current=!1,v(Os(G))}))},[s,t]),Nt(()=>{let G=_.current;G&&(G.scrollTop=G.scrollHeight)},[i,u]);let $=()=>{let G=d.trim();!G||u||(m(""),t.addMessage({id:Ps(),role:"user",content:G}),c(Wn(t.messages)),t.runAgent().catch(()=>{}))},Z=G=>{G.key==="Enter"&&!G.shiftKey&&(G.preventDefault(),$())},Ue=e.subtitle??Fu,pe=e.welcomeMessage??Hu,Ct=i.some(G=>G.role==="assistant"),se=!!pe&&!Ct,Ae=u&&i[i.length-1]?.role!=="assistant";if(!o&&!s)return O("button",{type:"button",class:`surg-launcher surg-pos-${e.position??"bottom-right"}`,"aria-label":"Open chat",onClick:()=>a(!0),children:e.logoUrl?O("img",{class:"surg-launcher-logo",src:e.logoUrl,alt:""}):Vu});let Us=o?"surg-panel surg-inline":`surg-panel surg-pos-${e.position??"bottom-right"}`;return O("div",{class:Us,role:"dialog","aria-label":E,children:[O("div",{class:"surg-header",children:[O("div",{class:"surg-header-id",children:[e.logoUrl&&O("img",{class:"surg-logo",src:e.logoUrl,alt:""}),O("div",{class:"surg-header-text",children:[O("span",{class:"surg-title",children:E}),Ue&&O("span",{class:"surg-subtitle",children:Ue})]})]}),!o&&O("button",{type:"button",class:"surg-close","aria-label":"Close chat",onClick:()=>a(!1),children:$u})]}),O("div",{class:"surg-messages",ref:_,children:[se&&O("div",{class:"surg-bubble surg-assistant",dangerouslySetInnerHTML:{__html:Bn(pe)}}),i.map(G=>G.role==="assistant"?O("div",{class:"surg-bubble surg-assistant",dangerouslySetInnerHTML:{__html:Bn(Rs(G.content))}},G.id):O("div",{class:"surg-bubble surg-user",children:G.content},G.id)),Ae&&O("div",{class:"surg-bubble surg-assistant surg-typing",children:[O("span",{}),O("span",{}),O("span",{})]})]}),f&&O("div",{class:"surg-error",children:f}),O("div",{class:"surg-composer",children:[O("textarea",{class:"surg-input",rows:1,placeholder:"Type a message\u2026",value:d,disabled:u,onInput:G=>m(G.target.value),onKeyDown:Z}),O("button",{type:"button",class:"surg-send","aria-label":"Send",disabled:u||!d.trim(),onClick:$,children:ju})]}),O("div",{class:"surg-powered",children:["Powered by"," ",O("a",{href:"https://surogate.ai/",target:"_blank",rel:"noopener noreferrer",children:"Surogate"})]})]})}var Ls="#4f46e5";function Bu(t){let e=t.replace("#",""),r=e.length===3?e.split("").map(i=>i+i).join(""):e;if(r.length!==6||/[^0-9a-f]/i.test(r))return"#ffffff";let n=parseInt(r.slice(0,2),16),o=parseInt(r.slice(2,4),16),s=parseInt(r.slice(4,6),16);return(.299*n+.587*o+.114*s)/255>.62?"#0f172a":"#ffffff"}async function Ds(t){if(t?.apiUrl)return Xr(t);if(!t?.publishableKey)throw new Error('SurogatesWidget.mountWithPairing: "publishableKey" is required.');let{agentId:e,apiWebUrl:r}=await Qo(t.pairingUrl??Jo,t.publishableKey);return Xr({...t,apiUrl:r,agentId:e})}function Xr(t){if(!t||!t.apiUrl||!t.publishableKey)throw new Error('SurogatesWidget.mount: "apiUrl" and "publishableKey" are required.');let e=t.accentColor??Ls,r=!1,n=document.createElement("div");n.setAttribute("data-surogates-widget","");let o=n.attachShadow({mode:"open"}),s=document.createElement("style");s.textContent=vs,o.appendChild(s);let a=document.createElement("div");a.className="surg-root",o.appendChild(a);let i=E=>{let _=E??Ls;a.style.setProperty("--surg-accent",_),a.style.setProperty("--surg-accent-fg",Bu(_))};i(e);let c=()=>(t.target??document.body)?.appendChild(n);t.target||document.body?c():document.addEventListener("DOMContentLoaded",()=>{r||c()},{once:!0});let u=new wt(t),p,f=t.inline||!!t.openByDefault,v=E=>{p=E},d=E=>{f=E},m=t,h=()=>{Gn(O(Ms,{agent:u,config:m,registerOpenControl:v,onOpenChange:d}),a)};h();let y=()=>{u.end()};return window.addEventListener("beforeunload",y),{agent:u,open:()=>p?.(!0),close:()=>p?.(!1),toggle:()=>p?.(!f),update:E=>{r||(m={...m,...E},"accentColor"in E&&i(m.accentColor),h())},destroy:()=>{r||(r=!0,window.removeEventListener("beforeunload",y),u.end(),Gn(null,a),n.remove())}}}return js(Wu);})();
222
225
  /*! Bundled license information:
223
226
 
224
227
  fast-json-patch/module/helpers.mjs: