@mcp-use/inspector 0.13.0-canary.8 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +2 -2
- package/dist/client/assets/{browser-C25bUfYp.js → browser-I_PMdsM0.js} +142 -142
- package/dist/client/assets/{display-A5IEINAP-ByZ9IIJl.js → display-A5IEINAP-5VPyRE5O.js} +2 -2
- package/dist/client/assets/embeddings-BNrmfKFy.js +1 -0
- package/dist/client/assets/fs-u42MReIY.js +1 -0
- package/dist/client/assets/index-BSdThYb2.js +7 -0
- package/dist/client/assets/index-BeJAljgp.js +1676 -0
- package/dist/client/assets/index-C5URJhI3.js +33 -0
- package/dist/client/assets/index-C74O6YE7.js +49 -0
- package/dist/client/assets/index-C8I8qFXo.js +80 -0
- package/dist/client/assets/index-CGBDt1uT.js +71 -0
- package/dist/client/assets/{index-DTt5KCEV.js → index-CJtjIp1D.js} +1 -1
- package/dist/client/assets/index-DQ7i0BFM.css +1 -0
- package/dist/client/assets/index-VuReKekR.js +40 -0
- package/dist/client/assets/{index-BRrjjTR6.js → index-rCIx5_U5.js} +2 -2
- package/dist/client/assets/llms-Bhs98QIx.js +2 -0
- package/dist/client/assets/module-D4IOASh4.js +4 -0
- package/dist/client/assets/path-B4EKd5uv.js +1 -0
- package/dist/client/assets/{winston-7dQlPZMw.js → winston-CO4zA-JC.js} +24 -24
- package/dist/client/index.html +3 -3
- package/dist/server/{chunk-OS2WTNLR.js → chunk-JEKCWLHD.js} +1 -1
- package/dist/server/{chunk-Z5QIR3IS.js → chunk-MCMZDGO6.js} +2 -2
- package/dist/server/{chunk-WLIY2SQG.js → chunk-XGILHZOF.js} +1 -1
- package/dist/server/cli.js +2 -2
- package/dist/server/index.js +3 -3
- package/dist/server/middleware.js +3 -3
- package/dist/server/server.js +2 -2
- package/dist/server/shared-routes.js +2 -2
- package/dist/server/shared-utils-browser.d.ts.map +1 -1
- package/dist/server/shared-utils-browser.js +1 -1
- package/package.json +29 -33
- package/dist/client/assets/embeddings-CgzAByVu.js +0 -1
- package/dist/client/assets/index-9hzrT5HP.js +0 -7
- package/dist/client/assets/index-CEBAtJQV.js +0 -33
- package/dist/client/assets/index-DPEqrSDR.js +0 -80
- package/dist/client/assets/index-Ddy9yyxP.js +0 -71
- package/dist/client/assets/index-Dq7UrqnC.js +0 -25
- package/dist/client/assets/index-FyLdp58J.js +0 -1707
- package/dist/client/assets/index-VOipG1yN.js +0 -8
- package/dist/client/assets/index-beDRbW3x.css +0 -1
- package/dist/client/assets/langfuse-74RGPTAH-ThX8caF_.js +0 -1
- package/dist/client/assets/module-DXhXtM9n.js +0 -4
- package/dist/client/assets/path-C8e-fwNk.js +0 -1
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import{c as gn,v as Pe,w as uc,x as nt,y as il,$ as ol,z as lc,m as ls,A as cl,B as ul,C as ll,D as dl,k as Xs}from"./index-BeJAljgp.js";var te;(function(t){t.assertEqual=a=>{};function e(a){}t.assertIs=e;function r(a){throw new Error}t.assertNever=r,t.arrayToEnum=a=>{const s={};for(const i of a)s[i]=i;return s},t.getValidEnumValues=a=>{const s=t.objectKeys(a).filter(o=>typeof a[a[o]]!="number"),i={};for(const o of s)i[o]=a[o];return t.objectValues(i)},t.objectValues=a=>t.objectKeys(a).map(function(s){return a[s]}),t.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{const s=[];for(const i in a)Object.prototype.hasOwnProperty.call(a,i)&&s.push(i);return s},t.find=(a,s)=>{for(const i of a)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function n(a,s=" | "){return a.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(a,s)=>typeof s=="bigint"?s.toString():s})(te||(te={}));var ei;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(ei||(ei={}));const O=te.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),pt=t=>{switch(typeof t){case"undefined":return O.undefined;case"string":return O.string;case"number":return Number.isNaN(t)?O.nan:O.number;case"boolean":return O.boolean;case"function":return O.function;case"bigint":return O.bigint;case"symbol":return O.symbol;case"object":return Array.isArray(t)?O.array:t===null?O.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?O.promise:typeof Map<"u"&&t instanceof Map?O.map:typeof Set<"u"&&t instanceof Set?O.set:typeof Date<"u"&&t instanceof Date?O.date:O.object;default:return O.unknown}},w=te.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"]);class Me 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]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(s){return s.message},n={_errors:[]},a=s=>{for(const i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(a);else if(i.code==="invalid_return_type")a(i.returnTypeError);else if(i.code==="invalid_arguments")a(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let o=n,c=0;for(;c<i.path.length;){const u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(r(i))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return a(this),n}static assert(e){if(!(e instanceof Me))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,te.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r=Object.create(null),n=[];for(const a of this.issues)if(a.path.length>0){const s=a.path[0];r[s]=r[s]||[],r[s].push(e(a))}else n.push(e(a));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}Me.create=t=>new Me(t);const dr=(t,e)=>{let r;switch(t.code){case w.invalid_type:t.received===O.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case w.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,te.jsonStringifyReplacer)}`;break;case w.unrecognized_keys:r=`Unrecognized key(s) in object: ${te.joinValues(t.keys,", ")}`;break;case w.invalid_union:r="Invalid input";break;case w.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${te.joinValues(t.options)}`;break;case w.invalid_enum_value:r=`Invalid enum value. Expected ${te.joinValues(t.options)}, received '${t.received}'`;break;case w.invalid_arguments:r="Invalid function arguments";break;case w.invalid_return_type:r="Invalid function return type";break;case w.invalid_date:r="Invalid date";break;case w.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}"`:te.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case w.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 w.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 w.custom:r="Invalid input";break;case w.invalid_intersection_types:r="Intersection results could not be merged";break;case w.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case w.not_finite:r="Number must be finite";break;default:r=e.defaultError,te.assertNever(t)}return{message:r}};let fl=dr;function Fa(){return fl}const Ba=t=>{const{data:e,path:r,errorMaps:n,issueData:a}=t,s=[...r,...a.path||[]],i={...a,path:s};if(a.message!==void 0)return{...a,path:s,message:a.message};let o="";const c=n.filter(u=>!!u).slice().reverse();for(const u of c)o=u(i,{data:e,defaultError:o}).message;return{...a,path:s,message:o}};function x(t,e){const r=Fa(),n=Ba({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===dr?void 0:dr].filter(a=>!!a)});t.common.issues.push(n)}class Te{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const a of r){if(a.status==="aborted")return V;a.status==="dirty"&&e.dirty(),n.push(a.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const a of r){const s=await a.key,i=await a.value;n.push({key:s,value:i})}return Te.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const a of r){const{key:s,value:i}=a;if(s.status==="aborted"||i.status==="aborted")return V;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||a.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}}const V=Object.freeze({status:"aborted"}),nr=t=>({status:"dirty",value:t}),ke=t=>({status:"valid",value:t}),ti=t=>t.status==="aborted",ri=t=>t.status==="dirty",Gt=t=>t.status==="valid",Xr=t=>typeof Promise<"u"&&t instanceof Promise;var N;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(N||(N={}));class Qe{constructor(e,r,n,a){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=a}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}}const ni=(t,e)=>{if(Gt(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;const r=new Me(t.common.issues);return this._error=r,this._error}}};function Q(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:a}=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:a}:{errorMap:(i,o)=>{const{message:c}=t;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:a}}class ee{get description(){return this._def.description}_getType(e){return pt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Te,ctx:{common:e.parent.common,data:e.data,parsedType:pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(Xr(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pt(e)},a=this._parseSync({data:e,path:n.path,parent:n});return ni(n,a)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pt(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return Gt(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=>Gt(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pt(e)},a=this._parse({data:e,path:n.path,parent:n}),s=await(Xr(a)?a:Promise.resolve(a));return ni(n,s)}refine(e,r){const n=a=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(a):r;return this._refinement((a,s)=>{const i=e(a),o=()=>s.addIssue({code:w.custom,...n(a)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,a)=>e(n)?!0:(a.addIssue(typeof r=="function"?r(n,a):r),!1))}_refinement(e){return new Vt({schema:this,typeName:b.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 yt.create(this,this._def)}nullable(){return Wt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ke.create(this)}promise(){return mr.create(this,this._def)}or(e){return tn.create([this,e],this._def)}and(e){return rn.create(this,e,this._def)}transform(e){return new Vt({...Q(this._def),schema:this,typeName:b.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new Za({...Q(this._def),innerType:this,defaultValue:r,typeName:b.ZodDefault})}brand(){return new Ll({typeName:b.ZodBranded,type:this,...Q(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new Va({...Q(this._def),innerType:this,catchValue:r,typeName:b.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return ds.create(this,e)}readonly(){return Wa.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const hl=/^c[^\s-]{8,}$/i,pl=/^[0-9a-z]+$/,ml=/^[0-9A-HJKMNP-TV-Z]{26}$/i,gl=/^[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,yl=/^[a-z0-9_-]{21}$/i,_l=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,vl=/^[-+]?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)?)??$/,wl=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,bl="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let An;const El=/^(?:(?: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])$/,Sl=/^(?:(?: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])$/,Tl=/^(([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]))$/,xl=/^(([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])$/,Il=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Al=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dc="((\\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])))",$l=new RegExp(`^${dc}$`);function fc(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Rl(t){return new RegExp(`^${fc(t)}$`)}function Ol(t){let e=`${dc}T${fc(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function kl(t,e){return!!((e==="v4"||!e)&&El.test(t)||(e==="v6"||!e)&&Tl.test(t))}function Cl(t,e){if(!_l.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),a=JSON.parse(atob(n));return!(typeof a!="object"||a===null||"typ"in a&&a?.typ!=="JWT"||!a.alg||e&&a.alg!==e)}catch{return!1}}function Nl(t,e){return!!((e==="v4"||!e)&&Sl.test(t)||(e==="v6"||!e)&&xl.test(t))}class at extends ee{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==O.string){const s=this._getOrReturnCtx(e);return x(s,{code:w.invalid_type,expected:O.string,received:s.parsedType}),V}const n=new Te;let a;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(a=this._getOrReturnCtx(e,a),x(a,{code:w.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&&(a=this._getOrReturnCtx(e,a),x(a,{code:w.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){const i=e.data.length>s.value,o=e.data.length<s.value;(i||o)&&(a=this._getOrReturnCtx(e,a),i?x(a,{code:w.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&x(a,{code:w.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")wl.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"email",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")An||(An=new RegExp(bl,"u")),An.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"emoji",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")gl.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"uuid",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")yl.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"nanoid",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")hl.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"cuid",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")pl.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"cuid2",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")ml.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"ulid",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{a=this._getOrReturnCtx(e,a),x(a,{validation:"url",code:w.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"regex",code:w.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)||(a=this._getOrReturnCtx(e,a),x(a,{code:w.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)||(a=this._getOrReturnCtx(e,a),x(a,{code:w.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(a=this._getOrReturnCtx(e,a),x(a,{code:w.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Ol(s).test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{code:w.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?$l.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{code:w.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Rl(s).test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{code:w.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?vl.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"duration",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?kl(e.data,s.version)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"ip",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?Cl(e.data,s.alg)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"jwt",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Nl(e.data,s.version)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"cidr",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?Il.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"base64",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?Al.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"base64url",code:w.invalid_string,message:s.message}),n.dirty()):te.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(a=>e.test(a),{validation:r,code:w.invalid_string,...N.errToObj(n)})}_addCheck(e){return new at({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...N.errToObj(e)})}url(e){return this._addCheck({kind:"url",...N.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...N.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...N.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...N.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...N.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...N.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...N.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...N.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...N.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...N.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...N.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...N.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,...N.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,...N.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...N.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...N.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...N.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...N.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...N.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...N.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...N.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...N.errToObj(r)})}nonempty(e){return this.min(1,N.errToObj(e))}trim(){return new at({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new at({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new at({...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(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}at.create=t=>new at({checks:[],typeName:b.ZodString,coerce:t?.coerce??!1,...Q(t)});function Pl(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,a=r>n?r:n,s=Number.parseInt(t.toFixed(a).replace(".","")),i=Number.parseInt(e.toFixed(a).replace(".",""));return s%i/10**a}class Ht extends ee{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)!==O.number){const s=this._getOrReturnCtx(e);return x(s,{code:w.invalid_type,expected:O.number,received:s.parsedType}),V}let n;const a=new Te;for(const s of this._def.checks)s.kind==="int"?te.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{code:w.invalid_type,expected:"integer",received:"float",message:s.message}),a.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),x(n,{code:w.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),x(n,{code:w.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty()):s.kind==="multipleOf"?Pl(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),x(n,{code:w.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{code:w.not_finite,message:s.message}),a.dirty()):te.assertNever(s);return{status:a.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,N.toString(r))}gt(e,r){return this.setLimit("min",e,!1,N.toString(r))}lte(e,r){return this.setLimit("max",e,!0,N.toString(r))}lt(e,r){return this.setLimit("max",e,!1,N.toString(r))}setLimit(e,r,n,a){return new Ht({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:N.toString(a)}]})}_addCheck(e){return new Ht({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:N.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:N.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const 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"&&te.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const 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)}}Ht.create=t=>new Ht({checks:[],typeName:b.ZodNumber,coerce:t?.coerce||!1,...Q(t)});class fr extends ee{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)!==O.bigint)return this._getInvalidInput(e);let n;const a=new Te;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),x(n,{code:w.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),x(n,{code:w.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),x(n,{code:w.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):te.assertNever(s);return{status:a.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return x(r,{code:w.invalid_type,expected:O.bigint,received:r.parsedType}),V}gte(e,r){return this.setLimit("min",e,!0,N.toString(r))}gt(e,r){return this.setLimit("min",e,!1,N.toString(r))}lte(e,r){return this.setLimit("max",e,!0,N.toString(r))}lt(e,r){return this.setLimit("max",e,!1,N.toString(r))}setLimit(e,r,n,a){return new fr({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:N.toString(a)}]})}_addCheck(e){return new fr({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}fr.create=t=>new fr({checks:[],typeName:b.ZodBigInt,coerce:t?.coerce??!1,...Q(t)});class za extends ee{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==O.boolean){const n=this._getOrReturnCtx(e);return x(n,{code:w.invalid_type,expected:O.boolean,received:n.parsedType}),V}return ke(e.data)}}za.create=t=>new za({typeName:b.ZodBoolean,coerce:t?.coerce||!1,...Q(t)});class en extends ee{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==O.date){const s=this._getOrReturnCtx(e);return x(s,{code:w.invalid_type,expected:O.date,received:s.parsedType}),V}if(Number.isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return x(s,{code:w.invalid_date}),V}const n=new Te;let a;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(a=this._getOrReturnCtx(e,a),x(a,{code:w.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(a=this._getOrReturnCtx(e,a),x(a,{code:w.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):te.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new en({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:N.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:N.toString(r)})}get minDate(){let e=null;for(const 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(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}en.create=t=>new en({checks:[],coerce:t?.coerce||!1,typeName:b.ZodDate,...Q(t)});class ai extends ee{_parse(e){if(this._getType(e)!==O.symbol){const n=this._getOrReturnCtx(e);return x(n,{code:w.invalid_type,expected:O.symbol,received:n.parsedType}),V}return ke(e.data)}}ai.create=t=>new ai({typeName:b.ZodSymbol,...Q(t)});class qa extends ee{_parse(e){if(this._getType(e)!==O.undefined){const n=this._getOrReturnCtx(e);return x(n,{code:w.invalid_type,expected:O.undefined,received:n.parsedType}),V}return ke(e.data)}}qa.create=t=>new qa({typeName:b.ZodUndefined,...Q(t)});class si extends ee{_parse(e){if(this._getType(e)!==O.null){const n=this._getOrReturnCtx(e);return x(n,{code:w.invalid_type,expected:O.null,received:n.parsedType}),V}return ke(e.data)}}si.create=t=>new si({typeName:b.ZodNull,...Q(t)});class hr extends ee{constructor(){super(...arguments),this._any=!0}_parse(e){return ke(e.data)}}hr.create=t=>new hr({typeName:b.ZodAny,...Q(t)});class zt extends ee{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ke(e.data)}}zt.create=t=>new zt({typeName:b.ZodUnknown,...Q(t)});class vt extends ee{_parse(e){const r=this._getOrReturnCtx(e);return x(r,{code:w.invalid_type,expected:O.never,received:r.parsedType}),V}}vt.create=t=>new vt({typeName:b.ZodNever,...Q(t)});class ii extends ee{_parse(e){if(this._getType(e)!==O.undefined){const n=this._getOrReturnCtx(e);return x(n,{code:w.invalid_type,expected:O.void,received:n.parsedType}),V}return ke(e.data)}}ii.create=t=>new ii({typeName:b.ZodVoid,...Q(t)});class Ke extends ee{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),a=this._def;if(r.parsedType!==O.array)return x(r,{code:w.invalid_type,expected:O.array,received:r.parsedType}),V;if(a.exactLength!==null){const i=r.data.length>a.exactLength.value,o=r.data.length<a.exactLength.value;(i||o)&&(x(r,{code:i?w.too_big:w.too_small,minimum:o?a.exactLength.value:void 0,maximum:i?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),n.dirty())}if(a.minLength!==null&&r.data.length<a.minLength.value&&(x(r,{code:w.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),n.dirty()),a.maxLength!==null&&r.data.length>a.maxLength.value&&(x(r,{code:w.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,o)=>a.type._parseAsync(new Qe(r,i,r.path,o)))).then(i=>Te.mergeArray(n,i));const s=[...r.data].map((i,o)=>a.type._parseSync(new Qe(r,i,r.path,o)));return Te.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new Ke({...this._def,minLength:{value:e,message:N.toString(r)}})}max(e,r){return new Ke({...this._def,maxLength:{value:e,message:N.toString(r)}})}length(e,r){return new Ke({...this._def,exactLength:{value:e,message:N.toString(r)}})}nonempty(e){return this.min(1,e)}}Ke.create=(t,e)=>new Ke({type:t,minLength:null,maxLength:null,exactLength:null,typeName:b.ZodArray,...Q(e)});function Dt(t){if(t instanceof de){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=yt.create(Dt(n))}return new de({...t._def,shape:()=>e})}else return t instanceof Ke?new Ke({...t._def,type:Dt(t.element)}):t instanceof yt?yt.create(Dt(t.unwrap())):t instanceof Wt?Wt.create(Dt(t.unwrap())):t instanceof ot?ot.create(t.items.map(e=>Dt(e))):t}class de extends ee{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=te.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==O.object){const u=this._getOrReturnCtx(e);return x(u,{code:w.invalid_type,expected:O.object,received:u.parsedType}),V}const{status:n,ctx:a}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof vt&&this._def.unknownKeys==="strip"))for(const u in a.data)i.includes(u)||o.push(u);const c=[];for(const u of i){const l=s[u],d=a.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Qe(a,d,a.path,u)),alwaysSet:u in a.data})}if(this._def.catchall instanceof vt){const u=this._def.unknownKeys;if(u==="passthrough")for(const l of o)c.push({key:{status:"valid",value:l},value:{status:"valid",value:a.data[l]}});else if(u==="strict")o.length>0&&(x(a,{code:w.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const l of o){const d=a.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Qe(a,d,a.path,l)),alwaysSet:l in a.data})}}return a.common.async?Promise.resolve().then(async()=>{const u=[];for(const l of c){const d=await l.key,f=await l.value;u.push({key:d,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>Te.mergeObjectSync(n,u)):Te.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return N.errToObj,new de({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{const a=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:N.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new de({...this._def,unknownKeys:"strip"})}passthrough(){return new de({...this._def,unknownKeys:"passthrough"})}extend(e){return new de({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new de({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:b.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new de({...this._def,catchall:e})}pick(e){const r={};for(const n of te.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new de({...this._def,shape:()=>r})}omit(e){const r={};for(const n of te.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new de({...this._def,shape:()=>r})}deepPartial(){return Dt(this)}partial(e){const r={};for(const n of te.objectKeys(this.shape)){const a=this.shape[n];e&&!e[n]?r[n]=a:r[n]=a.optional()}return new de({...this._def,shape:()=>r})}required(e){const r={};for(const n of te.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof yt;)s=s._def.innerType;r[n]=s}return new de({...this._def,shape:()=>r})}keyof(){return hc(te.objectKeys(this.shape))}}de.create=(t,e)=>new de({shape:()=>t,unknownKeys:"strip",catchall:vt.create(),typeName:b.ZodObject,...Q(e)});de.strictCreate=(t,e)=>new de({shape:()=>t,unknownKeys:"strict",catchall:vt.create(),typeName:b.ZodObject,...Q(e)});de.lazycreate=(t,e)=>new de({shape:t,unknownKeys:"strip",catchall:vt.create(),typeName:b.ZodObject,...Q(e)});class tn extends ee{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function a(s){for(const o of s)if(o.result.status==="valid")return o.result;for(const o of s)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;const i=s.map(o=>new Me(o.ctx.common.issues));return x(r,{code:w.invalid_union,unionErrors:i}),V}if(r.common.async)return Promise.all(n.map(async s=>{const i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(a);{let s;const i=[];for(const c of n){const u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const o=i.map(c=>new Me(c));return x(r,{code:w.invalid_union,unionErrors:o}),V}}get options(){return this._def.options}}tn.create=(t,e)=>new tn({options:t,typeName:b.ZodUnion,...Q(e)});function Ga(t,e){const r=pt(t),n=pt(e);if(t===e)return{valid:!0,data:t};if(r===O.object&&n===O.object){const a=te.objectKeys(e),s=te.objectKeys(t).filter(o=>a.indexOf(o)!==-1),i={...t,...e};for(const o of s){const c=Ga(t[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(r===O.array&&n===O.array){if(t.length!==e.length)return{valid:!1};const a=[];for(let s=0;s<t.length;s++){const i=t[s],o=e[s],c=Ga(i,o);if(!c.valid)return{valid:!1};a.push(c.data)}return{valid:!0,data:a}}else return r===O.date&&n===O.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class rn extends ee{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),a=(s,i)=>{if(ti(s)||ti(i))return V;const o=Ga(s.value,i.value);return o.valid?((ri(s)||ri(i))&&r.dirty(),{status:r.value,value:o.data}):(x(n,{code:w.invalid_intersection_types}),V)};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,i])=>a(s,i)):a(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}rn.create=(t,e,r)=>new rn({left:t,right:e,typeName:b.ZodIntersection,...Q(r)});class ot extends ee{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.array)return x(n,{code:w.invalid_type,expected:O.array,received:n.parsedType}),V;if(n.data.length<this._def.items.length)return x(n,{code:w.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),V;!this._def.rest&&n.data.length>this._def.items.length&&(x(n,{code:w.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...n.data].map((i,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new Qe(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Te.mergeArray(r,i)):Te.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new ot({...this._def,rest:e})}}ot.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ot({items:t,typeName:b.ZodTuple,rest:null,...Q(e)})};class nn extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.object)return x(n,{code:w.invalid_type,expected:O.object,received:n.parsedType}),V;const a=[],s=this._def.keyType,i=this._def.valueType;for(const o in n.data)a.push({key:s._parse(new Qe(n,o,n.path,o)),value:i._parse(new Qe(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?Te.mergeObjectAsync(r,a):Te.mergeObjectSync(r,a)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ee?new nn({keyType:e,valueType:r,typeName:b.ZodRecord,...Q(n)}):new nn({keyType:at.create(),valueType:e,typeName:b.ZodRecord,...Q(r)})}}class oi extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.map)return x(n,{code:w.invalid_type,expected:O.map,received:n.parsedType}),V;const a=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([o,c],u)=>({key:a._parse(new Qe(n,o,n.path,[u,"key"])),value:s._parse(new Qe(n,c,n.path,[u,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of i){const u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return V;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(u.value,l.value)}return{status:r.value,value:o}})}else{const o=new Map;for(const c of i){const u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return V;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(u.value,l.value)}return{status:r.value,value:o}}}}oi.create=(t,e,r)=>new oi({valueType:e,keyType:t,typeName:b.ZodMap,...Q(r)});class pr extends ee{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.set)return x(n,{code:w.invalid_type,expected:O.set,received:n.parsedType}),V;const a=this._def;a.minSize!==null&&n.data.size<a.minSize.value&&(x(n,{code:w.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),r.dirty()),a.maxSize!==null&&n.data.size>a.maxSize.value&&(x(n,{code:w.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),r.dirty());const s=this._def.valueType;function i(c){const u=new Set;for(const l of c){if(l.status==="aborted")return V;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}const o=[...n.data.values()].map((c,u)=>s._parse(new Qe(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,r){return new pr({...this._def,minSize:{value:e,message:N.toString(r)}})}max(e,r){return new pr({...this._def,maxSize:{value:e,message:N.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}pr.create=(t,e)=>new pr({valueType:t,minSize:null,maxSize:null,typeName:b.ZodSet,...Q(e)});class cr extends ee{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==O.function)return x(r,{code:w.invalid_type,expected:O.function,received:r.parsedType}),V;function n(o,c){return Ba({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Fa(),dr].filter(u=>!!u),issueData:{code:w.invalid_arguments,argumentsError:c}})}function a(o,c){return Ba({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Fa(),dr].filter(u=>!!u),issueData:{code:w.invalid_return_type,returnTypeError:c}})}const s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof mr){const o=this;return ke(async function(...c){const u=new Me([]),l=await o._def.args.parseAsync(c,s).catch(h=>{throw u.addIssue(n(c,h)),u}),d=await Reflect.apply(i,this,l);return await o._def.returns._def.type.parseAsync(d,s).catch(h=>{throw u.addIssue(a(d,h)),u})})}else{const o=this;return ke(function(...c){const u=o._def.args.safeParse(c,s);if(!u.success)throw new Me([n(c,u.error)]);const l=Reflect.apply(i,this,u.data),d=o._def.returns.safeParse(l,s);if(!d.success)throw new Me([a(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new cr({...this._def,args:ot.create(e).rest(zt.create())})}returns(e){return new cr({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new cr({args:e||ot.create([]).rest(zt.create()),returns:r||zt.create(),typeName:b.ZodFunction,...Q(n)})}}class ci extends ee{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}ci.create=(t,e)=>new ci({getter:t,typeName:b.ZodLazy,...Q(e)});class Ha extends ee{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return x(r,{received:r.data,code:w.invalid_literal,expected:this._def.value}),V}return{status:"valid",value:e.data}}get value(){return this._def.value}}Ha.create=(t,e)=>new Ha({value:t,typeName:b.ZodLiteral,...Q(e)});function hc(t,e){return new Zt({values:t,typeName:b.ZodEnum,...Q(e)})}class Zt extends ee{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return x(r,{expected:te.joinValues(n),received:r.parsedType,code:w.invalid_type}),V}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return x(r,{received:r.data,code:w.invalid_enum_value,options:n}),V}return ke(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return Zt.create(e,{...this._def,...r})}exclude(e,r=this._def){return Zt.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}Zt.create=hc;class ui extends ee{_parse(e){const r=te.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==O.string&&n.parsedType!==O.number){const a=te.objectValues(r);return x(n,{expected:te.joinValues(a),received:n.parsedType,code:w.invalid_type}),V}if(this._cache||(this._cache=new Set(te.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const a=te.objectValues(r);return x(n,{received:n.data,code:w.invalid_enum_value,options:a}),V}return ke(e.data)}get enum(){return this._def.values}}ui.create=(t,e)=>new ui({values:t,typeName:b.ZodNativeEnum,...Q(e)});class mr extends ee{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==O.promise&&r.common.async===!1)return x(r,{code:w.invalid_type,expected:O.promise,received:r.parsedType}),V;const n=r.parsedType===O.promise?r.data:Promise.resolve(r.data);return ke(n.then(a=>this._def.type.parseAsync(a,{path:r.path,errorMap:r.common.contextualErrorMap})))}}mr.create=(t,e)=>new mr({type:t,typeName:b.ZodPromise,...Q(e)});class Vt extends ee{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===b.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),a=this._def.effect||null,s={addIssue:i=>{x(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),a.type==="preprocess"){const i=a.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async o=>{if(r.value==="aborted")return V;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?V:c.status==="dirty"||r.value==="dirty"?nr(c.value):c});{if(r.value==="aborted")return V;const o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?V:o.status==="dirty"||r.value==="dirty"?nr(o.value):o}}if(a.type==="refinement"){const i=o=>{const c=a.refinement(o,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 o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?V:(o.status==="dirty"&&r.dirty(),i(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?V:(o.status==="dirty"&&r.dirty(),i(o.value).then(()=>({status:r.value,value:o.value}))))}if(a.type==="transform")if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Gt(i))return V;const o=a.transform(i.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Gt(i)?Promise.resolve(a.transform(i.value,s)).then(o=>({status:r.value,value:o})):V);te.assertNever(a)}}Vt.create=(t,e,r)=>new Vt({schema:t,typeName:b.ZodEffects,effect:e,...Q(r)});Vt.createWithPreprocess=(t,e,r)=>new Vt({schema:e,effect:{type:"preprocess",transform:t},typeName:b.ZodEffects,...Q(r)});class yt extends ee{_parse(e){return this._getType(e)===O.undefined?ke(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}yt.create=(t,e)=>new yt({innerType:t,typeName:b.ZodOptional,...Q(e)});class Wt extends ee{_parse(e){return this._getType(e)===O.null?ke(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Wt.create=(t,e)=>new Wt({innerType:t,typeName:b.ZodNullable,...Q(e)});class Za extends ee{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===O.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}Za.create=(t,e)=>new Za({innerType:t,typeName:b.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Q(e)});class Va extends ee{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},a=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Xr(a)?a.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Me(n.common.issues)},input:n.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Me(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Va.create=(t,e)=>new Va({innerType:t,typeName:b.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Q(e)});class li extends ee{_parse(e){if(this._getType(e)!==O.nan){const n=this._getOrReturnCtx(e);return x(n,{code:w.invalid_type,expected:O.nan,received:n.parsedType}),V}return{status:"valid",value:e.data}}}li.create=t=>new li({typeName:b.ZodNaN,...Q(t)});class Ll extends ee{_parse(e){const{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}}class ds extends ee{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?V:s.status==="dirty"?(r.dirty(),nr(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const a=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?V:a.status==="dirty"?(r.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:n.path,parent:n})}}static create(e,r){return new ds({in:e,out:r,typeName:b.ZodPipeline})}}class Wa extends ee{_parse(e){const r=this._def.innerType._parse(e),n=a=>(Gt(a)&&(a.value=Object.freeze(a.value)),a);return Xr(r)?r.then(a=>n(a)):n(r)}unwrap(){return this._def.innerType}}Wa.create=(t,e)=>new Wa({innerType:t,typeName:b.ZodReadonly,...Q(e)});function di(t,e){const r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Ml(t,e={},r){return t?hr.create().superRefine((n,a)=>{const s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){const o=di(e,n),c=o.fatal??r??!0;a.addIssue({code:"custom",...o,fatal:c})}});if(!s){const i=di(e,n),o=i.fatal??r??!0;a.addIssue({code:"custom",...i,fatal:o})}}):hr.create()}var b;(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"})(b||(b={}));const Gg=(t,e={message:`Input not instance of ${t.name}`})=>Ml(r=>r instanceof t,e),jl=at.create,Hg=Ht.create,Zg=za.create,Vg=qa.create,fi=hr.create;zt.create;vt.create;const Wg=Ke.create,Dl=de.create,Jg=tn.create;rn.create;ot.create;const Kg=nn.create,Yg=cr.create,Qg=Ha.create,Xg=Zt.create,ey=mr.create;yt.create;Wt.create;var Ul=Object.defineProperty,ge=(t,e)=>{for(var r in e)Ul(t,r,{get:e[r],enumerable:!0})};function ct(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}function fs(t){return ct(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function hs(t){return ct(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function pc(t){return ct(t)&&t.source_type==="text"&&"text"in t&&typeof t.text=="string"}function ps(t){return ct(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}function mc(t){if(ct(t)){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url}};if(t.source_type==="base64"){if(!t.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${t.mime_type};base64,${t.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function gc(t){const e=t.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${t}" - does not match type/subtype format.`);const r=e[0].trim(),n=e[1].trim();if(r===""||n==="")throw new Error(`Invalid mime type: "${t}" - type or subtype is empty.`);const a={};for(const s of t.split(";").slice(1)){const i=s.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${t}".`);const o=i[0].trim(),c=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${t}".`);a[o]=c}return{type:r,subtype:n,parameters:a}}function an({dataUrl:t,asTypedArray:e=!1}){const r=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let n;if(r){n=r[1].toLowerCase();const a=e?Uint8Array.from(atob(r[2]),s=>s.charCodeAt(0)):r[2];return{mime_type:n,data:a}}}function yc(t,e){if(t.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(t)}if(t.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(t)}if(t.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(t)}if(t.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(t)}throw new Error(`Unable to convert content block type '${t.type}' to provider-specific format: not recognized.`)}function ms(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}var $n,hi;function Fl(){return hi||(hi=1,$n=function(t,e){if(typeof t!="string")throw new TypeError("Expected a string");return e=typeof e>"u"?"_":e,t.replace(/([a-z\d])([A-Z])/g,"$1"+e+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+e+"$2").toLowerCase()}),$n}var Bl=Fl();const zl=gn(Bl);var Dr={exports:{}},pi;function ql(){if(pi)return Dr.exports;pi=1;const t=/[\p{Lu}]/u,e=/[\p{Ll}]/u,r=/^[\p{Lu}](?![\p{Lu}])/gu,n=/([\p{Alpha}\p{N}_]|$)/u,a=/[_.\- ]+/,s=new RegExp("^"+a.source),i=new RegExp(a.source+n.source,"gu"),o=new RegExp("\\d+"+n.source,"gu"),c=(f,h,p)=>{let m=!1,g=!1,y=!1;for(let v=0;v<f.length;v++){const _=f[v];m&&t.test(_)?(f=f.slice(0,v)+"-"+f.slice(v),m=!1,y=g,g=!0,v++):g&&y&&e.test(_)?(f=f.slice(0,v-1)+"-"+f.slice(v-1),y=g,g=!1,m=!0):(m=h(_)===_&&p(_)!==_,y=g,g=p(_)===_&&h(_)!==_)}return f},u=(f,h)=>(r.lastIndex=0,f.replace(r,p=>h(p))),l=(f,h)=>(i.lastIndex=0,o.lastIndex=0,f.replace(i,(p,m)=>h(m)).replace(o,p=>h(p))),d=(f,h)=>{if(!(typeof f=="string"||Array.isArray(f)))throw new TypeError("Expected the input to be `string | string[]`");if(h={pascalCase:!1,preserveConsecutiveUppercase:!1,...h},Array.isArray(f)?f=f.map(y=>y.trim()).filter(y=>y.length).join("-"):f=f.trim(),f.length===0)return"";const p=h.locale===!1?y=>y.toLowerCase():y=>y.toLocaleLowerCase(h.locale),m=h.locale===!1?y=>y.toUpperCase():y=>y.toLocaleUpperCase(h.locale);return f.length===1?h.pascalCase?m(f):p(f):(f!==p(f)&&(f=c(f,p,m)),f=f.replace(s,""),h.preserveConsecutiveUppercase?f=u(f,p):f=p(f),h.pascalCase&&(f=m(f.charAt(0))+f.slice(1)),l(f,m))};return Dr.exports=d,Dr.exports.default=d,Dr.exports}var Gl=ql();const Hl=gn(Gl);function Zl(t,e){return e?.[t]||zl(t)}function ty(t,e){return e?.[t]||Hl(t)}function Vl(t,e,r){const n={};for(const a in t)Object.hasOwn(t,a)&&(n[e(a,r)]=t[a]);return n}var Wl={};ge(Wl,{Serializable:()=>gr,get_lc_unique_name:()=>gs});function mi(t){return Array.isArray(t)?[...t]:{...t}}function Jl(t,e){const r=mi(t);for(const[n,a]of Object.entries(e)){const[s,...i]=n.split(".").reverse();let o=r;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=mi(o[c]),o=o[c]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[a]})}return r}function gs(t){const e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}var gr=class _c{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,gs(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...r){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof _c||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},r={},n=Object.keys(this.lc_kwargs).reduce((a,s)=>(a[s]=s in this?this[s]:this.lc_kwargs[s],a),{});for(let a=Object.getPrototypeOf(this);a;a=Object.getPrototypeOf(a))Object.assign(e,Reflect.get(a,"lc_aliases",this)),Object.assign(r,Reflect.get(a,"lc_secrets",this)),Object.assign(n,Reflect.get(a,"lc_attributes",this));return Object.keys(r).forEach(a=>{let s=this,i=n;const[o,...c]=a.split(".").reverse();for(const u of c.reverse()){if(!(u in s)||s[u]===void 0)return;(!(u in i)||i[u]===void 0)&&(typeof s[u]=="object"&&s[u]!=null?i[u]={}:Array.isArray(s[u])&&(i[u]=[])),s=s[u],i=i[u]}o in s&&s[o]!==void 0&&(i[o]=i[o]||s[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:Vl(Object.keys(r).length?Jl(n,r):n,Zl,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function D(t,e){return K(t)&&t.type===e}function K(t){return typeof t=="object"&&t!==null}function Ye(t){return Array.isArray(t)}function k(t){return typeof t=="string"}function ze(t){return typeof t=="number"}function ys(t){return t instanceof Uint8Array}function gi(t){try{return JSON.parse(t)}catch{return}}const yr=t=>t();function Kl(t){if(t.type==="char_location"&&k(t.document_title)&&ze(t.start_char_index)&&ze(t.end_char_index)&&k(t.cited_text)){const{document_title:e,start_char_index:r,end_char_index:n,cited_text:a,...s}=t;return{...s,type:"citation",source:"char",title:e??void 0,startIndex:r,endIndex:n,citedText:a}}if(t.type==="page_location"&&k(t.document_title)&&ze(t.start_page_number)&&ze(t.end_page_number)&&k(t.cited_text)){const{document_title:e,start_page_number:r,end_page_number:n,cited_text:a,...s}=t;return{...s,type:"citation",source:"page",title:e??void 0,startIndex:r,endIndex:n,citedText:a}}if(t.type==="content_block_location"&&k(t.document_title)&&ze(t.start_block_index)&&ze(t.end_block_index)&&k(t.cited_text)){const{document_title:e,start_block_index:r,end_block_index:n,cited_text:a,...s}=t;return{...s,type:"citation",source:"block",title:e??void 0,startIndex:r,endIndex:n,citedText:a}}if(t.type==="web_search_result_location"&&k(t.url)&&k(t.title)&&k(t.encrypted_index)&&k(t.cited_text)){const{url:e,title:r,encrypted_index:n,cited_text:a,...s}=t;return{...s,type:"citation",source:"url",url:e,title:r,startIndex:Number(n),endIndex:Number(n),citedText:a}}if(t.type==="search_result_location"&&k(t.source)&&k(t.title)&&ze(t.start_block_index)&&ze(t.end_block_index)&&k(t.cited_text)){const{source:e,title:r,start_block_index:n,end_block_index:a,cited_text:s,...i}=t;return{...i,type:"citation",source:"search",url:e,title:r??void 0,startIndex:n,endIndex:a,citedText:s}}}function vc(t){if(D(t,"document")&&K(t.source)&&"type"in t.source){if(t.source.type==="base64"&&k(t.source.media_type)&&k(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&k(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&k(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&k(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(D(t,"image")&&K(t.source)&&"type"in t.source){if(t.source.type==="base64"&&k(t.source.media_type)&&k(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&k(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&k(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}function Yl(t){function*e(){for(const r of t){const n=vc(r);n?yield n:yield r}}return Array.from(e())}function yi(t){function*e(){const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r){if(D(n,"text")&&k(n.text)){const{text:a,citations:s,...i}=n;if(Ye(s)&&s.length){const o=s.reduce((c,u)=>{const l=Kl(u);return l?[...c,l]:c},[]);yield{...i,type:"text",text:a,annotations:o};continue}else{yield{...i,type:"text",text:a};continue}}else if(D(n,"thinking")&&k(n.thinking)){const{thinking:a,signature:s,...i}=n;yield{...i,type:"reasoning",reasoning:a,signature:s};continue}else if(D(n,"redacted_thinking")){yield{type:"non_standard",value:n};continue}else if(D(n,"tool_use")&&k(n.name)&&k(n.id)){yield{type:"tool_call",id:n.id,name:n.name,args:n.input};continue}else if(D(n,"input_json_delta")){if(Xl(t)&&t.tool_call_chunks?.length){const a=t.tool_call_chunks[0];yield{type:"tool_call_chunk",id:a.id,name:a.name,args:a.args,index:a.index};continue}}else if(D(n,"server_tool_use")&&k(n.name)&&k(n.id)){const{name:a,id:s}=n;if(a==="web_search"){const i=yr(()=>{if(typeof n.input=="string")return n.input;if(K(n.input)&&k(n.input.query))return n.input.query;if(k(n.partial_json)){const o=gi(n.partial_json);if(o?.query)return o.query}return""});yield{id:s,type:"server_tool_call",name:"web_search",args:{query:i}};continue}else if(n.name==="code_execution"){const i=yr(()=>{if(typeof n.input=="string")return n.input;if(K(n.input)&&k(n.input.code))return n.input.code;if(k(n.partial_json)){const o=gi(n.partial_json);if(o?.code)return o.code}return""});yield{id:s,type:"server_tool_call",name:"code_execution",args:{code:i}};continue}}else if(D(n,"web_search_tool_result")&&k(n.tool_use_id)&&Ye(n.content)){const{content:a,tool_use_id:s}=n,i=a.reduce((o,c)=>D(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:s,status:"success",output:{urls:i}};continue}else if(D(n,"code_execution_tool_result")&&k(n.tool_use_id)&&K(n.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(D(n,"mcp_tool_use")){yield{id:n.id,type:"server_tool_call",name:"mcp_tool_use",args:n.input};continue}else if(D(n,"mcp_tool_result")&&k(n.tool_use_id)&&K(n.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(D(n,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:n.input};continue}else if(D(n,"search_result")){yield{id:n.id,type:"non_standard",value:n};continue}else if(D(n,"tool_result")){yield{id:n.id,type:"non_standard",value:n};continue}else{const a=vc(n);if(a){yield a;continue}}yield{type:"non_standard",value:n}}}return Array.from(e())}const Ql={translateContent:yi,translateContentChunk:yi};function Xl(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}function ed(t){return fs(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:hs(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:ps(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}function td(t){return t.map(ed)}function rd(t){return!!(D(t,"image_url")&&K(t.image_url)||D(t,"input_audio")&&K(t.input_audio)||D(t,"file")&&K(t.file))}function nd(t){if(D(t,"image_url")&&K(t.image_url)&&k(t.image_url.url)){const e=an({dataUrl:t.image_url.url});return e?{type:"image",mimeType:e.mime_type,data:e.data}:{type:"image",url:t.image_url.url}}else{if(D(t,"input_audio")&&K(t.input_audio)&&k(t.input_audio.data)&&k(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(D(t,"file")&&K(t.file)&&k(t.file.data)){const e=an({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(k(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}function ad(t){const e=[];typeof t.content=="string"?e.push({type:"text",text:t.content}):e.push(..._s(t.content));for(const r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}function sd(t){const e=[];typeof t.content=="string"?e.push({type:"text",text:t.content}):e.push(..._s(t.content));for(const r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}function _s(t){const e=[];for(const r of t)rd(r)?e.push(nd(r)):e.push(r);return e}function id(t){if(t.type==="url_citation"){const{url:e,title:r,start_index:n,end_index:a}=t;return{type:"citation",url:e,title:r,startIndex:n,endIndex:a}}if(t.type==="file_citation"){const{file_id:e,filename:r,index:n}=t;return{type:"citation",title:r,startIndex:n,endIndex:n,fileId:e}}return t}function wc(t){function*e(){K(t.additional_kwargs?.reasoning)&&Ye(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((a,s)=>K(s)&&k(s.text)?`${a}${s.text}`:a,"")});const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r)if(D(n,"text")){const{text:a,annotations:s,...i}=n;Array.isArray(s)?yield{...i,type:"text",text:String(a),annotations:s.map(id)}:yield{...i,type:"text",text:String(a)}}for(const n of t.tool_calls??[])yield{type:"tool_call",id:n.id,name:n.name,args:n.args};if(K(t.additional_kwargs)&&Ye(t.additional_kwargs.tool_outputs))for(const n of t.additional_kwargs.tool_outputs){if(D(n,"web_search_call")){yield{id:n.id,type:"server_tool_call",name:"web_search",args:{query:n.query}};continue}else if(D(n,"file_search_call")){yield{id:n.id,type:"server_tool_call",name:"file_search",args:{query:n.query}};continue}else if(D(n,"computer_call")){yield{type:"non_standard",value:n};continue}else if(D(n,"code_interpreter_call")){if(k(n.code)&&(yield{id:n.id,type:"server_tool_call",name:"code_interpreter",args:{code:n.code}}),Ye(n.outputs)){const a=yr(()=>{if(n.status!=="in_progress"){if(n.status==="completed")return 0;if(n.status==="incomplete")return 127;if(n.status!=="interpreting"&&n.status==="failed")return 1}});for(const s of n.outputs)if(D(s,"logs")){yield{type:"server_tool_call_result",toolCallId:n.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:a??0,stderr:[0,void 0].includes(a)?void 0:String(s.logs),stdout:[0,void 0].includes(a)?String(s.logs):void 0}};continue}}continue}else if(D(n,"mcp_call")){yield{id:n.id,type:"server_tool_call",name:"mcp_call",args:n.input};continue}else if(D(n,"mcp_list_tools")){yield{id:n.id,type:"server_tool_call",name:"mcp_list_tools",args:n.input};continue}else if(D(n,"mcp_approval_request")){yield{type:"non_standard",value:n};continue}else if(D(n,"image_generation_call")){yield{type:"non_standard",value:n};continue}K(n)&&(yield{type:"non_standard",value:n})}}return Array.from(e())}function od(t){function*e(){yield*wc(t);for(const r of t.tool_call_chunks??[])yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args}}return Array.from(e())}const cd={translateContent:t=>typeof t.content=="string"?ad(t):wc(t),translateContentChunk:t=>typeof t.content=="string"?sd(t):od(t)};function ud(t,e="pretty"){return e==="pretty"?ld(t):JSON.stringify(t)}function ld(t){const e=[],r=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,n=Math.floor((80-r.length)/2),a="=".repeat(n),s=r.length%2===0?a:`${a}=`;if(e.push(`${a}${r}${s}`),t.type==="ai"){const i=t;if(i.tool_calls&&i.tool_calls.length>0){e.push("Tool Calls:");for(const o of i.tool_calls){e.push(` ${o.name} (${o.id})`),e.push(` Call ID: ${o.id}`),e.push(" Args:");for(const[c,u]of Object.entries(o.args))e.push(` ${c}: ${typeof u=="object"?JSON.stringify(u):u}`)}}}if(t.type==="tool"){const i=t;i.name&&e.push(`Name: ${i.name}`)}return typeof t.content=="string"&&t.content.trim()&&(e.length>1&&e.push(""),e.push(t.content)),e.join(`
|
|
2
|
+
`)}const Rn=Symbol.for("langchain.message");function Xe(t,e){return typeof t=="string"?t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.length===0?t:Array.isArray(e)&&e.some(r=>ct(r))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e]:Array.isArray(e)?Kt(t,e)??[...t,...e]:e===""?t:Array.isArray(t)&&t.some(r=>ct(r))?[...t,{type:"file",source_type:"text",text:e}]:[...t,{type:"text",text:e}]}function vs(t,e){return t==="error"||e==="error"?"error":"success"}function dd(t,e){function r(n,a){if(typeof n!="object"||n===null||n===void 0)return n;if(a>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(i=>r(i,a+1));const s={};for(const i of Object.keys(n))s[i]=r(n[i],a+1);return s}return JSON.stringify(r(t,0),null,2)}var tt=class extends gr{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[Rn]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(t){const e=typeof t=="string"||Array.isArray(t)?{content:t}:t;e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),this.name=e.name,e.content===void 0&&e.contentBlocks!==void 0?(this.content=e.contentBlocks,this.response_metadata={output_version:"v1",...e.response_metadata}):e.content!==void 0?(this.content=e.content??[],this.response_metadata=e.response_metadata):(this.content=[],this.response_metadata=e.response_metadata),this.additional_kwargs=e.additional_kwargs,this.id=e.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(t=>typeof t=="string"?t:t.type==="text"?t.text:"").join(""):""}get contentBlocks(){const t=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[td,_s,Yl].reduce((n,a)=>a(n),t)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(t){return typeof t=="object"&&t!==null&&Rn in t&&t[Rn]===!0&&ms(t)}_updateId(t){this.id=t,this.lc_kwargs.id=t}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](t){if(t===null)return this;const e=dd(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return ud(this,t)}};function bc(t){return Array.isArray(t)&&t.every(e=>typeof e.index=="number")}function ve(t={},e={}){const r={...t};for(const[n,a]of Object.entries(e))if(r[n]==null)r[n]=a;else{if(a==null)continue;if(typeof r[n]!=typeof a||Array.isArray(r[n])!==Array.isArray(a))throw new Error(`field[${n}] already exists in the message chunk, but with a different type.`);if(typeof r[n]=="string"){if(n==="type")continue;["id","name","output_version","model_provider"].includes(n)?a&&(r[n]=a):r[n]+=a}else if(typeof r[n]=="object"&&!Array.isArray(r[n]))r[n]=ve(r[n],a);else if(Array.isArray(r[n]))r[n]=Kt(r[n],a);else{if(r[n]===a)continue;console.warn(`field[${n}] already exists in this message chunk and value has unsupported type.`)}}return r}function Kt(t,e){if(!(t===void 0&&e===void 0)){if(t===void 0||e===void 0)return t||e;{const r=[...t];for(const n of e)if(typeof n=="object"&&n!==null&&"index"in n&&typeof n.index=="number"){const a=r.findIndex(s=>{const i=typeof s=="object",o="index"in s&&s.index===n.index,c="id"in s&&"id"in n&&s?.id===n?.id,u=!("id"in s)||!s?.id||!("id"in n)||!n?.id;return i&&o&&(c||u)});a!==-1&&typeof r[a]=="object"&&r[a]!==null?r[a]=ve(r[a],n):r.push(n)}else{if(typeof n=="object"&&n!==null&&"text"in n&&n.text==="")continue;r.push(n)}return r}}}function ws(t,e){if(!t&&!e)throw new Error("Cannot merge two undefined objects.");if(!t||!e)return t||e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types.
|
|
3
|
+
Left ${typeof t}
|
|
4
|
+
Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return Kt(t,e);if(typeof t=="object"&&typeof e=="object")return ve(t,e);if(t===e)return t;throw new Error(`Can not merge objects of different types.
|
|
5
|
+
Left ${t}
|
|
6
|
+
Right ${e}`)}var dt=class Ec extends tt{static isInstance(e){if(!super.isInstance(e))return!1;let r=Object.getPrototypeOf(e);for(;r!==null;){if(r===Ec.prototype)return!0;r=Object.getPrototypeOf(r)}return!1}};function bs(t){return typeof t.role=="string"}function Es(t){return typeof t?._getType=="function"}function Ss(t){return dt.isInstance(t)}function Ts(t,e){return ve(t??{},e??{})}function Sc(t,e){const r={};return(t?.audio!==void 0||e?.audio!==void 0)&&(r.audio=(t?.audio??0)+(e?.audio??0)),(t?.image!==void 0||e?.image!==void 0)&&(r.image=(t?.image??0)+(e?.image??0)),(t?.video!==void 0||e?.video!==void 0)&&(r.video=(t?.video??0)+(e?.video??0)),(t?.document!==void 0||e?.document!==void 0)&&(r.document=(t?.document??0)+(e?.document??0)),(t?.text!==void 0||e?.text!==void 0)&&(r.text=(t?.text??0)+(e?.text??0)),r}function fd(t,e){const r={...Sc(t,e)};return(t?.cache_read!==void 0||e?.cache_read!==void 0)&&(r.cache_read=(t?.cache_read??0)+(e?.cache_read??0)),(t?.cache_creation!==void 0||e?.cache_creation!==void 0)&&(r.cache_creation=(t?.cache_creation??0)+(e?.cache_creation??0)),r}function hd(t,e){const r={...Sc(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(r.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),r}function xs(t,e){return{input_tokens:(t?.input_tokens??0)+(e?.input_tokens??0),output_tokens:(t?.output_tokens??0)+(e?.output_tokens??0),total_tokens:(t?.total_tokens??0)+(e?.total_tokens??0),input_token_details:fd(t?.input_token_details,e?.input_token_details),output_token_details:hd(t?.output_token_details,e?.output_token_details)}}var pd={};ge(pd,{ToolMessage:()=>Ct,ToolMessageChunk:()=>Tr,defaultToolCallParser:()=>yn,isDirectToolOutput:()=>Is,isToolMessage:()=>As,isToolMessageChunk:()=>$s});function Is(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}var Ct=class extends tt{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}lc_direct_tool_output=!0;type="tool";status;tool_call_id;metadata;artifact;constructor(t,e,r){const n=typeof t=="string"||Array.isArray(t)?{content:t,name:r,tool_call_id:e}:t;super(n),this.tool_call_id=n.tool_call_id,this.artifact=n.artifact,this.status=n.status,this.metadata=n.metadata}static isInstance(t){return super.isInstance(t)&&t.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},Tr=class extends dt{type="tool";tool_call_id;status;artifact;constructor(t){super(t),this.tool_call_id=t.tool_call_id,this.artifact=t.artifact,this.status=t.status}static lc_name(){return"ToolMessageChunk"}concat(t){const e=this.constructor;return new e({content:Xe(this.content,t.content),additional_kwargs:ve(this.additional_kwargs,t.additional_kwargs),response_metadata:ve(this.response_metadata,t.response_metadata),artifact:ws(this.artifact,t.artifact),tool_call_id:this.tool_call_id,id:this.id??t.id,status:vs(this.status,t.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function yn(t){const e=[],r=[];for(const n of t)if(n.function){const a=n.function.name;try{const s=JSON.parse(n.function.arguments);e.push({name:a||"",args:s||{},id:n.id})}catch{r.push({name:a,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}function As(t){return typeof t=="object"&&t!==null&&"getType"in t&&typeof t.getType=="function"&&t.getType()==="tool"}function $s(t){return t._getType()==="tool"}var Yt=class Tc extends tt{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return Tc}constructor(e,r){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:r}),super(e),this.role=e.role}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},xr=class extends dt{static lc_name(){return"ChatMessageChunk"}type="generic";role;constructor(t,e){(typeof t=="string"||Array.isArray(t))&&(t={content:t,role:e}),super(t),this.role=t.role}concat(t){const e=this.constructor;return new e({content:Xe(this.content,t.content),additional_kwargs:ve(this.additional_kwargs,t.additional_kwargs),response_metadata:ve(this.response_metadata,t.response_metadata),role:this.role,id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}};function xc(t){return t._getType()==="generic"}function Ic(t){return t._getType()==="generic"}var Ir=class extends tt{static lc_name(){return"FunctionMessage"}type="function";name;constructor(t){super(t),this.name=t.name}},Ar=class extends dt{static lc_name(){return"FunctionMessageChunk"}type="function";concat(t){const e=this.constructor;return new e({content:Xe(this.content,t.content),additional_kwargs:ve(this.additional_kwargs,t.additional_kwargs),response_metadata:ve(this.response_metadata,t.response_metadata),name:this.name??"",id:this.id??t.id})}};function Ac(t){return t._getType()==="function"}function $c(t){return t._getType()==="function"}var Nt=class extends tt{static lc_name(){return"HumanMessage"}type="human";constructor(t){super(t)}static isInstance(t){return super.isInstance(t)&&t.type==="human"}},$r=class extends dt{static lc_name(){return"HumanMessageChunk"}type="human";constructor(t){super(t)}concat(t){const e=this.constructor;return new e({content:Xe(this.content,t.content),additional_kwargs:ve(this.additional_kwargs,t.additional_kwargs),response_metadata:ve(this.response_metadata,t.response_metadata),id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="human"}};function Rc(t){return t.getType()==="human"}function Oc(t){return t.getType()==="human"}var _r=class extends tt{type="remove";id;constructor(t){super({...t,content:[]}),this.id=t.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(t){return super.isInstance(t)&&t.type==="remove"}},ut=class Jr extends tt{static lc_name(){return"SystemMessage"}type="system";constructor(e){super(e)}concat(e){if(typeof e=="string")return new Jr({...this,content:Xe(this.content,e)});if(Jr.isInstance(e))return new Jr({...this,additional_kwargs:{...this.additional_kwargs,...e.additional_kwargs},response_metadata:{...this.response_metadata,...e.response_metadata},content:Xe(this.content,e.content)});throw new Error("Unexpected chunk type for system message")}static isInstance(e){return super.isInstance(e)&&e.type==="system"}},Rt=class extends dt{static lc_name(){return"SystemMessageChunk"}type="system";constructor(t){super(t)}concat(t){const e=this.constructor;return new e({content:Xe(this.content,t.content),additional_kwargs:ve(this.additional_kwargs,t.additional_kwargs),response_metadata:ve(this.response_metadata,t.response_metadata),id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="system"}};function kc(t){return t._getType()==="system"}function Cc(t){return t._getType()==="system"}function md(t,e){return t.lc_error_code=e,t.message=`${t.message}
|
|
7
|
+
|
|
8
|
+
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
|
|
9
|
+
`,t}function Nc(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function ry(t){return!!(t&&typeof t=="object"&&"toolCall"in t&&t.toolCall!=null&&typeof t.toolCall=="object"&&"id"in t.toolCall&&typeof t.toolCall.id=="string")}var gd=class extends Error{output;constructor(t,e){super(t),this.output=e}};function ny(t,e=Pc){t=t.trim();const r=t.indexOf("```");if(r===-1)return e(t);let n=t.substring(r+3);n.startsWith(`json
|
|
10
|
+
`)?n=n.substring(5):n.startsWith("json")?n=n.substring(4):n.startsWith(`
|
|
11
|
+
`)&&(n=n.substring(1));const a=n.indexOf("```");let s=n;return a!==-1&&(s=n.substring(0,a)),e(s.trim())}function yd(t){try{return JSON.parse(t)}catch{}const e=t.trim();if(e.length===0)throw new Error("Unexpected end of JSON input");let r=0;function n(){for(;r<e.length&&/\s/.test(e[r]);)r+=1}function a(){if(e[r]!=='"')throw new Error(`Expected '"' at position ${r}, got '${e[r]}'`);r+=1;let l="",d=!1;for(;r<e.length;){const f=e[r];if(d){if(f==="n")l+=`
|
|
12
|
+
`;else if(f==="t")l+=" ";else if(f==="r")l+="\r";else if(f==="\\")l+="\\";else if(f==='"')l+='"';else if(f==="b")l+="\b";else if(f==="f")l+="\f";else if(f==="/")l+="/";else if(f==="u"){const h=e.substring(r+1,r+5);if(/^[0-9A-Fa-f]{0,4}$/.test(h))h.length===4?l+=String.fromCharCode(Number.parseInt(h,16)):l+=`u${h}`,r+=h.length;else throw new Error(`Invalid unicode escape sequence '\\u${h}' at position ${r}`)}else throw new Error(`Invalid escape sequence '\\${f}' at position ${r}`);d=!1}else if(f==="\\")d=!0;else{if(f==='"')return r+=1,l;l+=f}r+=1}return d&&(l+="\\"),l}function s(){const l=r;let d="";if(e[r]==="-"&&(d+="-",r+=1),r<e.length&&e[r]==="0"&&(d+="0",r+=1,e[r]>="0"&&e[r]<="9"))throw new Error(`Invalid number at position ${l}`);if(r<e.length&&e[r]>="1"&&e[r]<="9")for(;r<e.length&&e[r]>="0"&&e[r]<="9";)d+=e[r],r+=1;if(r<e.length&&e[r]===".")for(d+=".",r+=1;r<e.length&&e[r]>="0"&&e[r]<="9";)d+=e[r],r+=1;if(r<e.length&&(e[r]==="e"||e[r]==="E"))for(d+=e[r],r+=1,r<e.length&&(e[r]==="+"||e[r]==="-")&&(d+=e[r],r+=1);r<e.length&&e[r]>="0"&&e[r]<="9";)d+=e[r],r+=1;if(d==="-")return-0;const f=Number.parseFloat(d);if(Number.isNaN(f))throw r=l,new Error(`Invalid number '${d}' at position ${l}`);return f}function i(){if(n(),r>=e.length)throw new Error(`Unexpected end of input at position ${r}`);const l=e[r];if(l==="{")return c();if(l==="[")return o();if(l==='"')return a();if("null".startsWith(e.substring(r,r+4)))return r+=Math.min(4,e.length-r),null;if("true".startsWith(e.substring(r,r+4)))return r+=Math.min(4,e.length-r),!0;if("false".startsWith(e.substring(r,r+5)))return r+=Math.min(5,e.length-r),!1;if(l==="-"||l>="0"&&l<="9")return s();throw new Error(`Unexpected character '${l}' at position ${r}`)}function o(){if(e[r]!=="[")throw new Error(`Expected '[' at position ${r}, got '${e[r]}'`);const l=[];if(r+=1,n(),r>=e.length)return l;if(e[r]==="]")return r+=1,l;for(;r<e.length;){if(n(),r>=e.length||(l.push(i()),n(),r>=e.length))return l;if(e[r]==="]")return r+=1,l;if(e[r]===","){r+=1;continue}throw new Error(`Expected ',' or ']' at position ${r}, got '${e[r]}'`)}return l}function c(){if(e[r]!=="{")throw new Error(`Expected '{' at position ${r}, got '${e[r]}'`);const l={};if(r+=1,n(),r>=e.length)return l;if(e[r]==="}")return r+=1,l;for(;r<e.length;){if(n(),r>=e.length)return l;const d=a();if(n(),r>=e.length)return l;if(e[r]!==":")throw new Error(`Expected ':' at position ${r}, got '${e[r]}'`);if(r+=1,n(),r>=e.length||(l[d]=i(),n(),r>=e.length))return l;if(e[r]==="}")return r+=1,l;if(e[r]===","){r+=1;continue}throw new Error(`Expected ',' or '}' at position ${r}, got '${e[r]}'`)}return l}const u=i();if(n(),r<e.length)throw new Error(`Unexpected character '${e[r]}' at position ${r}`);return u}function Pc(t){try{return typeof t>"u"?null:yd(t)}catch{return null}}function Rs(t){switch(t){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function _d(t){if(K(t.document)&&K(t.document.source)){const e=K(t.document)&&k(t.document.format)?t.document.format:"",r=Rs(e);if(K(t.document.source)){if(K(t.document.source.s3Location)&&k(t.document.source.s3Location.uri))return{type:"file",mimeType:r,fileId:t.document.source.s3Location.uri};if(ys(t.document.source.bytes))return{type:"file",mimeType:r,data:t.document.source.bytes};if(k(t.document.source.text))return{type:"file",mimeType:r,data:Buffer.from(t.document.source.text).toString("base64")};if(Ye(t.document.source.content)){const n=t.document.source.content.reduce((a,s)=>K(s)&&k(s.text)?a+s.text:a,"");return{type:"file",mimeType:r,data:n}}}}return{type:"non_standard",value:t}}function vd(t){if(D(t,"image")&&K(t.image)){const e=K(t.image)&&k(t.image.format)?t.image.format:"",r=Rs(e);if(K(t.image.source)){if(K(t.image.source.s3Location)&&k(t.image.source.s3Location.uri))return{type:"image",mimeType:r,fileId:t.image.source.s3Location.uri};if(ys(t.image.source.bytes))return{type:"image",mimeType:r,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}function wd(t){if(D(t,"video")&&K(t.video)){const e=K(t.video)&&k(t.video.format)?t.video.format:"",r=Rs(e);if(K(t.video.source)){if(K(t.video.source.s3Location)&&k(t.video.source.s3Location.uri))return{type:"video",mimeType:r,fileId:t.video.source.s3Location.uri};if(ys(t.video.source.bytes))return{type:"video",mimeType:r,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}function _i(t){function*e(){const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r){if(D(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(D(n,"citations_content")&&K(n.citationsContent)){const a=Ye(n.citationsContent.content)?n.citationsContent.content.reduce((i,o)=>K(o)&&k(o.text)?i+o.text:i,""):"",s=Ye(n.citationsContent.citations)?n.citationsContent.citations.reduce((i,o)=>{if(K(o)){const c=Ye(o.sourceContent)?o.sourceContent.reduce((l,d)=>K(d)&&k(d.text)?l+d.text:l,""):"",u=yr(()=>{if(K(o.location)){const l=o.location.documentChar||o.location.documentPage||o.location.documentChunk;if(K(l))return{source:ze(l.documentIndex)?l.documentIndex.toString():void 0,startIndex:ze(l.start)?l.start:void 0,endIndex:ze(l.end)?l.end:void 0}}return{}});i.push({type:"citation",citedText:c,...u})}return i},[]):[];yield{type:"text",text:a,annotations:s};continue}else if(D(n,"document")&&K(n.document)){yield _d(n);continue}else if(D(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(D(n,"image")&&K(n.image)){yield vd(n);continue}else if(D(n,"reasoning_content")&&k(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(D(n,"text")&&k(n.text)){yield{type:"text",text:n.text};continue}else if(D(n,"tool_result")){yield{type:"non_standard",value:n};continue}else{if(D(n,"tool_call"))continue;if(D(n,"video")&&K(n.video)){yield wd(n);continue}}yield{type:"non_standard",value:n}}}return Array.from(e())}const bd={translateContent:_i,translateContentChunk:_i};function vi(t){function*e(){const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r){if(D(n,"text")&&k(n.text)){yield{type:"text",text:n.text};continue}else if(D(n,"inlineData")&&K(n.inlineData)&&k(n.inlineData.mimeType)&&k(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(D(n,"functionCall")&&K(n.functionCall)&&k(n.functionCall.name)&&K(n.functionCall.args)){yield{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(D(n,"functionResponse")){yield{type:"non_standard",value:n};continue}else if(D(n,"fileData")&&K(n.fileData)&&k(n.fileData.mimeType)&&k(n.fileData.fileUri)){yield{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(D(n,"executableCode")){yield{type:"non_standard",value:n};continue}else if(D(n,"codeExecutionResult")){yield{type:"non_standard",value:n};continue}yield{type:"non_standard",value:n}}}return Array.from(e())}const Ed={translateContent:vi,translateContentChunk:vi};function wi(t){function*e(){const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r){if(D(n,"reasoning")&&k(n.reasoning)){const a=yr(()=>{const s=r.indexOf(n);if(Ye(t.additional_kwargs?.signatures)&&s>=0)return t.additional_kwargs.signatures.at(s)});k(a)?yield{type:"reasoning",reasoning:n.reasoning,signature:a}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(D(n,"text")&&k(n.text)){yield{type:"text",text:n.text};continue}else if(D(n,"image_url")){if(k(n.image_url))if(n.image_url.startsWith("data:")){const a=/^data:([^;]+);base64,(.+)$/,s=n.image_url.match(a);s?yield{type:"image",data:s[2],mimeType:s[1]}:yield{type:"image",url:n.image_url}}else yield{type:"image",url:n.image_url};continue}else if(D(n,"media")&&k(n.mimeType)&&k(n.data)){yield{type:"file",mimeType:n.mimeType,data:n.data};continue}yield{type:"non_standard",value:n}}}return Array.from(e())}const Sd={translateContent:wi,translateContentChunk:wi};globalThis.lc_block_translators_registry??=new Map([["anthropic",Ql],["bedrock-converse",bd],["google-genai",Ed],["google-vertexai",Sd],["openai",cd]]);function Lc(t){return globalThis.lc_block_translators_registry.get(t)}var Ot=class extends tt{type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(t){let e;if(typeof t=="string"||Array.isArray(t))e={content:t,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{e=t;const r=e.additional_kwargs?.tool_calls,n=e.tool_calls;r!=null&&r.length>0&&(n===void 0||n.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
|
|
13
|
+
|
|
14
|
+
Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(r!=null&&n===void 0){const[a,s]=yn(r);e.tool_calls=a??[],e.invalid_tool_calls=s??[]}else e.tool_calls=e.tool_calls??[],e.invalid_tool_calls=e.invalid_tool_calls??[]}catch{e.tool_calls=[],e.invalid_tool_calls=[]}if(e.response_metadata!==void 0&&"output_version"in e.response_metadata&&e.response_metadata.output_version==="v1"&&(e.contentBlocks=e.content,e.content=void 0),e.contentBlocks!==void 0){e.contentBlocks.push(...e.tool_calls.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args})));const a=e.contentBlocks.filter(s=>s.type==="tool_call").filter(s=>!e.tool_calls?.some(i=>i.id===s.id&&i.name===s.name));a.length>0&&(e.tool_calls=a.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args})))}}super(e),typeof e!="string"&&(this.tool_calls=e.tool_calls??this.tool_calls,this.invalid_tool_calls=e.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=e.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const e=Lc(this.response_metadata.model_provider);if(e)return e.translateContent(this)}const t=super.contentBlocks;if(this.tool_calls){const e=this.tool_calls.filter(r=>!t.some(n=>n.id===r.id&&n.name===r.name));t.push(...e.map(r=>({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})))}return t}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}};function Mc(t){return t._getType()==="ai"}function jc(t){return t._getType()==="ai"}var Pt=class extends dt{type="ai";tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(t){let e;typeof t=="string"||Array.isArray(t)?e={content:t,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]}:t.tool_call_chunks===void 0||t.tool_call_chunks.length===0?e={...t,tool_calls:t.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:t.usage_metadata!==void 0?t.usage_metadata:void 0}:e={...t,...Cs(t.tool_call_chunks??[]),usage_metadata:t.usage_metadata!==void 0?t.usage_metadata:void 0},super(e),this.tool_call_chunks=e.tool_call_chunks??this.tool_call_chunks,this.tool_calls=e.tool_calls??this.tool_calls,this.invalid_tool_calls=e.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=e.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const e=Lc(this.response_metadata.model_provider);if(e)return e.translateContent(this)}const t=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){const e=this.content.filter(r=>r.type==="tool_call").map(r=>r.id);for(const r of this.tool_calls)r.id&&!e.includes(r.id)&&t.push({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})}return t}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(t){const e={content:Xe(this.content,t.content),additional_kwargs:ve(this.additional_kwargs,t.additional_kwargs),response_metadata:Ts(this.response_metadata,t.response_metadata),tool_call_chunks:[],id:this.id??t.id};if(this.tool_call_chunks!==void 0||t.tool_call_chunks!==void 0){const n=Kt(this.tool_call_chunks,t.tool_call_chunks);n!==void 0&&n.length>0&&(e.tool_call_chunks=n)}(this.usage_metadata!==void 0||t.usage_metadata!==void 0)&&(e.usage_metadata=xs(this.usage_metadata,t.usage_metadata));const r=this.constructor;return new r(e)}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}};const Dc=t=>t();function Td(t){return Nc(t)?t:typeof t.id=="string"&&t.type==="function"&&typeof t.function=="object"&&t.function!==null&&"arguments"in t.function&&typeof t.function.arguments=="string"&&"name"in t.function&&typeof t.function.name=="string"?{id:t.id,args:JSON.parse(t.function.arguments),name:t.function.name,type:"tool_call"}:t}function xd(t){return typeof t=="object"&&t!=null&&t.lc===1&&Array.isArray(t.id)&&t.kwargs!=null&&typeof t.kwargs=="object"}function On(t){let e,r;if(xd(t)){const n=t.id.at(-1);n==="HumanMessage"||n==="HumanMessageChunk"?e="user":n==="AIMessage"||n==="AIMessageChunk"?e="assistant":n==="SystemMessage"||n==="SystemMessageChunk"?e="system":n==="FunctionMessage"||n==="FunctionMessageChunk"?e="function":n==="ToolMessage"||n==="ToolMessageChunk"?e="tool":e="unknown",r=t.kwargs}else{const{type:n,...a}=t;e=n,r=a}if(e==="human"||e==="user")return new Nt(r);if(e==="ai"||e==="assistant"){const{tool_calls:n,...a}=r;if(!Array.isArray(n))return new Ot(r);const s=n.map(Td);return new Ot({...a,tool_calls:s})}else{if(e==="system")return new ut(r);if(e==="developer")return new ut({...r,additional_kwargs:{...r.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in r)return new Ct({...r,content:r.content,tool_call_id:r.tool_call_id,name:r.name});if(e==="remove"&&"id"in r&&typeof r.id=="string")return new _r({...r,id:r.id});throw md(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
|
|
15
|
+
|
|
16
|
+
Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Uc(t){if(typeof t=="string")return new Nt(t);if(Es(t))return t;if(Array.isArray(t)){const[e,r]=t;return On({type:e,content:r})}else if(bs(t)){const{role:e,...r}=t;return On({...r,type:e})}else return On(t)}function Os(t,e="Human",r="AI"){const n=[];for(const a of t){let s;if(a._getType()==="human")s=e;else if(a._getType()==="ai")s=r;else if(a._getType()==="system")s="System";else if(a._getType()==="tool")s="Tool";else if(a._getType()==="generic")s=a.role;else throw new Error(`Got unsupported message type: ${a._getType()}`);const i=a.name?`${a.name}, `:"",o=typeof a.content=="string"?a.content:JSON.stringify(a.content,null,2);n.push(`${s}: ${i}${o}`)}return n.join(`
|
|
17
|
+
`)}function Id(t){if(t.data!==void 0)return t;{const e=t;return{type:e.type,data:{content:e.text,role:e.role,name:void 0,tool_call_id:void 0}}}}function ks(t){const e=Id(t);switch(e.type){case"human":return new Nt(e.data);case"ai":return new Ot(e.data);case"system":return new ut(e.data);case"function":if(e.data.name===void 0)throw new Error("Name must be defined for function messages");return new Ir(e.data);case"tool":if(e.data.tool_call_id===void 0)throw new Error("Tool call ID must be defined for tool messages");return new Ct(e.data);case"generic":if(e.data.role===void 0)throw new Error("Role must be defined for chat messages");return new Yt(e.data);default:throw new Error(`Got unexpected type: ${e.type}`)}}function Fc(t){return t.map(ks)}function Bc(t){return t.map(e=>e.toDict())}function sn(t){const e=t._getType();if(e==="human")return new $r({...t});if(e==="ai"){let r={...t};return"tool_calls"in r&&(r={...r,tool_call_chunks:r.tool_calls?.map(n=>({...n,type:"tool_call_chunk",index:void 0,args:JSON.stringify(n.args)}))}),new Pt({...r})}else{if(e==="system")return new Rt({...t});if(e==="function")return new Ar({...t});if(Yt.isInstance(t))return new xr({...t});throw new Error("Unknown message type.")}}function Cs(t){const e=t.reduce((a,s)=>{const i=a.findIndex(([o])=>"id"in s&&s.id&&"index"in s&&s.index!==void 0?s.id===o.id&&s.index===o.index:"id"in s&&s.id?s.id===o.id:"index"in s&&s.index!==void 0?s.index===o.index:!1);return i!==-1?a[i].push(s):a.push([s]),a},[]),r=[],n=[];for(const a of e){let s=null;const i=a[0]?.name??"",o=a.map(l=>l.args||"").join("").trim(),c=o.length?o:"{}",u=a[0]?.id;try{if(s=Pc(c),!u||s===null||typeof s!="object"||Array.isArray(s))throw new Error("Malformed tool call chunk args.");r.push({name:i,args:s,id:u,type:"tool_call"})}catch{n.push({name:i,args:c,id:u,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:t,tool_calls:r,invalid_tool_calls:n}}const zc=Symbol.for("ls:tracing_async_local_storage"),ur=Symbol.for("lc:context_variables"),Ad=t=>{globalThis[zc]=t},vr=()=>globalThis[zc];var $d={},Rd={};ge(Rd,{getEnv:()=>Vc,getEnvironmentVariable:()=>It,getRuntimeEnvironment:()=>Wc,isBrowser:()=>qc,isDeno:()=>_n,isJsDom:()=>Hc,isNode:()=>Zc,isWebWorker:()=>Gc});const qc=()=>typeof window<"u"&&typeof window.document<"u",Gc=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Hc=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),_n=()=>typeof Deno<"u",Zc=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!_n(),Vc=()=>{let t;return qc()?t="browser":Zc()?t="node":Gc()?t="webworker":Hc()?t="jsdom":_n()?t="deno":t="other",t};let kn;function Wc(){return kn===void 0&&(kn={library:"langchain-js",runtime:Vc()}),kn}function It(t){try{return typeof process<"u"?$d?.[t]:_n()?Deno?.env.get(t):void 0}catch{return}}const Od=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function lr(t){return typeof t=="string"&&Od.test(t)}function kd(t){if(!lr(t))throw TypeError("Invalid UUID");var e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}var _e=[];for(var Cn=0;Cn<256;++Cn)_e.push((Cn+256).toString(16).slice(1));function Ns(t,e=0){return(_e[t[e+0]]+_e[t[e+1]]+_e[t[e+2]]+_e[t[e+3]]+"-"+_e[t[e+4]]+_e[t[e+5]]+"-"+_e[t[e+6]]+_e[t[e+7]]+"-"+_e[t[e+8]]+_e[t[e+9]]+"-"+_e[t[e+10]]+_e[t[e+11]]+_e[t[e+12]]+_e[t[e+13]]+_e[t[e+14]]+_e[t[e+15]]).toLowerCase()}var Ur,Cd=new Uint8Array(16);function Jc(){if(!Ur&&(Ur=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Ur))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ur(Cd)}function Nd(t){t=unescape(encodeURIComponent(t));for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var Pd="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Ld="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Md(t,e,r){function n(a,s,i,o){var c;if(typeof a=="string"&&(a=Nd(a)),typeof s=="string"&&(s=kd(s)),((c=s)===null||c===void 0?void 0:c.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var u=new Uint8Array(16+a.length);if(u.set(s),u.set(a,s.length),u=r(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,i){o=o||0;for(var l=0;l<16;++l)i[o+l]=u[l];return i}return Ns(u)}try{n.name=t}catch{}return n.DNS=Pd,n.URL=Ld,n}var jd=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const bi={randomUUID:jd};function Tt(t,e,r){if(bi.randomUUID&&!t)return bi.randomUUID();t=t||{};var n=t.random||(t.rng||Jc)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,Ns(n)}function Dd(t,e,r,n){switch(t){case 0:return e&r^~e&n;case 1:return e^r^n;case 2:return e&r^e&n^r&n;case 3:return e^r^n}}function Nn(t,e){return t<<e|t>>>32-e}function Ud(t){var e=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof t=="string"){var n=unescape(encodeURIComponent(t));t=[];for(var a=0;a<n.length;++a)t.push(n.charCodeAt(a))}else Array.isArray(t)||(t=Array.prototype.slice.call(t));t.push(128);for(var s=t.length/4+2,i=Math.ceil(s/16),o=new Array(i),c=0;c<i;++c){for(var u=new Uint32Array(16),l=0;l<16;++l)u[l]=t[c*64+l*4]<<24|t[c*64+l*4+1]<<16|t[c*64+l*4+2]<<8|t[c*64+l*4+3];o[c]=u}o[i-1][14]=(t.length-1)*8/Math.pow(2,32),o[i-1][14]=Math.floor(o[i-1][14]),o[i-1][15]=(t.length-1)*8&4294967295;for(var d=0;d<i;++d){for(var f=new Uint32Array(80),h=0;h<16;++h)f[h]=o[d][h];for(var p=16;p<80;++p)f[p]=Nn(f[p-3]^f[p-8]^f[p-14]^f[p-16],1);for(var m=r[0],g=r[1],y=r[2],v=r[3],_=r[4],S=0;S<80;++S){var R=Math.floor(S/20),U=Nn(m,5)+Dd(R,g,y,v)+_+e[R]+f[S]>>>0;_=v,v=y,y=Nn(g,30)>>>0,g=m,m=U}r[0]=r[0]+m>>>0,r[1]=r[1]+g>>>0,r[2]=r[2]+y>>>0,r[3]=r[3]+v>>>0,r[4]=r[4]+_>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,r[0]&255,r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,r[1]&255,r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,r[2]&255,r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,r[3]&255,r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,r[4]&255]}var ar=Md("v5",80,Ud),Ei=null,Si=null,De=0;function mt(t,e,r){t=t||{};var n=0,a=new Uint8Array(16),s=t.random||(t.rng||Jc)(),i=t.msecs!==void 0?t.msecs:Date.now(),o=t.seq!==void 0?t.seq:null,c=Si,u=Ei;return i>De&&t.msecs===void 0&&(De=i,o!==null&&(c=null,u=null)),o!==null&&(o>2147483647&&(o=2147483647),c=o>>>19&4095,u=o&524287),(c===null||u===null)&&(c=s[6]&127,c=c<<8|s[7],u=s[8]&63,u=u<<8|s[9],u=u<<5|s[10]>>>3),i+1e4>De&&o===null?++u>524287&&(u=0,++c>4095&&(c=0,De++)):De=i,Si=c,Ei=u,a[n++]=De/1099511627776&255,a[n++]=De/4294967296&255,a[n++]=De/16777216&255,a[n++]=De/65536&255,a[n++]=De/256&255,a[n++]=De&255,a[n++]=c>>>4&15|112,a[n++]=c&255,a[n++]=u>>>13&63|128,a[n++]=u>>>5&255,a[n++]=u<<3&255|s[10]&7,a[n++]=s[11],a[n++]=s[12],a[n++]=s[13],a[n++]=s[14],a[n++]=s[15],Ns(a)}var Fd={};ge(Fd,{BaseCallbackHandler:()=>Rr,callbackHandlerPrefersStreaming:()=>zd,isBaseCallbackHandler:()=>Kc});var Bd=class{};function zd(t){return"lc_prefer_streaming"in t&&t.lc_prefer_streaming}var Rr=class extends Bd{lc_serializable=!1;get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,gs(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=It("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(t){super(),this.lc_kwargs=t||{},t&&(this.ignoreLLM=t.ignoreLLM??this.ignoreLLM,this.ignoreChain=t.ignoreChain??this.ignoreChain,this.ignoreAgent=t.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=t.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=t.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=t.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(t._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return gr.prototype.toJSON.call(this)}toJSONNotImplemented(){return gr.prototype.toJSONNotImplemented.call(this)}static fromMethods(t){class e extends Rr{name=mt();constructor(){super(),Object.assign(this,t)}}return new e}};const Kc=t=>{const e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},qd="gen_ai.operation.name",Gd="gen_ai.system",Ti="gen_ai.request.model",Hd="gen_ai.response.model",xi="gen_ai.usage.input_tokens",Ii="gen_ai.usage.output_tokens",Ai="gen_ai.usage.total_tokens",Zd="gen_ai.request.max_tokens",Vd="gen_ai.request.temperature",Wd="gen_ai.request.top_p",Jd="gen_ai.request.frequency_penalty",Kd="gen_ai.request.presence_penalty",Yd="gen_ai.response.finish_reasons",Qd="gen_ai.prompt",Xd="gen_ai.completion",ef="gen_ai.request.extra_query",tf="gen_ai.request.extra_body",rf="gen_ai.serialized.name",nf="gen_ai.serialized.signature",af="gen_ai.serialized.doc",sf="gen_ai.response.id",of="gen_ai.response.service_tier",cf="gen_ai.response.system_fingerprint",uf="gen_ai.usage.input_token_details",lf="gen_ai.usage.output_token_details",df="langsmith.trace.session_id",ff="langsmith.trace.session_name",hf="langsmith.span.kind",pf="langsmith.trace.name",mf="langsmith.metadata",$i="langsmith.span.tags",gf="langsmith.request.streaming",yf="langsmith.request.headers",_f=(...t)=>fetch(...t),Yc=Symbol.for("ls:fetch_implementation"),vf=()=>{const t=globalThis[Yc];return t?typeof t=="function"&&"Headers"in t&&"Request"in t&&"Response"in t:!1},wf=t=>async(...e)=>{if(t||Re("DEBUG")==="true"){const[n,a]=e;console.log(`→ ${a?.method||"GET"} ${n}`)}const r=await(globalThis[Yc]??_f)(...e);return(t||Re("DEBUG")==="true")&&console.log(`← ${r.status} ${r.statusText} ${r.url}`),r},Qc=()=>Re("PROJECT")??et("LANGCHAIN_SESSION")??"default",Ri={};function Ja(t){Ri[t]||(console.warn(t),Ri[t]=!0)}const bf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function J(t,e){if(!bf.test(t)){const r=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(r)}return t}function Ef(t){const e=typeof t=="string"?Date.parse(t):t;return mt({msecs:e,seq:0})}const Xc="0.3.87";var Ka={};let We;const Sf=()=>typeof window<"u"&&typeof window.document<"u",Tf=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",xf=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),eu=()=>typeof Deno<"u",If=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!eu(),tu=()=>We||(typeof Bun<"u"?We="bun":Sf()?We="browser":If()?We="node":Tf()?We="webworker":xf()?We="jsdom":eu()?We="deno":We="other",We);let Pn;function ru(){if(Pn===void 0){const t=tu(),e=$f();Pn={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:Xc,...e}}return Pn}function nu(){const t=Af(),e={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[n,a]of Object.entries(t))typeof a=="string"&&!r.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?e.revision_id=a:e[n]=a);return e}function Af(){const t={};try{if(typeof process<"u"&&Ka)for(const[e,r]of Object.entries(Ka))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&r!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof r=="string"?t[e]=r.slice(0,2)+"*".repeat(r.length-4)+r.slice(-2):t[e]=r)}catch{}return t}function et(t){try{return typeof process<"u"?Ka?.[t]:void 0}catch{return}}function Re(t){return et(`LANGSMITH_${t}`)||et(`LANGCHAIN_${t}`)}let Ln;function $f(){if(Ln!==void 0)return Ln;const t=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(const r of t){const n=et(r);n!==void 0&&(e[r]=n)}return Ln=e,e}function au(){return et("OTEL_ENABLED")==="true"||Re("OTEL_ENABLED")==="true"}class Rf{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...r){!this.hasWarned&&au()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let n;if(r.length===1&&typeof r[0]=="function"?n=r[0]:r.length===2&&typeof r[1]=="function"?n=r[1]:r.length===3&&typeof r[2]=="function"&&(n=r[2]),typeof n=="function")return n()}}class Of{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new Rf})}getTracer(e,r){return this.mockTracer}getActiveSpan(){}setSpan(e,r){return e}getSpan(e){}setSpanContext(e,r){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}}class kf{active(){return{}}with(e,r){return r()}}const Mn=Symbol.for("ls:otel_trace"),jn=Symbol.for("ls:otel_context"),Oi=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),Cf=new Of,Nf=new kf;class Pf{getTraceInstance(){return globalThis[Mn]??Cf}getContextInstance(){return globalThis[jn]??Nf}initializeGlobalInstances(e){globalThis[Mn]===void 0&&(globalThis[Mn]=e.trace),globalThis[jn]===void 0&&(globalThis[jn]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[Oi]=e}getDefaultOTLPTracerComponents(){return globalThis[Oi]??void 0}}const Ps=new Pf;function su(){return Ps.getTraceInstance()}function Lf(){return Ps.getContextInstance()}function Mf(){return Ps.getDefaultOTLPTracerComponents()}const jf={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function Df(t){return jf[t]||t}class Uf{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,r){for(const n of e)try{if(!n.run)continue;if(n.operation==="post"){const a=this.createSpanForRun(n,n.run,r.get(n.id));a&&!n.run.end_time&&this.spans.set(n.id,a)}else this.updateSpanForRun(n,n.run)}catch(a){console.error(`Error processing operation ${n.id}:`,a)}}createSpanForRun(e,r,n){const a=n&&su().getSpan(n);if(a)try{return this.finishSpanSetup(a,r,e)}catch(s){console.error(`Failed to create span for run ${e.id}:`,s);return}}finishSpanSetup(e,r,n){return this.setSpanAttributes(e,r,n),r.error?(e.setStatus({code:2}),e.recordException(new Error(r.error))):e.setStatus({code:1}),r.end_time&&e.end(new Date(r.end_time)),e}updateSpanForRun(e,r){try{const n=this.spans.get(e.id);if(!n){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(n,r,e),r.error?(n.setStatus({code:2}),n.recordException(new Error(r.error))):n.setStatus({code:1});const a=r.end_time;a&&(n.end(new Date(a)),this.spans.delete(e.id))}catch(n){console.error(`Failed to update span for run ${e.id}:`,n)}}extractModelName(e){if(e.extra?.metadata){const r=e.extra.metadata;if(r.ls_model_name)return r.ls_model_name;if(r.invocation_params){const n=r.invocation_params;if(n.model)return n.model;if(n.model_name)return n.model_name}}}setSpanAttributes(e,r,n){if("run_type"in r&&r.run_type){e.setAttribute(hf,r.run_type);const o=Df(r.run_type||"chain");e.setAttribute(qd,o)}"name"in r&&r.name&&e.setAttribute(pf,r.name),"session_id"in r&&r.session_id&&e.setAttribute(df,r.session_id),"session_name"in r&&r.session_name&&e.setAttribute(ff,r.session_name),this.setGenAiSystem(e,r);const a=this.extractModelName(r);a&&e.setAttribute(Ti,a),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&e.setAttribute(xi,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&e.setAttribute(Ii,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&e.setAttribute(Ai,r.total_tokens),this.setInvocationParameters(e,r);const s=r.extra?.metadata||{};for(const[o,c]of Object.entries(s))c!=null&&e.setAttribute(`${mf}.${o}`,String(c));const i=r.tags;if(i&&Array.isArray(i)?e.setAttribute($i,i.join(", ")):i&&e.setAttribute($i,String(i)),"serialized"in r&&typeof r.serialized=="object"){const o=r.serialized;o.name&&e.setAttribute(rf,String(o.name)),o.signature&&e.setAttribute(nf,String(o.signature)),o.doc&&e.setAttribute(af,String(o.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,r){let n="langchain";const a=this.extractModelName(r);if(a){const s=a.toLowerCase();s.includes("anthropic")||s.startsWith("claude")?n="anthropic":s.includes("bedrock")?n="aws.bedrock":s.includes("azure")&&s.includes("openai")?n="az.ai.openai":s.includes("azure")&&s.includes("inference")?n="az.ai.inference":s.includes("cohere")?n="cohere":s.includes("deepseek")?n="deepseek":s.includes("gemini")?n="gemini":s.includes("groq")?n="groq":s.includes("watson")||s.includes("ibm")?n="ibm.watsonx.ai":s.includes("mistral")?n="mistral_ai":s.includes("gpt")||s.includes("openai")?n="openai":s.includes("perplexity")||s.includes("sonar")?n="perplexity":s.includes("vertex")?n="vertex_ai":(s.includes("xai")||s.includes("grok"))&&(n="xai")}e.setAttribute(Gd,n)}setInvocationParameters(e,r){if(!r.extra?.metadata?.invocation_params)return;const n=r.extra.metadata.invocation_params;n.max_tokens!==void 0&&e.setAttribute(Zd,n.max_tokens),n.temperature!==void 0&&e.setAttribute(Vd,n.temperature),n.top_p!==void 0&&e.setAttribute(Wd,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(Jd,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(Kd,n.presence_penalty)}setIOAttributes(e,r){if(r.run.inputs)try{const n=r.run.inputs;typeof n=="object"&&n!==null&&(n.model&&Array.isArray(n.messages)&&e.setAttribute(Ti,n.model),n.stream!==void 0&&e.setAttribute(gf,n.stream),n.extra_headers&&e.setAttribute(yf,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(ef,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(tf,JSON.stringify(n.extra_body))),e.setAttribute(Qd,JSON.stringify(n))}catch(n){console.debug(`Failed to process inputs for run ${r.id}`,n)}if(r.run.outputs)try{const n=r.run.outputs,a=this.getUnifiedRunTokens(n);if(a&&(e.setAttribute(xi,a[0]),e.setAttribute(Ii,a[1]),e.setAttribute(Ai,a[0]+a[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(Hd,String(n.model)),n.id&&e.setAttribute(sf,n.id),n.choices&&Array.isArray(n.choices)){const s=n.choices.map(i=>i.finish_reason).filter(i=>i).map(String);s.length>0&&e.setAttribute(Yd,s.join(", "))}if(n.service_tier&&e.setAttribute(of,n.service_tier),n.system_fingerprint&&e.setAttribute(cf,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){const s=n.usage_metadata;s.input_token_details&&e.setAttribute(uf,JSON.stringify(s.input_token_details)),s.output_token_details&&e.setAttribute(lf,JSON.stringify(s.output_token_details))}}e.setAttribute(Xd,JSON.stringify(n))}catch(n){console.debug(`Failed to process outputs for run ${r.id}`,n)}}getUnifiedRunTokens(e){if(!e)return null;let r=this.extractUnifiedRunTokens(e.usage_metadata);if(r)return r;const n=Object.keys(e);for(const i of n){const o=e[i];if(!(!o||typeof o!="object")&&(r=this.extractUnifiedRunTokens(o.usage_metadata),r||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(r=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),r)))return r}const a=e.generations||[];if(!Array.isArray(a))return null;const s=Array.isArray(a[0])?a.flat():a;for(const i of s)if(typeof i=="object"&&i.message&&typeof i.message=="object"&&i.message.kwargs&&typeof i.message.kwargs=="object"&&(r=this.extractUnifiedRunTokens(i.message.kwargs.usage_metadata),r))return r;return null}extractUnifiedRunTokens(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}}const Ff=Object.prototype.toString,Bf=t=>Ff.call(t)==="[object Error]",zf=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function qf(t){if(!(t&&Bf(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;const{message:r,stack:n}=t;return r==="Load failed"?n===void 0||"__sentry_captured__"in t:r.startsWith("error sending request for url")?!0:zf.has(r)}function Gf(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Fr(t,e,{min:r=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<r)throw new TypeError(`Expected \`${t}\` to be ≥ ${r}.`)}}let Hf=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function Zf(t,e){const r=Math.max(1,t+1),n=e.randomize?Math.random()+1:1;let a=Math.round(n*e.minTimeout*e.factor**(r-1));return a=Math.min(a,e.maxTimeout),a}function ki(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}async function Vf({error:t,attemptNumber:e,retriesConsumed:r,startTime:n,options:a}){const s=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(s instanceof Hf)throw s.originalError;const i=Number.isFinite(a.retries)?Math.max(0,a.retries-r):a.retries,o=a.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:r});if(await a.onFailedAttempt(c),ki(n,o)<=0)throw s;const u=await a.shouldConsumeRetry(c),l=ki(n,o);if(l<=0||i<=0)throw s;if(s instanceof TypeError&&!qf(s)){if(u)throw s;return a.signal?.throwIfAborted(),!1}if(!await a.shouldRetry(c))throw s;if(!u)return a.signal?.throwIfAborted(),!1;const d=Zf(r,a),f=Math.min(d,l);return f>0&&await new Promise((h,p)=>{const m=()=>{clearTimeout(g),a.signal?.removeEventListener("abort",m),p(a.signal.reason)},g=setTimeout(()=>{a.signal?.removeEventListener("abort",m),h()},f);a.unref&&g.unref?.(),a.signal?.addEventListener("abort",m,{once:!0})}),a.signal?.throwIfAborted(),!0}async function Wf(t,e={}){if(e={...e},Gf(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,Fr("factor",e.factor,{min:0,allowInfinity:!1}),Fr("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Fr("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Fr("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let r=0,n=0;const a=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){r++;try{e.signal?.throwIfAborted();const s=await t(r);return e.signal?.throwIfAborted(),s}catch(s){await Vf({error:s,attemptNumber:r,retriesConsumed:n,startTime:a,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Br={},Dn={exports:{}},Ci;function Jf(){return Ci||(Ci=1,(function(t){var e=Object.prototype.hasOwnProperty,r="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1));function a(c,u,l){this.fn=c,this.context=u,this.once=l||!1}function s(c,u,l,d,f){if(typeof l!="function")throw new TypeError("The listener must be a function");var h=new a(l,d||c,f),p=r?r+u:u;return c._events[p]?c._events[p].fn?c._events[p]=[c._events[p],h]:c._events[p].push(h):(c._events[p]=h,c._eventsCount++),c}function i(c,u){--c._eventsCount===0?c._events=new n:delete c._events[u]}function o(){this._events=new n,this._eventsCount=0}o.prototype.eventNames=function(){var u=[],l,d;if(this._eventsCount===0)return u;for(d in l=this._events)e.call(l,d)&&u.push(r?d.slice(1):d);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(l)):u},o.prototype.listeners=function(u){var l=r?r+u:u,d=this._events[l];if(!d)return[];if(d.fn)return[d.fn];for(var f=0,h=d.length,p=new Array(h);f<h;f++)p[f]=d[f].fn;return p},o.prototype.listenerCount=function(u){var l=r?r+u:u,d=this._events[l];return d?d.fn?1:d.length:0},o.prototype.emit=function(u,l,d,f,h,p){var m=r?r+u:u;if(!this._events[m])return!1;var g=this._events[m],y=arguments.length,v,_;if(g.fn){switch(g.once&&this.removeListener(u,g.fn,void 0,!0),y){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,l),!0;case 3:return g.fn.call(g.context,l,d),!0;case 4:return g.fn.call(g.context,l,d,f),!0;case 5:return g.fn.call(g.context,l,d,f,h),!0;case 6:return g.fn.call(g.context,l,d,f,h,p),!0}for(_=1,v=new Array(y-1);_<y;_++)v[_-1]=arguments[_];g.fn.apply(g.context,v)}else{var S=g.length,R;for(_=0;_<S;_++)switch(g[_].once&&this.removeListener(u,g[_].fn,void 0,!0),y){case 1:g[_].fn.call(g[_].context);break;case 2:g[_].fn.call(g[_].context,l);break;case 3:g[_].fn.call(g[_].context,l,d);break;case 4:g[_].fn.call(g[_].context,l,d,f);break;default:if(!v)for(R=1,v=new Array(y-1);R<y;R++)v[R-1]=arguments[R];g[_].fn.apply(g[_].context,v)}}return!0},o.prototype.on=function(u,l,d){return s(this,u,l,d,!1)},o.prototype.once=function(u,l,d){return s(this,u,l,d,!0)},o.prototype.removeListener=function(u,l,d,f){var h=r?r+u:u;if(!this._events[h])return this;if(!l)return i(this,h),this;var p=this._events[h];if(p.fn)p.fn===l&&(!f||p.once)&&(!d||p.context===d)&&i(this,h);else{for(var m=0,g=[],y=p.length;m<y;m++)(p[m].fn!==l||f&&!p[m].once||d&&p[m].context!==d)&&g.push(p[m]);g.length?this._events[h]=g.length===1?g[0]:g:i(this,h)}return this},o.prototype.removeAllListeners=function(u){var l;return u?(l=r?r+u:u,this._events[l]&&i(this,l)):(this._events=new n,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,t.exports=o})(Dn)),Dn.exports}var rr={exports:{}},Un,Ni;function Kf(){return Ni||(Ni=1,Un=(t,e)=>(e=e||(()=>{}),t.then(r=>new Promise(n=>{n(e())}).then(()=>r),r=>new Promise(n=>{n(e())}).then(()=>{throw r})))),Un}var Pi;function Yf(){if(Pi)return rr.exports;Pi=1;const t=Kf();class e extends Error{constructor(a){super(a),this.name="TimeoutError"}}const r=(n,a,s)=>new Promise((i,o)=>{if(typeof a!="number"||a<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(a===1/0){i(n);return}const c=setTimeout(()=>{if(typeof s=="function"){try{i(s())}catch(d){o(d)}return}const u=typeof s=="string"?s:`Promise timed out after ${a} milliseconds`,l=s instanceof Error?s:new e(u);typeof n.cancel=="function"&&n.cancel(),o(l)},a);t(n.then(i,o),()=>{clearTimeout(c)})});return rr.exports=r,rr.exports.default=r,rr.exports.TimeoutError=e,rr.exports}var zr={},qr={},Li;function Qf(){if(Li)return qr;Li=1,Object.defineProperty(qr,"__esModule",{value:!0});function t(e,r,n){let a=0,s=e.length;for(;s>0;){const i=s/2|0;let o=a+i;n(e[o],r)<=0?(a=++o,s-=i+1):s=i}return a}return qr.default=t,qr}var Mi;function Xf(){if(Mi)return zr;Mi=1,Object.defineProperty(zr,"__esModule",{value:!0});const t=Qf();class e{constructor(){this._queue=[]}enqueue(n,a){a=Object.assign({priority:0},a);const s={priority:a.priority,run:n};if(this.size&&this._queue[this.size-1].priority>=a.priority){this._queue.push(s);return}const i=t.default(this._queue,s,(o,c)=>c.priority-o.priority);this._queue.splice(i,0,s)}dequeue(){const n=this._queue.shift();return n?.run}filter(n){return this._queue.filter(a=>a.priority===n.priority).map(a=>a.run)}get size(){return this._queue.length}}return zr.default=e,zr}var ji;function eh(){if(ji)return Br;ji=1,Object.defineProperty(Br,"__esModule",{value:!0});const t=Jf(),e=Yf(),r=Xf(),n=()=>{},a=new e.TimeoutError;class s extends t{constructor(o){var c,u,l,d;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=n,this._resolveIdle=n,o=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:r.default},o),!(typeof o.intervalCap=="number"&&o.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(u=(c=o.intervalCap)===null||c===void 0?void 0:c.toString())!==null&&u!==void 0?u:""}\` (${typeof o.intervalCap})`);if(o.interval===void 0||!(Number.isFinite(o.interval)&&o.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(d=(l=o.interval)===null||l===void 0?void 0:l.toString())!==null&&d!==void 0?d:""}\` (${typeof o.interval})`);this._carryoverConcurrencyCount=o.carryoverConcurrencyCount,this._isIntervalIgnored=o.intervalCap===1/0||o.interval===0,this._intervalCap=o.intervalCap,this._interval=o.interval,this._queue=new o.queueClass,this._queueClass=o.queueClass,this.concurrency=o.concurrency,this._timeout=o.timeout,this._throwOnTimeout=o.throwOnTimeout===!0,this._isPaused=o.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=n,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=n,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const o=Date.now();if(this._intervalId===void 0){const c=this._intervalEnd-o;if(c<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},c)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const o=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const c=this._queue.dequeue();return c?(this.emit("active"),c(),o&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(o){if(!(typeof o=="number"&&o>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${o}\` (${typeof o})`);this._concurrency=o,this._processQueue()}async add(o,c={}){return new Promise((u,l)=>{const d=async()=>{this._pendingCount++,this._intervalCount++;try{const f=this._timeout===void 0&&c.timeout===void 0?o():e.default(Promise.resolve(o()),c.timeout===void 0?this._timeout:c.timeout,()=>{(c.throwOnTimeout===void 0?this._throwOnTimeout:c.throwOnTimeout)&&l(a)});u(await f)}catch(f){l(f)}this._next()};this._queue.enqueue(d,c),this._tryToStartAnother(),this.emit("add")})}async addAll(o,c){return Promise.all(o.map(async u=>this.add(u,c)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(o=>{const c=this._resolveEmpty;this._resolveEmpty=()=>{c(),o()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(o=>{const c=this._resolveIdle;this._resolveIdle=()=>{c(),o()}})}get size(){return this._queue.size}sizeBy(o){return this._queue.filter(o).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(o){this._timeout=o}}return Br.default=s,Br}var th=eh();const st=gn(th),rh=[408,425,429,500,502,503,504];let Di=class{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxQueueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.maxQueueSizeBytes=e.maxQueueSizeBytes,"default"in st?this.queue=new st.default({concurrency:this.maxConcurrency}):this.queue=new st({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...r){return this.callWithOptions({},e,...r)}callWithOptions(e,r,...n){const a=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&a>0&&this.queueSizeBytes+a>this.maxQueueSizeBytes)return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${a} bytes.`));a>0&&(this.queueSizeBytes+=a);const s=this.onFailedResponseHook;let i=this.queue.add(()=>Wf(()=>r(...n).catch(o=>{throw o instanceof Error?o:new Error(o)}),{async onFailedAttempt({error:o}){if(o.message.startsWith("Cancel")||o.message.startsWith("TimeoutError")||o.name==="TimeoutError"||o.message.startsWith("AbortError")||o?.code==="ECONNABORTED")throw o;const c=o?.response;if(s&&await s(c))return;const u=c?.status??o?.status;if(u&&!rh.includes(+u))throw o},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return a>0&&(i=i.finally(()=>{this.queueSizeBytes-=a})),e.signal?Promise.race([i,new Promise((o,c)=>{e.signal?.addEventListener("abort",()=>{c(new Error("AbortError"))})})]):i}};function Ui(t){return typeof t?._getType=="function"}function Fi(t){const e={type:t._getType(),data:{content:t.content}};return t?.additional_kwargs&&Object.keys(t.additional_kwargs).length>0&&(e.data.additional_kwargs={...t.additional_kwargs}),e}var Gr={exports:{}},Fn,Bi;function vn(){if(Bi)return Fn;Bi=1;const t="2.0.0",e=256,r=Number.MAX_SAFE_INTEGER||9007199254740991,n=16,a=e-6;return Fn={MAX_LENGTH:e,MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:a,MAX_SAFE_INTEGER:r,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:t,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},Fn}var Bn,zi;function wn(){if(zi)return Bn;zi=1;var t={};return Bn=typeof process=="object"&&t&&t.NODE_DEBUG&&/\bsemver\b/i.test(t.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{},Bn}var qi;function Or(){return qi||(qi=1,(function(t,e){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:a}=vn(),s=wn();e=t.exports={};const i=e.re=[],o=e.safeRe=[],c=e.src=[],u=e.safeSrc=[],l=e.t={};let d=0;const f="[a-zA-Z0-9-]",h=[["\\s",1],["\\d",a],[f,n]],p=g=>{for(const[y,v]of h)g=g.split(`${y}*`).join(`${y}{0,${v}}`).split(`${y}+`).join(`${y}{1,${v}}`);return g},m=(g,y,v)=>{const _=p(y),S=d++;s(g,S,y),l[g]=S,c[S]=y,u[S]=_,i[S]=new RegExp(y,v?"g":void 0),o[S]=new RegExp(_,v?"g":void 0)};m("NUMERICIDENTIFIER","0|[1-9]\\d*"),m("NUMERICIDENTIFIERLOOSE","\\d+"),m("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${f}*`),m("MAINVERSION",`(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})`),m("MAINVERSIONLOOSE",`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASEIDENTIFIER",`(?:${c[l.NONNUMERICIDENTIFIER]}|${c[l.NUMERICIDENTIFIER]})`),m("PRERELEASEIDENTIFIERLOOSE",`(?:${c[l.NONNUMERICIDENTIFIER]}|${c[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASE",`(?:-(${c[l.PRERELEASEIDENTIFIER]}(?:\\.${c[l.PRERELEASEIDENTIFIER]})*))`),m("PRERELEASELOOSE",`(?:-?(${c[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[l.PRERELEASEIDENTIFIERLOOSE]})*))`),m("BUILDIDENTIFIER",`${f}+`),m("BUILD",`(?:\\+(${c[l.BUILDIDENTIFIER]}(?:\\.${c[l.BUILDIDENTIFIER]})*))`),m("FULLPLAIN",`v?${c[l.MAINVERSION]}${c[l.PRERELEASE]}?${c[l.BUILD]}?`),m("FULL",`^${c[l.FULLPLAIN]}$`),m("LOOSEPLAIN",`[v=\\s]*${c[l.MAINVERSIONLOOSE]}${c[l.PRERELEASELOOSE]}?${c[l.BUILD]}?`),m("LOOSE",`^${c[l.LOOSEPLAIN]}$`),m("GTLT","((?:<|>)?=?)"),m("XRANGEIDENTIFIERLOOSE",`${c[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),m("XRANGEIDENTIFIER",`${c[l.NUMERICIDENTIFIER]}|x|X|\\*`),m("XRANGEPLAIN",`[v=\\s]*(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:${c[l.PRERELEASE]})?${c[l.BUILD]}?)?)?`),m("XRANGEPLAINLOOSE",`[v=\\s]*(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:${c[l.PRERELEASELOOSE]})?${c[l.BUILD]}?)?)?`),m("XRANGE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAIN]}$`),m("XRANGELOOSE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAINLOOSE]}$`),m("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),m("COERCE",`${c[l.COERCEPLAIN]}(?:$|[^\\d])`),m("COERCEFULL",c[l.COERCEPLAIN]+`(?:${c[l.PRERELEASE]})?(?:${c[l.BUILD]})?(?:$|[^\\d])`),m("COERCERTL",c[l.COERCE],!0),m("COERCERTLFULL",c[l.COERCEFULL],!0),m("LONETILDE","(?:~>?)"),m("TILDETRIM",`(\\s*)${c[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",m("TILDE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAIN]}$`),m("TILDELOOSE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAINLOOSE]}$`),m("LONECARET","(?:\\^)"),m("CARETTRIM",`(\\s*)${c[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",m("CARET",`^${c[l.LONECARET]}${c[l.XRANGEPLAIN]}$`),m("CARETLOOSE",`^${c[l.LONECARET]}${c[l.XRANGEPLAINLOOSE]}$`),m("COMPARATORLOOSE",`^${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]})$|^$`),m("COMPARATOR",`^${c[l.GTLT]}\\s*(${c[l.FULLPLAIN]})$|^$`),m("COMPARATORTRIM",`(\\s*)${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]}|${c[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",m("HYPHENRANGE",`^\\s*(${c[l.XRANGEPLAIN]})\\s+-\\s+(${c[l.XRANGEPLAIN]})\\s*$`),m("HYPHENRANGELOOSE",`^\\s*(${c[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[l.XRANGEPLAINLOOSE]})\\s*$`),m("STAR","(<|>)?=?\\s*\\*"),m("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),m("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(Gr,Gr.exports)),Gr.exports}var zn,Gi;function Ls(){if(Gi)return zn;Gi=1;const t=Object.freeze({loose:!0}),e=Object.freeze({});return zn=n=>n?typeof n!="object"?t:n:e,zn}var qn,Hi;function iu(){if(Hi)return qn;Hi=1;const t=/^[0-9]+$/,e=(n,a)=>{if(typeof n=="number"&&typeof a=="number")return n===a?0:n<a?-1:1;const s=t.test(n),i=t.test(a);return s&&i&&(n=+n,a=+a),n===a?0:s&&!i?-1:i&&!s?1:n<a?-1:1};return qn={compareIdentifiers:e,rcompareIdentifiers:(n,a)=>e(a,n)},qn}var Gn,Zi;function xe(){if(Zi)return Gn;Zi=1;const t=wn(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:r}=vn(),{safeRe:n,t:a}=Or(),s=Ls(),{compareIdentifiers:i}=iu();class o{constructor(u,l){if(l=s(l),u instanceof o){if(u.loose===!!l.loose&&u.includePrerelease===!!l.includePrerelease)return u;u=u.version}else if(typeof u!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof u}".`);if(u.length>e)throw new TypeError(`version is longer than ${e} characters`);t("SemVer",u,l),this.options=l,this.loose=!!l.loose,this.includePrerelease=!!l.includePrerelease;const d=u.trim().match(l.loose?n[a.LOOSE]:n[a.FULL]);if(!d)throw new TypeError(`Invalid Version: ${u}`);if(this.raw=u,this.major=+d[1],this.minor=+d[2],this.patch=+d[3],this.major>r||this.major<0)throw new TypeError("Invalid major version");if(this.minor>r||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>r||this.patch<0)throw new TypeError("Invalid patch version");d[4]?this.prerelease=d[4].split(".").map(f=>{if(/^[0-9]+$/.test(f)){const h=+f;if(h>=0&&h<r)return h}return f}):this.prerelease=[],this.build=d[5]?d[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(u){if(t("SemVer.compare",this.version,this.options,u),!(u instanceof o)){if(typeof u=="string"&&u===this.version)return 0;u=new o(u,this.options)}return u.version===this.version?0:this.compareMain(u)||this.comparePre(u)}compareMain(u){return u instanceof o||(u=new o(u,this.options)),this.major<u.major?-1:this.major>u.major?1:this.minor<u.minor?-1:this.minor>u.minor?1:this.patch<u.patch?-1:this.patch>u.patch?1:0}comparePre(u){if(u instanceof o||(u=new o(u,this.options)),this.prerelease.length&&!u.prerelease.length)return-1;if(!this.prerelease.length&&u.prerelease.length)return 1;if(!this.prerelease.length&&!u.prerelease.length)return 0;let l=0;do{const d=this.prerelease[l],f=u.prerelease[l];if(t("prerelease compare",l,d,f),d===void 0&&f===void 0)return 0;if(f===void 0)return 1;if(d===void 0)return-1;if(d===f)continue;return i(d,f)}while(++l)}compareBuild(u){u instanceof o||(u=new o(u,this.options));let l=0;do{const d=this.build[l],f=u.build[l];if(t("build compare",l,d,f),d===void 0&&f===void 0)return 0;if(f===void 0)return 1;if(d===void 0)return-1;if(d===f)continue;return i(d,f)}while(++l)}inc(u,l,d){if(u.startsWith("pre")){if(!l&&d===!1)throw new Error("invalid increment argument: identifier is empty");if(l){const f=`-${l}`.match(this.options.loose?n[a.PRERELEASELOOSE]:n[a.PRERELEASE]);if(!f||f[1]!==l)throw new Error(`invalid identifier: ${l}`)}}switch(u){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",l,d);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",l,d);break;case"prepatch":this.prerelease.length=0,this.inc("patch",l,d),this.inc("pre",l,d);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",l,d),this.inc("pre",l,d);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const f=Number(d)?1:0;if(this.prerelease.length===0)this.prerelease=[f];else{let h=this.prerelease.length;for(;--h>=0;)typeof this.prerelease[h]=="number"&&(this.prerelease[h]++,h=-2);if(h===-1){if(l===this.prerelease.join(".")&&d===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(f)}}if(l){let h=[l,f];d===!1&&(h=[l]),i(this.prerelease[0],l)===0?isNaN(this.prerelease[1])&&(this.prerelease=h):this.prerelease=h}break}default:throw new Error(`invalid increment argument: ${u}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return Gn=o,Gn}var Hn,Vi;function Qt(){if(Vi)return Hn;Vi=1;const t=xe();return Hn=(r,n,a=!1)=>{if(r instanceof t)return r;try{return new t(r,n)}catch(s){if(!a)return null;throw s}},Hn}var Zn,Wi;function nh(){if(Wi)return Zn;Wi=1;const t=Qt();return Zn=(r,n)=>{const a=t(r,n);return a?a.version:null},Zn}var Vn,Ji;function ah(){if(Ji)return Vn;Ji=1;const t=Qt();return Vn=(r,n)=>{const a=t(r.trim().replace(/^[=v]+/,""),n);return a?a.version:null},Vn}var Wn,Ki;function sh(){if(Ki)return Wn;Ki=1;const t=xe();return Wn=(r,n,a,s,i)=>{typeof a=="string"&&(i=s,s=a,a=void 0);try{return new t(r instanceof t?r.version:r,a).inc(n,s,i).version}catch{return null}},Wn}var Jn,Yi;function ih(){if(Yi)return Jn;Yi=1;const t=Qt();return Jn=(r,n)=>{const a=t(r,null,!0),s=t(n,null,!0),i=a.compare(s);if(i===0)return null;const o=i>0,c=o?a:s,u=o?s:a,l=!!c.prerelease.length;if(!!u.prerelease.length&&!l){if(!u.patch&&!u.minor)return"major";if(u.compareMain(c)===0)return u.minor&&!u.patch?"minor":"patch"}const f=l?"pre":"";return a.major!==s.major?f+"major":a.minor!==s.minor?f+"minor":a.patch!==s.patch?f+"patch":"prerelease"},Jn}var Kn,Qi;function oh(){if(Qi)return Kn;Qi=1;const t=xe();return Kn=(r,n)=>new t(r,n).major,Kn}var Yn,Xi;function ch(){if(Xi)return Yn;Xi=1;const t=xe();return Yn=(r,n)=>new t(r,n).minor,Yn}var Qn,eo;function uh(){if(eo)return Qn;eo=1;const t=xe();return Qn=(r,n)=>new t(r,n).patch,Qn}var Xn,to;function lh(){if(to)return Xn;to=1;const t=Qt();return Xn=(r,n)=>{const a=t(r,n);return a&&a.prerelease.length?a.prerelease:null},Xn}var ea,ro;function He(){if(ro)return ea;ro=1;const t=xe();return ea=(r,n,a)=>new t(r,a).compare(new t(n,a)),ea}var ta,no;function dh(){if(no)return ta;no=1;const t=He();return ta=(r,n,a)=>t(n,r,a),ta}var ra,ao;function fh(){if(ao)return ra;ao=1;const t=He();return ra=(r,n)=>t(r,n,!0),ra}var na,so;function Ms(){if(so)return na;so=1;const t=xe();return na=(r,n,a)=>{const s=new t(r,a),i=new t(n,a);return s.compare(i)||s.compareBuild(i)},na}var aa,io;function hh(){if(io)return aa;io=1;const t=Ms();return aa=(r,n)=>r.sort((a,s)=>t(a,s,n)),aa}var sa,oo;function ph(){if(oo)return sa;oo=1;const t=Ms();return sa=(r,n)=>r.sort((a,s)=>t(s,a,n)),sa}var ia,co;function bn(){if(co)return ia;co=1;const t=He();return ia=(r,n,a)=>t(r,n,a)>0,ia}var oa,uo;function js(){if(uo)return oa;uo=1;const t=He();return oa=(r,n,a)=>t(r,n,a)<0,oa}var ca,lo;function ou(){if(lo)return ca;lo=1;const t=He();return ca=(r,n,a)=>t(r,n,a)===0,ca}var ua,fo;function cu(){if(fo)return ua;fo=1;const t=He();return ua=(r,n,a)=>t(r,n,a)!==0,ua}var la,ho;function Ds(){if(ho)return la;ho=1;const t=He();return la=(r,n,a)=>t(r,n,a)>=0,la}var da,po;function Us(){if(po)return da;po=1;const t=He();return da=(r,n,a)=>t(r,n,a)<=0,da}var fa,mo;function uu(){if(mo)return fa;mo=1;const t=ou(),e=cu(),r=bn(),n=Ds(),a=js(),s=Us();return fa=(o,c,u,l)=>{switch(c){case"===":return typeof o=="object"&&(o=o.version),typeof u=="object"&&(u=u.version),o===u;case"!==":return typeof o=="object"&&(o=o.version),typeof u=="object"&&(u=u.version),o!==u;case"":case"=":case"==":return t(o,u,l);case"!=":return e(o,u,l);case">":return r(o,u,l);case">=":return n(o,u,l);case"<":return a(o,u,l);case"<=":return s(o,u,l);default:throw new TypeError(`Invalid operator: ${c}`)}},fa}var ha,go;function mh(){if(go)return ha;go=1;const t=xe(),e=Qt(),{safeRe:r,t:n}=Or();return ha=(s,i)=>{if(s instanceof t)return s;if(typeof s=="number"&&(s=String(s)),typeof s!="string")return null;i=i||{};let o=null;if(!i.rtl)o=s.match(i.includePrerelease?r[n.COERCEFULL]:r[n.COERCE]);else{const h=i.includePrerelease?r[n.COERCERTLFULL]:r[n.COERCERTL];let p;for(;(p=h.exec(s))&&(!o||o.index+o[0].length!==s.length);)(!o||p.index+p[0].length!==o.index+o[0].length)&&(o=p),h.lastIndex=p.index+p[1].length+p[2].length;h.lastIndex=-1}if(o===null)return null;const c=o[2],u=o[3]||"0",l=o[4]||"0",d=i.includePrerelease&&o[5]?`-${o[5]}`:"",f=i.includePrerelease&&o[6]?`+${o[6]}`:"";return e(`${c}.${u}.${l}${d}${f}`,i)},ha}var pa,yo;function gh(){if(yo)return pa;yo=1;class t{constructor(){this.max=1e3,this.map=new Map}get(r){const n=this.map.get(r);if(n!==void 0)return this.map.delete(r),this.map.set(r,n),n}delete(r){return this.map.delete(r)}set(r,n){if(!this.delete(r)&&n!==void 0){if(this.map.size>=this.max){const s=this.map.keys().next().value;this.delete(s)}this.map.set(r,n)}return this}}return pa=t,pa}var ma,_o;function Ze(){if(_o)return ma;_o=1;const t=/\s+/g;class e{constructor(E,F){if(F=a(F),E instanceof e)return E.loose===!!F.loose&&E.includePrerelease===!!F.includePrerelease?E:new e(E.raw,F);if(E instanceof s)return this.raw=E.value,this.set=[[E]],this.formatted=void 0,this;if(this.options=F,this.loose=!!F.loose,this.includePrerelease=!!F.includePrerelease,this.raw=E.trim().replace(t," "),this.set=this.raw.split("||").map(P=>this.parseRange(P.trim())).filter(P=>P.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const P=this.set[0];if(this.set=this.set.filter(B=>!m(B[0])),this.set.length===0)this.set=[P];else if(this.set.length>1){for(const B of this.set)if(B.length===1&&g(B[0])){this.set=[B];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let E=0;E<this.set.length;E++){E>0&&(this.formatted+="||");const F=this.set[E];for(let P=0;P<F.length;P++)P>0&&(this.formatted+=" "),this.formatted+=F[P].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(E){const P=((this.options.includePrerelease&&h)|(this.options.loose&&p))+":"+E,B=n.get(P);if(B)return B;const L=this.options.loose,H=L?c[u.HYPHENRANGELOOSE]:c[u.HYPHENRANGE];E=E.replace(H,je(this.options.includePrerelease)),i("hyphen replace",E),E=E.replace(c[u.COMPARATORTRIM],l),i("comparator trim",E),E=E.replace(c[u.TILDETRIM],d),i("tilde trim",E),E=E.replace(c[u.CARETTRIM],f),i("caret trim",E);let X=E.split(" ").map(ne=>v(ne,this.options)).join(" ").split(/\s+/).map(ne=>we(ne,this.options));L&&(X=X.filter(ne=>(i("loose invalid filter",ne,this.options),!!ne.match(c[u.COMPARATORLOOSE])))),i("range list",X);const Y=new Map,se=X.map(ne=>new s(ne,this.options));for(const ne of se){if(m(ne))return[ne];Y.set(ne.value,ne)}Y.size>1&&Y.has("")&&Y.delete("");const pe=[...Y.values()];return n.set(P,pe),pe}intersects(E,F){if(!(E instanceof e))throw new TypeError("a Range is required");return this.set.some(P=>y(P,F)&&E.set.some(B=>y(B,F)&&P.every(L=>B.every(H=>L.intersects(H,F)))))}test(E){if(!E)return!1;if(typeof E=="string")try{E=new o(E,this.options)}catch{return!1}for(let F=0;F<this.set.length;F++)if(jt(this.set[F],E,this.options))return!0;return!1}}ma=e;const r=gh(),n=new r,a=Ls(),s=En(),i=wn(),o=xe(),{safeRe:c,t:u,comparatorTrimReplace:l,tildeTrimReplace:d,caretTrimReplace:f}=Or(),{FLAG_INCLUDE_PRERELEASE:h,FLAG_LOOSE:p}=vn(),m=A=>A.value==="<0.0.0-0",g=A=>A.value==="",y=(A,E)=>{let F=!0;const P=A.slice();let B=P.pop();for(;F&&P.length;)F=P.every(L=>B.intersects(L,E)),B=P.pop();return F},v=(A,E)=>(A=A.replace(c[u.BUILD],""),i("comp",A,E),A=U(A,E),i("caret",A),A=S(A,E),i("tildes",A),A=I(A,E),i("xrange",A),A=he(A,E),i("stars",A),A),_=A=>!A||A.toLowerCase()==="x"||A==="*",S=(A,E)=>A.trim().split(/\s+/).map(F=>R(F,E)).join(" "),R=(A,E)=>{const F=E.loose?c[u.TILDELOOSE]:c[u.TILDE];return A.replace(F,(P,B,L,H,X)=>{i("tilde",A,P,B,L,H,X);let Y;return _(B)?Y="":_(L)?Y=`>=${B}.0.0 <${+B+1}.0.0-0`:_(H)?Y=`>=${B}.${L}.0 <${B}.${+L+1}.0-0`:X?(i("replaceTilde pr",X),Y=`>=${B}.${L}.${H}-${X} <${B}.${+L+1}.0-0`):Y=`>=${B}.${L}.${H} <${B}.${+L+1}.0-0`,i("tilde return",Y),Y})},U=(A,E)=>A.trim().split(/\s+/).map(F=>z(F,E)).join(" "),z=(A,E)=>{i("caret",A,E);const F=E.loose?c[u.CARETLOOSE]:c[u.CARET],P=E.includePrerelease?"-0":"";return A.replace(F,(B,L,H,X,Y)=>{i("caret",A,B,L,H,X,Y);let se;return _(L)?se="":_(H)?se=`>=${L}.0.0${P} <${+L+1}.0.0-0`:_(X)?L==="0"?se=`>=${L}.${H}.0${P} <${L}.${+H+1}.0-0`:se=`>=${L}.${H}.0${P} <${+L+1}.0.0-0`:Y?(i("replaceCaret pr",Y),L==="0"?H==="0"?se=`>=${L}.${H}.${X}-${Y} <${L}.${H}.${+X+1}-0`:se=`>=${L}.${H}.${X}-${Y} <${L}.${+H+1}.0-0`:se=`>=${L}.${H}.${X}-${Y} <${+L+1}.0.0-0`):(i("no pr"),L==="0"?H==="0"?se=`>=${L}.${H}.${X}${P} <${L}.${H}.${+X+1}-0`:se=`>=${L}.${H}.${X}${P} <${L}.${+H+1}.0-0`:se=`>=${L}.${H}.${X} <${+L+1}.0.0-0`),i("caret return",se),se})},I=(A,E)=>(i("replaceXRanges",A,E),A.split(/\s+/).map(F=>oe(F,E)).join(" ")),oe=(A,E)=>{A=A.trim();const F=E.loose?c[u.XRANGELOOSE]:c[u.XRANGE];return A.replace(F,(P,B,L,H,X,Y)=>{i("xRange",A,P,B,L,H,X,Y);const se=_(L),pe=se||_(H),ne=pe||_(X),Ve=ne;return B==="="&&Ve&&(B=""),Y=E.includePrerelease?"-0":"",se?B===">"||B==="<"?P="<0.0.0-0":P="*":B&&Ve?(pe&&(H=0),X=0,B===">"?(B=">=",pe?(L=+L+1,H=0,X=0):(H=+H+1,X=0)):B==="<="&&(B="<",pe?L=+L+1:H=+H+1),B==="<"&&(Y="-0"),P=`${B+L}.${H}.${X}${Y}`):pe?P=`>=${L}.0.0${Y} <${+L+1}.0.0-0`:ne&&(P=`>=${L}.${H}.0${Y} <${L}.${+H+1}.0-0`),i("xRange return",P),P})},he=(A,E)=>(i("replaceStars",A,E),A.trim().replace(c[u.STAR],"")),we=(A,E)=>(i("replaceGTE0",A,E),A.trim().replace(c[E.includePrerelease?u.GTE0PRE:u.GTE0],"")),je=A=>(E,F,P,B,L,H,X,Y,se,pe,ne,Ve)=>(_(P)?F="":_(B)?F=`>=${P}.0.0${A?"-0":""}`:_(L)?F=`>=${P}.${B}.0${A?"-0":""}`:H?F=`>=${F}`:F=`>=${F}${A?"-0":""}`,_(se)?Y="":_(pe)?Y=`<${+se+1}.0.0-0`:_(ne)?Y=`<${se}.${+pe+1}.0-0`:Ve?Y=`<=${se}.${pe}.${ne}-${Ve}`:A?Y=`<${se}.${pe}.${+ne+1}-0`:Y=`<=${Y}`,`${F} ${Y}`.trim()),jt=(A,E,F)=>{for(let P=0;P<A.length;P++)if(!A[P].test(E))return!1;if(E.prerelease.length&&!F.includePrerelease){for(let P=0;P<A.length;P++)if(i(A[P].semver),A[P].semver!==s.ANY&&A[P].semver.prerelease.length>0){const B=A[P].semver;if(B.major===E.major&&B.minor===E.minor&&B.patch===E.patch)return!0}return!1}return!0};return ma}var ga,vo;function En(){if(vo)return ga;vo=1;const t=Symbol("SemVer ANY");class e{static get ANY(){return t}constructor(l,d){if(d=r(d),l instanceof e){if(l.loose===!!d.loose)return l;l=l.value}l=l.trim().split(/\s+/).join(" "),i("comparator",l,d),this.options=d,this.loose=!!d.loose,this.parse(l),this.semver===t?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(l){const d=this.options.loose?n[a.COMPARATORLOOSE]:n[a.COMPARATOR],f=l.match(d);if(!f)throw new TypeError(`Invalid comparator: ${l}`);this.operator=f[1]!==void 0?f[1]:"",this.operator==="="&&(this.operator=""),f[2]?this.semver=new o(f[2],this.options.loose):this.semver=t}toString(){return this.value}test(l){if(i("Comparator.test",l,this.options.loose),this.semver===t||l===t)return!0;if(typeof l=="string")try{l=new o(l,this.options)}catch{return!1}return s(l,this.operator,this.semver,this.options)}intersects(l,d){if(!(l instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(l.value,d).test(this.value):l.operator===""?l.value===""?!0:new c(this.value,d).test(l.semver):(d=r(d),d.includePrerelease&&(this.value==="<0.0.0-0"||l.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||l.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&l.operator.startsWith(">")||this.operator.startsWith("<")&&l.operator.startsWith("<")||this.semver.version===l.semver.version&&this.operator.includes("=")&&l.operator.includes("=")||s(this.semver,"<",l.semver,d)&&this.operator.startsWith(">")&&l.operator.startsWith("<")||s(this.semver,">",l.semver,d)&&this.operator.startsWith("<")&&l.operator.startsWith(">")))}}ga=e;const r=Ls(),{safeRe:n,t:a}=Or(),s=uu(),i=wn(),o=xe(),c=Ze();return ga}var ya,wo;function Sn(){if(wo)return ya;wo=1;const t=Ze();return ya=(r,n,a)=>{try{n=new t(n,a)}catch{return!1}return n.test(r)},ya}var _a,bo;function yh(){if(bo)return _a;bo=1;const t=Ze();return _a=(r,n)=>new t(r,n).set.map(a=>a.map(s=>s.value).join(" ").trim().split(" ")),_a}var va,Eo;function _h(){if(Eo)return va;Eo=1;const t=xe(),e=Ze();return va=(n,a,s)=>{let i=null,o=null,c=null;try{c=new e(a,s)}catch{return null}return n.forEach(u=>{c.test(u)&&(!i||o.compare(u)===-1)&&(i=u,o=new t(i,s))}),i},va}var wa,So;function vh(){if(So)return wa;So=1;const t=xe(),e=Ze();return wa=(n,a,s)=>{let i=null,o=null,c=null;try{c=new e(a,s)}catch{return null}return n.forEach(u=>{c.test(u)&&(!i||o.compare(u)===1)&&(i=u,o=new t(i,s))}),i},wa}var ba,To;function wh(){if(To)return ba;To=1;const t=xe(),e=Ze(),r=bn();return ba=(a,s)=>{a=new e(a,s);let i=new t("0.0.0");if(a.test(i)||(i=new t("0.0.0-0"),a.test(i)))return i;i=null;for(let o=0;o<a.set.length;++o){const c=a.set[o];let u=null;c.forEach(l=>{const d=new t(l.semver.version);switch(l.operator){case">":d.prerelease.length===0?d.patch++:d.prerelease.push(0),d.raw=d.format();case"":case">=":(!u||r(d,u))&&(u=d);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${l.operator}`)}}),u&&(!i||r(i,u))&&(i=u)}return i&&a.test(i)?i:null},ba}var Ea,xo;function bh(){if(xo)return Ea;xo=1;const t=Ze();return Ea=(r,n)=>{try{return new t(r,n).range||"*"}catch{return null}},Ea}var Sa,Io;function Fs(){if(Io)return Sa;Io=1;const t=xe(),e=En(),{ANY:r}=e,n=Ze(),a=Sn(),s=bn(),i=js(),o=Us(),c=Ds();return Sa=(l,d,f,h)=>{l=new t(l,h),d=new n(d,h);let p,m,g,y,v;switch(f){case">":p=s,m=o,g=i,y=">",v=">=";break;case"<":p=i,m=c,g=s,y="<",v="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(a(l,d,h))return!1;for(let _=0;_<d.set.length;++_){const S=d.set[_];let R=null,U=null;if(S.forEach(z=>{z.semver===r&&(z=new e(">=0.0.0")),R=R||z,U=U||z,p(z.semver,R.semver,h)?R=z:g(z.semver,U.semver,h)&&(U=z)}),R.operator===y||R.operator===v||(!U.operator||U.operator===y)&&m(l,U.semver))return!1;if(U.operator===v&&g(l,U.semver))return!1}return!0},Sa}var Ta,Ao;function Eh(){if(Ao)return Ta;Ao=1;const t=Fs();return Ta=(r,n,a)=>t(r,n,">",a),Ta}var xa,$o;function Sh(){if($o)return xa;$o=1;const t=Fs();return xa=(r,n,a)=>t(r,n,"<",a),xa}var Ia,Ro;function Th(){if(Ro)return Ia;Ro=1;const t=Ze();return Ia=(r,n,a)=>(r=new t(r,a),n=new t(n,a),r.intersects(n,a)),Ia}var Aa,Oo;function xh(){if(Oo)return Aa;Oo=1;const t=Sn(),e=He();return Aa=(r,n,a)=>{const s=[];let i=null,o=null;const c=r.sort((f,h)=>e(f,h,a));for(const f of c)t(f,n,a)?(o=f,i||(i=f)):(o&&s.push([i,o]),o=null,i=null);i&&s.push([i,null]);const u=[];for(const[f,h]of s)f===h?u.push(f):!h&&f===c[0]?u.push("*"):h?f===c[0]?u.push(`<=${h}`):u.push(`${f} - ${h}`):u.push(`>=${f}`);const l=u.join(" || "),d=typeof n.raw=="string"?n.raw:String(n);return l.length<d.length?l:n},Aa}var $a,ko;function Ih(){if(ko)return $a;ko=1;const t=Ze(),e=En(),{ANY:r}=e,n=Sn(),a=He(),s=(d,f,h={})=>{if(d===f)return!0;d=new t(d,h),f=new t(f,h);let p=!1;e:for(const m of d.set){for(const g of f.set){const y=c(m,g,h);if(p=p||y!==null,y)continue e}if(p)return!1}return!0},i=[new e(">=0.0.0-0")],o=[new e(">=0.0.0")],c=(d,f,h)=>{if(d===f)return!0;if(d.length===1&&d[0].semver===r){if(f.length===1&&f[0].semver===r)return!0;h.includePrerelease?d=i:d=o}if(f.length===1&&f[0].semver===r){if(h.includePrerelease)return!0;f=o}const p=new Set;let m,g;for(const I of d)I.operator===">"||I.operator===">="?m=u(m,I,h):I.operator==="<"||I.operator==="<="?g=l(g,I,h):p.add(I.semver);if(p.size>1)return null;let y;if(m&&g){if(y=a(m.semver,g.semver,h),y>0)return null;if(y===0&&(m.operator!==">="||g.operator!=="<="))return null}for(const I of p){if(m&&!n(I,String(m),h)||g&&!n(I,String(g),h))return null;for(const oe of f)if(!n(I,String(oe),h))return!1;return!0}let v,_,S,R,U=g&&!h.includePrerelease&&g.semver.prerelease.length?g.semver:!1,z=m&&!h.includePrerelease&&m.semver.prerelease.length?m.semver:!1;U&&U.prerelease.length===1&&g.operator==="<"&&U.prerelease[0]===0&&(U=!1);for(const I of f){if(R=R||I.operator===">"||I.operator===">=",S=S||I.operator==="<"||I.operator==="<=",m){if(z&&I.semver.prerelease&&I.semver.prerelease.length&&I.semver.major===z.major&&I.semver.minor===z.minor&&I.semver.patch===z.patch&&(z=!1),I.operator===">"||I.operator===">="){if(v=u(m,I,h),v===I&&v!==m)return!1}else if(m.operator===">="&&!n(m.semver,String(I),h))return!1}if(g){if(U&&I.semver.prerelease&&I.semver.prerelease.length&&I.semver.major===U.major&&I.semver.minor===U.minor&&I.semver.patch===U.patch&&(U=!1),I.operator==="<"||I.operator==="<="){if(_=l(g,I,h),_===I&&_!==g)return!1}else if(g.operator==="<="&&!n(g.semver,String(I),h))return!1}if(!I.operator&&(g||m)&&y!==0)return!1}return!(m&&S&&!g&&y!==0||g&&R&&!m&&y!==0||z||U)},u=(d,f,h)=>{if(!d)return f;const p=a(d.semver,f.semver,h);return p>0?d:p<0||f.operator===">"&&d.operator===">="?f:d},l=(d,f,h)=>{if(!d)return f;const p=a(d.semver,f.semver,h);return p<0?d:p>0||f.operator==="<"&&d.operator==="<="?f:d};return $a=s,$a}var Ra,Co;function Ah(){if(Co)return Ra;Co=1;const t=Or(),e=vn(),r=xe(),n=iu(),a=Qt(),s=nh(),i=ah(),o=sh(),c=ih(),u=oh(),l=ch(),d=uh(),f=lh(),h=He(),p=dh(),m=fh(),g=Ms(),y=hh(),v=ph(),_=bn(),S=js(),R=ou(),U=cu(),z=Ds(),I=Us(),oe=uu(),he=mh(),we=En(),je=Ze(),jt=Sn(),A=yh(),E=_h(),F=vh(),P=wh(),B=bh(),L=Fs(),H=Eh(),X=Sh(),Y=Th(),se=xh(),pe=Ih();return Ra={parse:a,valid:s,clean:i,inc:o,diff:c,major:u,minor:l,patch:d,prerelease:f,compare:h,rcompare:p,compareLoose:m,compareBuild:g,sort:y,rsort:v,gt:_,lt:S,eq:R,neq:U,gte:z,lte:I,cmp:oe,coerce:he,Comparator:we,Range:je,satisfies:jt,toComparators:A,maxSatisfying:E,minSatisfying:F,minVersion:P,validRange:B,outside:L,gtr:H,ltr:X,intersects:Y,simplifyRange:se,subset:pe,SemVer:r,re:t.re,src:t.src,tokens:t.t,SEMVER_SPEC_VERSION:e.SEMVER_SPEC_VERSION,RELEASE_TYPES:e.RELEASE_TYPES,compareIdentifiers:n.compareIdentifiers,rcompareIdentifiers:n.rcompareIdentifiers},Ra}Ah();function ft(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(`Invalid identifier format: ${t}`);const[e,r]=t.split(":"),n=r||"latest";if(e.includes("/")){const[a,s]=e.split("/",2);if(!a||!s)throw new Error(`Invalid identifier format: ${t}`);return[a,s,n]}else{if(!e)throw new Error(`Invalid identifier format: ${t}`);return["-",e,n]}}class $h extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}async function M(t,e,r){let n;if(t.ok){r&&(n=await t.text());return}if(t.status===403)try{(await t.json())?.error==="org_scoped_key_requires_workspace"&&(n="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{const o=new Error(`${t.status} ${t.statusText}`);throw o.status=t?.status,o}if(n===void 0)try{n=await t.text()}catch{n=""}const a=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${n}`;if(t.status===409)throw new $h(a);const s=new Error(a);throw s.status=t.status,s}const lu="ERR_CONFLICTING_ENDPOINTS";class Rh extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:lu}),this.name="ConflictingEndpointsError"}}function Oh(t){return typeof t=="object"&&t!==null&&t.code===lu}var No="[...]",kh={result:"[Circular]"},on=[],Ft=[];const Ch=new TextEncoder;function Nh(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Hr(t){return Ch.encode(t)}function du(t){if(t&&typeof t=="object"&&t!==null){if(t instanceof Map)return Object.fromEntries(t);if(t instanceof Set)return Array.from(t);if(t instanceof Date)return t.toISOString();if(t instanceof RegExp)return t.toString();if(t instanceof Error)return{name:t.name,message:t.message}}else if(typeof t=="bigint")return t.toString();return t}function Ph(t){return function(e,r){return du(r)}}function Ne(t,e,r,n,a){try{const s=JSON.stringify(t,Ph(r),n);return Hr(s)}catch(s){if(!s.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
|
|
18
|
+
Context: ${e}`:""}`),Hr("[Unserializable]");Re("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
|
|
19
|
+
Context: ${e}`:""}`),typeof a>"u"&&(a=Nh()),Ya(t,"",0,[],void 0,0,a);let i;try{Ft.length===0?i=JSON.stringify(t,r,n):i=JSON.stringify(t,Lh(r),n)}catch{return Hr("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;on.length!==0;){const o=on.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return Hr(i)}}function Oa(t,e,r,n){var a=Object.getOwnPropertyDescriptor(n,r);a.get!==void 0?a.configurable?(Object.defineProperty(n,r,{value:t}),on.push([n,r,e,a])):Ft.push([e,r,t]):(n[r]=t,on.push([n,r,e]))}function Ya(t,e,r,n,a,s,i){s+=1;var o;if(typeof t=="object"&&t!==null){for(o=0;o<n.length;o++)if(n[o]===t){Oa(kh,t,e,a);return}if(typeof i.depthLimit<"u"&&s>i.depthLimit){Oa(No,t,e,a);return}if(typeof i.edgesLimit<"u"&&r+1>i.edgesLimit){Oa(No,t,e,a);return}if(n.push(t),Array.isArray(t))for(o=0;o<t.length;o++)Ya(t[o],o,o,n,t,s,i);else{t=du(t);var c=Object.keys(t);for(o=0;o<c.length;o++){var u=c[o];Ya(t[u],u,o,n,t,s,i)}}n.pop()}}function Lh(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(Ft.length>0)for(var n=0;n<Ft.length;n++){var a=Ft[n];if(a[1]===e&&a[0]===r){r=a[2],Ft.splice(n,1);break}}return t.call(this,e,r)}}function Po(t,e,r){if(r)return t;const n=ru(),a=e??nu(),s=t.extra??{},i=s.metadata;return t.extra={...s,runtime:{...n,...s?.runtime},metadata:{...a,...a.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??a.revision_id}:{},...i}},t}const Mh=t=>{const e=t?.toString()??Re("TRACING_SAMPLING_RATE");if(e===void 0)return;const r=parseFloat(e);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},jh=t=>{const r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};async function Dh(t){const e=[];for await(const r of t)e.push(r);return e}function Zr(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const Uh=async t=>{if(t?.status===429){const e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(r=>setTimeout(r,e)),!0}return!1};function Lo(t){return typeof t=="number"?Number(t.toFixed(4)):t}const Fh=24*1024*1024,fu=1024*1024*1024,Bh=1e4,zh=100,Mo="https://api.smith.langchain.com";class qh{constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??fu}peek(){return this.items[0]}push(e){let r;const n=new Promise(s=>{r=s}),a=Ne(e.item,`Serializing run with id: ${e.item.id}`).length;return this.sizeBytes+a>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${a} bytes.`),r(),n):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:r,itemPromise:n,size:a}),this.sizeBytes+=a,n)}pop({upToSizeBytes:e,upToSize:r}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const n=[];let a=0;for(;a+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<r;){const s=this.items.shift();s&&(n.push(s),a+=s.size,this.sizeBytes-=s.size)}if(n.length===0&&this.items.length>0){const s=this.items.shift();n.push(s),a+=s.size,this.sizeBytes-=s.size}return[n.map(s=>({action:s.action,item:s.payload,otelContext:s.otelContext,apiKey:s.apiKey,apiUrl:s.apiUrl,size:s.size})),()=>n.forEach(s=>s.itemPromiseResolve())]}}class wr{get _fetch(){return this.fetchImplementation||wf(this.debug)}constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitTracedRuntimeInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:et("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:et("LANGSMITH_DEBUG")==="true"});const r=wr.getDefaultClientConfig();if(this.tracingSampleRate=Mh(e.tracingSamplingRate),this.apiUrl=Zr(e.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=Zr(e.apiKey??r.apiKey),this.webUrl=Zr(e.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=Zr(e.workspaceId??Re("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new Di({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation;const n=e.maxIngestMemoryBytes??fu;this.batchIngestCaller=new Di({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:n,...e.callerOptions??{},onFailedResponseHook:Uh,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??r.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??r.hideOutputs,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new qh(n),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,au()&&(this.langSmithToOTELTranslator=new Uf),this.cachedLSEnvVarsForMetadata=nu()}static getDefaultClientConfig(){const e=Re("API_KEY"),r=Re("ENDPOINT")??Mo,n=Re("HIDE_INPUTS")==="true",a=Re("HIDE_OUTPUTS")==="true";return{apiUrl:r,apiKey:e,webUrl:void 0,hideInputs:n,hideOutputs:a}}getHostUrl(){return this.webUrl?this.webUrl:jh(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){const e={"User-Agent":`langsmith-js/${Xc}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){const r={...e};return r.inputs!==void 0&&(r.inputs=await this.processInputs(r.inputs)),r.outputs!==void 0&&(r.outputs=await this.processOutputs(r.outputs)),r}async _getResponse(e,r){const n=r?.toString()??"",a=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{const i=await this._fetch(a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(i,`fetch ${e}`),i})}async _get(e,r){return(await this._getResponse(e,r)).json()}async*_getPaginated(e,r=new URLSearchParams,n){let a=Number(r.get("offset"))||0;const s=Number(r.get("limit"))||100;for(;;){r.set("offset",String(a)),r.set("limit",String(s));const i=`${this.apiUrl}${e}?${r}`,o=await this.caller.call(async()=>{const u=await this._fetch(i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(u,`fetch ${e}`),u}),c=n?n(await o.json()):await o.json();if(c.length===0||(yield c,c.length<s))break;a+=c.length}}async*_getCursorPaginatedList(e,r=null,n="POST",a="runs"){const s=r?{...r}:{};for(;;){const i=JSON.stringify(s),c=await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await M(l,`fetch ${e}`),l})).json();if(!c||!c[a])break;yield c[a];const u=c.cursors;if(!u||!u.next)break;s.cursor=u.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,r=!1){if(this.tracingSampleRate===void 0)return e;if(r){const n=[];for(const a of e)this.filteredPostUuids.has(a.trace_id)?a.id===a.trace_id&&this.filteredPostUuids.delete(a.trace_id):n.push(a);return n}else{const n=[];for(const a of e){const s=a.trace_id??a.id;this.filteredPostUuids.has(s)||(a.id===s?this._shouldSample()?n.push(a):this.filteredPostUuids.add(s):n.push(a))}return n}}async _getBatchSizeLimitBytes(){const e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e.batch_ingest_config?.size_limit_bytes??Fh}async _getBatchSizeLimit(){const e=await this._ensureServerInfo();return this.batchSizeLimit??e.batch_ingest_config?.size_limit??zh}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r}){const n=[];for(;this.autoBatchQueue.items.length>0;){const[a,s]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:r});if(!a.length){s();break}const i=a.reduce((u,l)=>{const d=l.apiUrl??this.apiUrl,f=l.apiKey??this.apiKey,p=l.apiKey===this.apiKey&&l.apiUrl===this.apiUrl?"default":`${d}|${f}`;return u[p]||(u[p]=[]),u[p].push(l),u},{}),o=[];for(const[u,l]of Object.entries(i)){const d=this._processBatch(l,{apiUrl:u==="default"?void 0:u.split("|")[0],apiKey:u==="default"?void 0:u.split("|")[1]});o.push(d)}const c=Promise.all(o).finally(s);n.push(c)}return Promise.all(n)}async _processBatch(e,r){if(!e.length)return;const n=e.reduce((a,s)=>a+(s.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{const a={runCreates:e.filter(i=>i.action==="create").map(i=>i.item),runUpdates:e.filter(i=>i.action==="update").map(i=>i.item)},s=await this._ensureServerInfo();if(s?.batch_ingest_config?.use_multipart_endpoint){const i=s?.instance_flags?.gzip_body_enabled;await this.multipartIngestRuns(a,{...r,useGzip:i,sizeBytes:n})}else await this.batchIngestRuns(a,{...r,sizeBytes:n})}}catch(a){console.error("Error exporting batch:",a)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){const r=new Map,n=[];for(const a of e)a.item.id&&a.otelContext&&(r.set(a.item.id,a.otelContext),a.action==="create"?n.push({operation:"post",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}):n.push({operation:"patch",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}));this.langSmithToOTELTranslator.exportBatch(n,r)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=Po(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);const r=this.autoBatchQueue.push(e);if(this.manualFlushMode)return r;const n=await this._getBatchSizeLimitBytes(),a=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>a)&&this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:a}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:a})},this.autoBatchAggregationDelayMs)),r}async _getServerInfo(){const r=await(await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(Bh),...this.fetchOptions});return await M(n,"get server info"),n})).json();return this.debug&&console.log(`
|
|
20
|
+
=== LangSmith Server Configuration ===
|
|
21
|
+
`+JSON.stringify(r,null,2)+`
|
|
22
|
+
`),r}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){const e=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r})}_cloneCurrentOTELContext(){const e=su(),r=Lf();if(this.langSmithToOTELTranslator!==void 0){const n=e.getActiveSpan();if(n)return e.setSpan(r.active(),n)}}async createRun(e,r){if(!this._filterForSampling([e]).length)return;const n={...this.headers,"Content-Type":"application/json"},a=e.project_name;delete e.project_name;const s=await this.prepareRunCreateOrUpdateInputs({session_name:a,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){const c=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:s,otelContext:c,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}const i=Po(s,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(n["x-tenant-id"]=r.workspaceId);const o=Ne(i,`Creating run with id: ${i.id}`);await this.caller.call(async()=>{const c=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await M(c,"create run",!0),c})}async batchIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let a=await Promise.all(e?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]),s=await Promise.all(r?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]);if(a.length>0&&s.length>0){const c=a.reduce((l,d)=>(d.id&&(l[d.id]=d),l),{}),u=[];for(const l of s)l.id!==void 0&&c[l.id]?c[l.id]={...c[l.id],...l}:u.push(l);a=Object.values(c),s=u}const i={post:a,patch:s};if(!i.post.length&&!i.patch.length)return;const o={post:[],patch:[]};for(const c of["post","patch"]){const u=c,l=i[u].reverse();let d=l.pop();for(;d!==void 0;)o[u].push(d),d=l.pop()}if(o.post.length>0||o.patch.length>0){const c=o.post.map(u=>u.id).concat(o.patch.map(u=>u.id)).join(",");await this._postBatchIngestRuns(Ne(o,`Ingesting runs with ids: ${c}`),n)}}async _postBatchIngestRuns(e,r){const n={...this.headers,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{const a=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await M(a,"batch create run",!0),a})}async multipartIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;const a={};let s=[];for(const d of e??[]){const f=await this.prepareRunCreateOrUpdateInputs(d);f.id!==void 0&&f.attachments!==void 0&&(a[f.id]=f.attachments),delete f.attachments,s.push(f)}let i=[];for(const d of r??[])i.push(await this.prepareRunCreateOrUpdateInputs(d));if(s.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(i.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(s.length>0&&i.length>0){const d=s.reduce((h,p)=>(p.id&&(h[p.id]=p),h),{}),f=[];for(const h of i)h.id!==void 0&&d[h.id]?d[h.id]={...d[h.id],...h}:f.push(h);s=Object.values(d),i=f}if(s.length===0&&i.length===0)return;const u=[],l=[];for(const[d,f]of[["post",s],["patch",i]])for(const h of f){const{inputs:p,outputs:m,events:g,extra:y,error:v,serialized:_,attachments:S,...R}=h,U={inputs:p,outputs:m,events:g,extra:y,error:v,serialized:_},z=Ne(R,`Serializing for multipart ingestion of run with id: ${R.id}`);l.push({name:`${d}.${R.id}`,payload:new Blob([z],{type:`application/json; length=${z.length}`})});for(const[I,oe]of Object.entries(U)){if(oe===void 0)continue;const he=Ne(oe,`Serializing ${I} for multipart ingestion of run with id: ${R.id}`);l.push({name:`${d}.${R.id}.${I}`,payload:new Blob([he],{type:`application/json; length=${he.length}`})})}if(R.id!==void 0){const I=a[R.id];if(I){delete a[R.id];for(const[oe,he]of Object.entries(I)){let we,je;if(Array.isArray(he)?[we,je]=he:(we=he.mimeType,je=he.data),oe.includes(".")){console.warn(`Skipping attachment '${oe}' for run ${R.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${R.id}.${oe}`,payload:new Blob([je],{type:`${we}; length=${je.byteLength}`})})}}}u.push(`trace=${R.trace_id},id=${R.id}`)}await this._sendMultipartRequest(l,u.join("; "),n)}async _createNodeFetchBody(e,r){const n=[];for(const i of e)n.push(new Blob([`--${r}\r
|
|
23
|
+
`])),n.push(new Blob([`Content-Disposition: form-data; name="${i.name}"\r
|
|
24
|
+
`,`Content-Type: ${i.payload.type}\r
|
|
25
|
+
\r
|
|
26
|
+
`])),n.push(i.payload),n.push(new Blob([`\r
|
|
27
|
+
`]));return n.push(new Blob([`--${r}--\r
|
|
28
|
+
`])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,r){const n=new TextEncoder;return new ReadableStream({async start(s){const i=async o=>{typeof o=="string"?s.enqueue(n.encode(o)):s.enqueue(o)};for(const o of e){await i(`--${r}\r
|
|
29
|
+
`),await i(`Content-Disposition: form-data; name="${o.name}"\r
|
|
30
|
+
`),await i(`Content-Type: ${o.payload.type}\r
|
|
31
|
+
\r
|
|
32
|
+
`);const u=o.payload.stream().getReader();try{let l;for(;!(l=await u.read()).done;)s.enqueue(l.value)}finally{u.releaseLock()}await i(`\r
|
|
33
|
+
`)}await i(`--${r}--\r
|
|
34
|
+
`),s.close()}})}async _sendMultipartRequest(e,r,n){const a="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),s=vf(),i=()=>this._createNodeFetchBody(e,a),o=()=>this._createMultipartStream(e,a),c=async u=>this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{const l=await u(),d={...this.headers,"Content-Type":`multipart/form-data; boundary=${a}`};n?.apiKey!==void 0&&(d["x-api-key"]=n.apiKey);let f=l;n?.useGzip&&typeof l=="object"&&"pipeThrough"in l&&(f=l.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");const h=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:f,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(h,"Failed to send multipart request",!0),h});try{let u,l=!1;!s&&!this.multipartStreamingDisabled&&tu()!=="bun"?(l=!0,u=await c(o)):u=await c(i),(!this.multipartStreamingDisabled||l)&&u.status===422&&(n?.apiUrl??this.apiUrl)!==Mo&&(console.warn(`Streaming multipart upload to ${n?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${r}".`),this.multipartStreamingDisabled=!0,u=await c(i))}catch(u){console.warn(`${u.message.trim()}
|
|
35
|
+
|
|
36
|
+
Context: ${r}`)}}async updateRun(e,r,n){J(e),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs));const a={...r,id:e};if(!this._filterForSampling([a],!0).length)return;if(this.autoBatchTracing&&a.trace_id!==void 0&&a.dotted_order!==void 0){const o=this._cloneCurrentOTELContext();if(r.end_time!==void 0&&a.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:a,otelContext:o,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:a,otelContext:o,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}const s={...this.headers,"Content-Type":"application/json"};n?.apiKey!==void 0&&(s["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(s["x-tenant-id"]=n.workspaceId);const i=Ne(r,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{const o=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:s,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await M(o,"update run",!0),o})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){J(e);let n=await this._get(`/runs/${e}`);return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:r,projectOpts:n}){if(r!==void 0){let a;r.session_id?a=r.session_id:n?.projectName?a=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?a=n?.projectId:a=(await this.readProject({projectName:Re("PROJECT")||"default"})).id;const s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${a}/r/${r.id}?poll=true`}else if(e!==void 0){const a=await this.readRun(e);if(!a.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${a.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){const r=await Dh(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},a={};r.sort((s,i)=>(s?.dotted_order??"").localeCompare(i?.dotted_order??""));for(const s of r){if(s.parent_run_id===null||s.parent_run_id===void 0)throw new Error(`Child run ${s.id} has no parent`);s.dotted_order?.startsWith(e.dotted_order??"")&&s.id!==e.id&&(s.parent_run_id in n||(n[s.parent_run_id]=[]),n[s.parent_run_id].push(s),a[s.id]=s)}e.child_runs=n[e.id]||[];for(const s in n)s!==e.id&&(a[s].child_runs=n[s]);return e}async*listRuns(e){const{projectId:r,projectName:n,parentRunId:a,traceId:s,referenceExampleId:i,startTime:o,executionOrder:c,isRoot:u,runType:l,error:d,id:f,query:h,filter:p,traceFilter:m,treeFilter:g,limit:y,select:v,order:_}=e;let S=[];if(r&&(S=Array.isArray(r)?r:[r]),n){const I=Array.isArray(n)?n:[n],oe=await Promise.all(I.map(he=>this.readProject({projectName:he}).then(we=>we.id)));S.push(...oe)}const R=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],U={session:S.length?S:null,run_type:l,reference_example:i,query:h,filter:p,trace_filter:m,tree_filter:g,execution_order:c,parent_run:a,start_time:o?o.toISOString():null,error:d,id:f,limit:y,trace:s,select:v||R,is_root:u,order:_};U.select.includes("child_run_ids")&&Ja("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let z=0;for await(const I of this._getCursorPaginatedList("/runs/query",U))if(y){if(z>=y)break;if(I.length+z>y){yield*I.slice(0,y-z);break}z+=I.length,yield*I}else yield*I}async*listGroupRuns(e){const{projectId:r,projectName:n,groupBy:a,filter:s,startTime:i,endTime:o,limit:c,offset:u}=e,d={session_id:r||(await this.readProject({projectName:n})).id,group_by:a,filter:s,start_time:i?i.toISOString():null,end_time:o?o.toISOString():null,limit:Number(c)||100};let f=Number(u)||0;const h="/runs/group",p=`${this.apiUrl}${h}`;for(;;){const m={...d,offset:f},g=Object.fromEntries(Object.entries(m).filter(([U,z])=>z!==void 0)),y=JSON.stringify(g),_=await(await this.caller.call(async()=>{const U=await this._fetch(p,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:y});return await M(U,`Failed to fetch ${h}`),U})).json(),{groups:S,total:R}=_;if(S.length===0)break;for(const U of S)yield U;if(f+=S.length,f>=R)break}}async getRunStats({id:e,trace:r,parentRun:n,runType:a,projectNames:s,projectIds:i,referenceExampleIds:o,startTime:c,endTime:u,error:l,query:d,filter:f,traceFilter:h,treeFilter:p,isRoot:m,dataSourceType:g}){let y=i||[];s&&(y=[...i||[],...await Promise.all(s.map(z=>this.readProject({projectName:z}).then(I=>I.id)))]);const _=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:a,session:y,reference_example:o,start_time:c,end_time:u,error:l,query:d,filter:f,trace_filter:h,tree_filter:p,is_root:m,data_source_type:g}).filter(([z,I])=>I!==void 0)),S=JSON.stringify(_);return await(await this.caller.call(async()=>{const z=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:S});return await M(z,"get run stats"),z})).json()}async shareRun(e,{shareId:r}={}){const n={run_id:e,share_token:r||Tt()};J(e);const a=JSON.stringify(n),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await M(o,"share run"),o})).json();if(i===null||!("share_token"in i))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(e){J(e),await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(r,"unshare run",!0),r})}async readRunSharedLink(e){J(e);const n=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(a,"read run shared link"),a})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:r}={}){const n=new URLSearchParams({share_token:e});if(r!==void 0)for(const i of r)n.append("id",i);return J(e),await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/public/${e}/runs${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(i,"list shared runs"),i})).json()}async readDatasetSharedSchema(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id),J(e);const a=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(s,"read dataset shared schema"),s})).json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async shareDataset(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id);const n={dataset_id:e};J(e);const a=JSON.stringify(n),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await M(o,"share dataset"),o})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){J(e),await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(r,"unshare dataset",!0),r})}async readSharedDataset(e){return J(e),await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(a,"read shared dataset"),a})).json()}async listSharedExamples(e,r){const n={};r?.exampleIds&&(n.id=r.exampleIds);const a=new URLSearchParams;Object.entries(n).forEach(([o,c])=>{Array.isArray(c)?c.forEach(u=>a.append(o,u)):a.append(o,c)});const s=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/public/${e}/examples?${a.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(o,"list shared examples"),o}),i=await s.json();if(!s.ok)throw"detail"in i?new Error(`Failed to list shared examples.
|
|
37
|
+
Status: ${s.status}
|
|
38
|
+
Message: ${Array.isArray(i.detail)?i.detail.join(`
|
|
39
|
+
`):"Unspecified error"}`):new Error(`Failed to list shared examples: ${s.status} ${s.statusText}`);return i.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:r=null,metadata:n=null,upsert:a=!1,projectExtra:s=null,referenceDatasetId:i=null}){const o=a?"?upsert=true":"",c=`${this.apiUrl}/sessions${o}`,u=s||{};n&&(u.metadata=n);const l={name:e,extra:u,description:r};i!==null&&(l.reference_dataset_id=i);const d=JSON.stringify(l);return await(await this.caller.call(async()=>{const p=await this._fetch(c,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});return await M(p,"create project"),p})).json()}async updateProject(e,{name:r=null,description:n=null,metadata:a=null,projectExtra:s=null,endTime:i=null}){const o=`${this.apiUrl}/sessions/${e}`;let c=s;a&&(c={...c||{},metadata:a});const u=JSON.stringify({name:r,extra:c,description:n,end_time:i?new Date(i).toISOString():null});return await(await this.caller.call(async()=>{const f=await this._fetch(o,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await M(f,"update project"),f})).json()}async hasProject({projectId:e,projectName:r}){let n="/sessions";const a=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)J(e),n+=`/${e}`;else if(r!==void 0)a.append("name",r);else throw new Error("Must provide projectName or projectId");const s=await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${n}?${a}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(i,"has project"),i});try{const i=await s.json();return s.ok?Array.isArray(i)?i.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:r,includeStats:n}){let a="/sessions";const s=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)J(e),a+=`/${e}`;else if(r!==void 0)s.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&s.append("include_stats",n.toString());const i=await this._get(a,s);let o;if(Array.isArray(i)){if(i.length===0)throw new Error(`Project[id=${e}, name=${r}] not found`);o=i[0]}else o=i;return o}async getProjectUrl({projectId:e,projectName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");const n=await this.readProject({projectId:e,projectName:r}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");const n=await this.readDataset({datasetId:e,datasetName:r}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;const e=new URLSearchParams({limit:"1"});for await(const r of this._getPaginated("/sessions",e))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:r,nameContains:n,referenceDatasetId:a,referenceDatasetName:s,includeStats:i,datasetVersion:o,referenceFree:c,metadata:u}={}){const l=new URLSearchParams;if(e!==void 0)for(const d of e)l.append("id",d);if(r!==void 0&&l.append("name",r),n!==void 0&&l.append("name_contains",n),a!==void 0)l.append("reference_dataset",a);else if(s!==void 0){const d=await this.readDataset({datasetName:s});l.append("reference_dataset",d.id)}i!==void 0&&l.append("include_stats",i.toString()),o!==void 0&&l.append("dataset_version",o),c!==void 0&&l.append("reference_free",c.toString()),u!==void 0&&l.append("metadata",JSON.stringify(u));for await(const d of this._getPaginated("/sessions",l))yield*d}async deleteProject({projectId:e,projectName:r}){let n;if(e===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?n=(await this.readProject({projectName:r})).id:n=e,J(n),await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(a,`delete session ${n} (${r})`,!0),a})}async uploadCsv({csvFile:e,fileName:r,inputKeys:n,outputKeys:a,description:s,dataType:i,name:o}){const c=`${this.apiUrl}/datasets/upload`,u=new FormData;return u.append("file",e,r),n.forEach(f=>{u.append("input_keys",f)}),a.forEach(f=>{u.append("output_keys",f)}),s&&u.append("description",s),i&&u.append("data_type",i),o&&u.append("name",o),await(await this.caller.call(async()=>{const f=await this._fetch(c,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await M(f,"upload CSV"),f})).json()}async createDataset(e,{description:r,dataType:n,inputsSchema:a,outputsSchema:s,metadata:i}={}){const o={name:e,description:r,extra:i?{metadata:i}:void 0};n&&(o.data_type=n),a&&(o.inputs_schema_definition=a),s&&(o.outputs_schema_definition=s);const c=JSON.stringify(o);return await(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await M(d,"create dataset"),d})).json()}async readDataset({datasetId:e,datasetName:r}){let n="/datasets";const a=new URLSearchParams({limit:"1"});if(e&&r)throw new Error("Must provide either datasetName or datasetId, not both");if(e)J(e),n+=`/${e}`;else if(r)a.append("name",r);else throw new Error("Must provide datasetName or datasetId");const s=await this._get(n,a);let i;if(Array.isArray(s)){if(s.length===0)throw new Error(`Dataset[id=${e}, name=${r}] not found`);i=s[0]}else i=s;return i}async hasDataset({datasetId:e,datasetName:r}){try{return await this.readDataset({datasetId:e,datasetName:r}),!0}catch(n){if(n instanceof Error&&n.message.toLocaleLowerCase().includes("not found"))return!1;throw n}}async diffDatasetVersions({datasetId:e,datasetName:r,fromVersion:n,toVersion:a}){let s=e;if(s===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:r})).id);const i=new URLSearchParams({from_version:typeof n=="string"?n:n.toISOString(),to_version:typeof a=="string"?a:a.toISOString()});return await this._get(`/datasets/${s}/versions/diff`,i)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:r}){const n="/datasets";if(e===void 0)if(r!==void 0)e=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${n}/${e}/openai_ft`)).text()).trim().split(`
|
|
40
|
+
`).map(o=>JSON.parse(o))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:n,datasetName:a,datasetNameContains:s,metadata:i}={}){const o="/datasets",c=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(n!==void 0)for(const u of n)c.append("id",u);a!==void 0&&c.append("name",a),s!==void 0&&c.append("name_contains",s),i!==void 0&&c.append("metadata",JSON.stringify(i));for await(const u of this._getPaginated(o,c))yield*u}async updateDataset(e){const{datasetId:r,datasetName:n,...a}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");const s=r??(await this.readDataset({datasetName:n})).id;J(s);const i=JSON.stringify(a);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await M(c,"update dataset"),c})).json()}async updateDatasetTag(e){const{datasetId:r,datasetName:n,asOf:a,tag:s}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");const i=r??(await this.readDataset({datasetName:n})).id;J(i);const o=JSON.stringify({as_of:typeof a=="string"?a:a.toISOString(),tag:s});await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${i}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await M(c,"update dataset tags",!0),c})}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",a=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(a=(await this.readDataset({datasetName:r})).id),a!==void 0)J(a),n+=`/${a}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{const s=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(s,`delete ${n}`,!0),s})}async indexDataset({datasetId:e,datasetName:r,tag:n}){let a=e;if(!a&&!r)throw new Error("Must provide either datasetName or datasetId");if(a&&r)throw new Error("Must provide either datasetName or datasetId, not both");a||(a=(await this.readDataset({datasetName:r})).id),J(a);const i=JSON.stringify({tag:n});await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${a}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await M(c,"index dataset"),c})).json()}async similarExamples(e,r,n,{filter:a}={}){const s={limit:n,inputs:e};a!==void 0&&(s.filter=a),J(r);const i=JSON.stringify(s);return(await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${r}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:i});return await M(u,"fetch similar examples"),u})).json()).examples}async createExample(e,r,n){if(jo(e)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let a=r?n?.datasetId:e.dataset_id;const s=r?n?.datasetName:e.dataset_name;if(a===void 0&&s===void 0)throw new Error("Must provide either datasetName or datasetId");if(a!==void 0&&s!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");a===void 0&&(a=(await this.readDataset({datasetName:s})).id);const i=(r?n?.createdAt:e.created_at)||new Date;let o;jo(e)?o=e:o={inputs:e,outputs:r,created_at:i?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};const c=await this._uploadExamplesMultipart(a,[o]);return await this.readExample(c.example_ids?.[0]??Tt())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];const v=e;let _=v[0].dataset_id;const S=v[0].dataset_name;if(_===void 0&&S===void 0)throw new Error("Must provide either datasetName or datasetId");if(_!==void 0&&S!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");_===void 0&&(_=(await this.readDataset({datasetName:S})).id);const R=await this._uploadExamplesMultipart(_,v);return await Promise.all(R.example_ids.map(z=>this.readExample(z)))}const{inputs:r,outputs:n,metadata:a,splits:s,sourceRunIds:i,useSourceRunIOs:o,useSourceRunAttachments:c,attachments:u,exampleIds:l,datasetId:d,datasetName:f}=e;if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let h=d;const p=f;if(h===void 0&&p===void 0)throw new Error("Must provide either datasetName or datasetId");if(h!==void 0&&p!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");h===void 0&&(h=(await this.readDataset({datasetName:p})).id);const m=r.map((v,_)=>({dataset_id:h,inputs:v,outputs:n?.[_],metadata:a?.[_],split:s?.[_],id:l?.[_],attachments:u?.[_],source_run_id:i?.[_],use_source_run_io:o?.[_],use_source_run_attachments:c?.[_]})),g=await this._uploadExamplesMultipart(h,m);return await Promise.all(g.example_ids.map(v=>this.readExample(v)))}async createLLMExample(e,r,n){return this.createExample({input:e},{output:r},n)}async createChatExample(e,r,n){const a=e.map(i=>Ui(i)?Fi(i):i),s=Ui(r)?Fi(r):r;return this.createExample({input:a},{output:s},n)}async readExample(e){J(e);const r=`/examples/${e}`,n=await this._get(r),{attachment_urls:a,...s}=n,i=s;return a&&(i.attachments=Object.entries(a).reduce((o,[c,u])=>(o[c.slice(11)]={presigned_url:u.presigned_url,mime_type:u.mime_type},o),{})),i}async*listExamples({datasetId:e,datasetName:r,exampleIds:n,asOf:a,splits:s,inlineS3Urls:i,metadata:o,limit:c,offset:u,filter:l,includeAttachments:d}={}){let f;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)f=e;else if(r!==void 0)f=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");const h=new URLSearchParams({dataset:f}),p=a?typeof a=="string"?a:a?.toISOString():void 0;p&&h.append("as_of",p);const m=i??!0;if(h.append("inline_s3_urls",m.toString()),n!==void 0)for(const y of n)h.append("id",y);if(s!==void 0)for(const y of s)h.append("splits",y);if(o!==void 0){const y=JSON.stringify(o);h.append("metadata",y)}c!==void 0&&h.append("limit",c.toString()),u!==void 0&&h.append("offset",u.toString()),l!==void 0&&h.append("filter",l),d===!0&&["attachment_urls","outputs","metadata"].forEach(y=>h.append("select",y));let g=0;for await(const y of this._getPaginated("/examples",h)){for(const v of y){const{attachment_urls:_,...S}=v,R=S;_&&(R.attachments=Object.entries(_).reduce((U,[z,I])=>(U[z.slice(11)]={presigned_url:I.presigned_url,mime_type:I.mime_type||void 0},U),{})),yield R,g++}if(c!==void 0&&g>=c)break}}async deleteExample(e){J(e);const r=`/examples/${e}`;await this.caller.call(async()=>{const n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(n,`delete ${r}`,!0),n})}async deleteExamples(e,r){if(e.forEach(n=>J(n)),r?.hardDelete){const n=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}${n}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({example_ids:e,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(a,"hard delete examples",!0),a})}else{const n=new URLSearchParams;e.forEach(a=>n.append("example_ids",a)),await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/examples?${n.toString()}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(a,"delete examples",!0),a})}}async updateExample(e,r){let n;r?n=e:n=e.id,J(n);let a;r?a={id:n,...r}:a=e;let s;return a.dataset_id!==void 0?s=a.dataset_id:s=(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(s,[a])}async updateExamples(e){let r;return e[0].dataset_id===void 0?r=(await this.readExample(e[0].id)).dataset_id:r=e[0].dataset_id,this._updateExamplesMultipart(r,e)}async readDatasetVersion({datasetId:e,datasetName:r,asOf:n,tag:a}){let s;if(e?s=e:s=(await this.readDataset({datasetName:r})).id,J(s),n&&a||!n&&!a)throw new Error("Exactly one of asOf and tag must be specified.");const i=new URLSearchParams;return n!==void 0&&i.append("as_of",typeof n=="string"?n:n.toISOString()),a!==void 0&&i.append("tag",a),await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${s}/version?${i.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(c,"read dataset version"),c})).json()}async listDatasetSplits({datasetId:e,datasetName:r,asOf:n}){let a;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?a=(await this.readDataset({datasetName:r})).id:a=e,J(a);const s=new URLSearchParams,i=n?typeof n=="string"?n:n?.toISOString():void 0;return i&&s.append("as_of",i),await this._get(`/datasets/${a}/splits`,s)}async updateDatasetSplits({datasetId:e,datasetName:r,splitName:n,exampleIds:a,remove:s=!1}){let i;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?i=(await this.readDataset({datasetName:r})).id:i=e,J(i);const o={split_name:n,examples:a.map(u=>(J(u),u)),remove:s},c=JSON.stringify(o);await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${i}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await M(u,"update dataset splits",!0),u})}async evaluateRun(e,r,{sourceInfo:n,loadChildRuns:a,referenceExample:s}={loadChildRuns:!1}){Ja("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");let i;if(typeof e=="string")i=await this.readRun(e,{loadChildRuns:a});else if(typeof e=="object"&&"id"in e)i=e;else throw new Error(`Invalid run type: ${typeof e}`);i.reference_example_id!==null&&i.reference_example_id!==void 0&&(s=await this.readExample(i.reference_example_id));const o=await r.evaluateRun(i,s),[c,u]=await this._logEvaluationFeedback(o,i,n);return u[0]}async createFeedback(e,r,{score:n,value:a,correction:s,comment:i,sourceInfo:o,feedbackSourceType:c="api",sourceRunId:u,feedbackId:l,feedbackConfig:d,projectId:f,comparativeExperimentId:h}){if(!e&&!f)throw new Error("One of runId or projectId must be provided");if(e&&f)throw new Error("Only one of runId or projectId can be provided");const p={type:c??"api",metadata:o??{}};u!==void 0&&p?.metadata!==void 0&&!p.metadata.__run&&(p.metadata.__run={run_id:u}),p?.metadata!==void 0&&p.metadata.__run?.run_id!==void 0&&J(p.metadata.__run.run_id);const m={id:l??Tt(),run_id:e,key:r,score:Lo(n),value:a,correction:s,comment:i,feedback_source:p,comparative_experiment_id:h,feedbackConfig:d,session_id:f},g=JSON.stringify(m),y=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const v=await this._fetch(y,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:g});return await M(v,"create feedback",!0),v}),m}async updateFeedback(e,{score:r,value:n,correction:a,comment:s}){const i={};r!=null&&(i.score=Lo(r)),n!=null&&(i.value=n),a!=null&&(i.correction=a),s!=null&&(i.comment=s),J(e);const o=JSON.stringify(i);await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await M(c,"update feedback",!0),c})}async readFeedback(e){J(e);const r=`/feedback/${e}`;return await this._get(r)}async deleteFeedback(e){J(e);const r=`/feedback/${e}`;await this.caller.call(async()=>{const n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(n,`delete ${r}`,!0),n})}async*listFeedback({runIds:e,feedbackKeys:r,feedbackSourceTypes:n}={}){const a=new URLSearchParams;if(e)for(const s of e)J(s),a.append("run",s);if(r)for(const s of r)a.append("key",s);if(n)for(const s of n)a.append("source",s);for await(const s of this._getPaginated("/feedback",a))yield*s}async createPresignedFeedbackToken(e,r,{expiration:n,feedbackConfig:a}={}){const s={run_id:e,feedback_key:r,feedback_config:a};n?typeof n=="string"?s.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(s.expires_in=n):s.expires_in={hours:3};const i=JSON.stringify(s);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await M(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:e,experimentIds:r,referenceDatasetId:n,createdAt:a,description:s,metadata:i,id:o}){if(r.length===0)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:r[0]})).reference_dataset_id),!n==null)throw new Error("A reference dataset is required");const c={id:o,name:e,experiment_ids:r,reference_dataset_id:n,description:s,created_at:(a??new Date)?.toISOString(),extra:{}};i&&(c.extra.metadata=i);const u=JSON.stringify(c);return(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await M(d,"create comparative experiment"),d})).json()}async*listPresignedFeedbackTokens(e){J(e);const r=new URLSearchParams({run_id:e});for await(const n of this._getPaginated("/feedback/tokens",r))yield*n}_selectEvalResults(e){let r;return"results"in e?r=e.results:Array.isArray(e)?r=e:r=[e],r}async _logEvaluationFeedback(e,r,n){const a=this._selectEvalResults(e),s=[];for(const i of a){let o=n||{};i.evaluatorInfo&&(o={...i.evaluatorInfo,...o});let c=null;i.targetRunId?c=i.targetRunId:r&&(c=r.id),s.push(await this.createFeedback(c,i.key,{score:i.score,value:i.value,comment:i.comment,correction:i.correction,sourceInfo:o,sourceRunId:i.sourceRunId,feedbackConfig:i.feedbackConfig,feedbackSourceType:"model"}))}return[a,s]}async logEvaluationFeedback(e,r,n){const[a]=await this._logEvaluationFeedback(e,r,n);return a}async*listAnnotationQueues(e={}){const{queueIds:r,name:n,nameContains:a,limit:s}=e,i=new URLSearchParams;r&&r.forEach((c,u)=>{J(c,`queueIds[${u}]`),i.append("ids",c)}),n&&i.append("name",n),a&&i.append("name_contains",a),i.append("limit",(s!==void 0?Math.min(s,100):100).toString());let o=0;for await(const c of this._getPaginated("/annotation-queues",i))if(yield*c,o++,s!==void 0&&o>=s)break}async createAnnotationQueue(e){const{name:r,description:n,queueId:a,rubricInstructions:s}=e,i={name:r,description:n,id:a||Tt(),rubric_instructions:s},o=JSON.stringify(Object.fromEntries(Object.entries(i).filter(([u,l])=>l!==void 0)));return(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await M(u,"create annotation queue"),u})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${J(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(e,r){const{name:n,description:a,rubricInstructions:s}=r,i=JSON.stringify({name:n,description:a,rubric_instructions:s});await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/annotation-queues/${J(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await M(o,"update annotation queue",!0),o})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${J(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(r,"delete annotation queue",!0),r})}async addRunsToAnnotationQueue(e,r){const n=JSON.stringify(r.map((a,s)=>J(a,`runIds[${s}]`).toString()));await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/annotation-queues/${J(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await M(a,"add runs to annotation queue",!0),a})}async getRunFromAnnotationQueue(e,r){const n=`/annotation-queues/${J(e,"queueId")}/run`;return(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${n}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(s,"get run from annotation queue"),s})).json()}async deleteRunFromAnnotationQueue(e,r){await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${J(e,"queueId")}/runs/${J(r,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(n,"delete run from annotation queue",!0),n})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${J(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(n,"get size from annotation queue"),n})).json()}async _currentTenantIsOwner(e){const r=await this._getSettings();return e=="-"||r.tenant_handle===e}async _ownerConflictError(e,r){const n=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
|
|
41
|
+
|
|
42
|
+
Current tenant: ${n.tenant_handle}
|
|
43
|
+
|
|
44
|
+
Requested tenant: ${r}`)}async _getLatestCommitHash(e){const n=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(a,"get latest commit hash"),a})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(e,r){const[n,a,s]=ft(e),i=JSON.stringify({like:r});return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/likes/${n}/${a}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await M(c,`${r?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(e){const[r,n,a]=ft(e);if(await this._currentTenantIsOwner(r)){const s=await this._getSettings();return a!=="latest"?`${this.getHostUrl()}/prompts/${n}/${a.substring(0,8)}?organizationId=${s.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${s.id}`}else return a!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${a.substring(0,8)}`:`${this.getHostUrl()}/hub/${r}/${n}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){for await(const r of this._getPaginated(`/commits/${e}/`,new URLSearchParams,n=>n.commits))yield*r}async*listPrompts(e){const r=new URLSearchParams;r.append("sort_field",e?.sortField??"updated_at"),r.append("sort_direction","desc"),r.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&r.append("is_public",e.isPublic.toString()),e?.query&&r.append("query",e.query);for await(const n of this._getPaginated("/repos",r,a=>a.repos))yield*n}async getPrompt(e){const[r,n,a]=ft(e),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return o?.status===404?null:(await M(o,"get prompt"),o)}))?.json();return i?.repo?i.repo:null}async createPrompt(e,r){const n=await this._getSettings();if(r?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
|
|
45
|
+
|
|
46
|
+
creating a LangChain Hub handle.
|
|
47
|
+
You can add a handle by creating a public prompt at:
|
|
48
|
+
|
|
49
|
+
https://smith.langchain.com/prompts`);const[a,s,i]=ft(e);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError("create a prompt",a);const o={repo_handle:s,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},c=JSON.stringify(o),u=await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await M(d,"create prompt"),d}),{repo:l}=await u.json();return l}async createCommit(e,r,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[a,s,i]=ft(e),o=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${a}/${s}`):n?.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(r)),parent_commit:o},u=JSON.stringify(c),d=await(await this.caller.call(async()=>{const f=await this._fetch(`${this.apiUrl}/commits/${a}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await M(f,"create commit"),f})).json();return this._getPromptUrl(`${a}/${s}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(e,r=[]){return this._updateExamplesMultipart(e,r)}async _updateExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const n=new FormData;for(const i of r){const o=i.id,c={...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split}},u=Ne(c,`Serializing body for example with id: ${o}`),l=new Blob([u],{type:"application/json"});if(n.append(o,l),i.inputs){const d=Ne(i.inputs,`Serializing inputs for example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.inputs`,f)}if(i.outputs){const d=Ne(i.outputs,`Serializing outputs whle updating example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.outputs`,f)}if(i.attachments)for(const[d,f]of Object.entries(i.attachments)){let h,p;Array.isArray(f)?[h,p]=f:(h=f.mimeType,p=f.data);const m=new Blob([p],{type:`${h}; length=${p.byteLength}`});n.append(`${o}.attachment.${d}`,m)}if(i.attachments_operations){const d=Ne(i.attachments_operations,`Serializing attachments while updating example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.attachments_operations`,f)}}const a=e??r[0]?.dataset_id;return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${a}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await M(i,"update examples"),i})).json()}async uploadExamplesMultipart(e,r=[]){return this._uploadExamplesMultipart(e,r)}async _uploadExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const n=new FormData;for(const s of r){const i=(s.id??Tt()).toString(),o={created_at:s.created_at,...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split},...s.source_run_id&&{source_run_id:s.source_run_id},...s.use_source_run_io&&{use_source_run_io:s.use_source_run_io},...s.use_source_run_attachments&&{use_source_run_attachments:s.use_source_run_attachments}},c=Ne(o,`Serializing body for uploaded example with id: ${i}`),u=new Blob([c],{type:"application/json"});if(n.append(i,u),s.inputs){const l=Ne(s.inputs,`Serializing inputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});n.append(`${i}.inputs`,d)}if(s.outputs){const l=Ne(s.outputs,`Serializing outputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});n.append(`${i}.outputs`,d)}if(s.attachments)for(const[l,d]of Object.entries(s.attachments)){let f,h;Array.isArray(d)?[f,h]=d:(f=d.mimeType,h=d.data);const p=new Blob([h],{type:`${f}; length=${h.byteLength}`});n.append(`${i}.attachment.${l}`,p)}}return(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await M(s,"upload examples"),s})).json()}async updatePrompt(e,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[n,a]=ft(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);const s={};if(r?.description!==void 0&&(s.description=r.description),r?.readme!==void 0&&(s.readme=r.readme),r?.tags!==void 0&&(s.tags=r.tags),r?.isPublic!==void 0&&(s.is_public=r.isPublic),r?.isArchived!==void 0&&(s.is_archived=r.isArchived),Object.keys(s).length===0)throw new Error("No valid update options provided");const i=JSON.stringify(s);return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/repos/${n}/${a}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await M(c,"update prompt"),c})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[r,n,a]=ft(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(i,"delete prompt"),i})).json()}async pullPromptCommit(e,r){const[n,a,s]=ft(e),o=await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/commits/${n}/${a}/${s}${r?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(c,"pull prompt commit"),c})).json();return{owner:n,repo:a,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async _pullPrompt(e,r){const n=await this.pullPromptCommit(e,{includeModel:r?.includeModel});return JSON.stringify(n.manifest)}async pushPrompt(e,r){return await this.promptExists(e)?r&&Object.keys(r).some(a=>a!=="object")&&await this.updatePrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}):await this.createPrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}),r?.object?await this.createCommit(e,r?.object,{parentCommitHash:r?.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,r={}){const{sourceApiUrl:n=this.apiUrl,datasetName:a}=r,[s,i]=this.parseTokenOrUrl(e,n),o=new wr({apiUrl:s,apiKey:"placeholder"}),c=await o.readSharedDataset(i),u=a||c.name;try{if(await this.hasDataset({datasetId:u})){console.log(`Dataset ${u} already exists in your tenant. Skipping.`);return}}catch{}const l=await o.listSharedExamples(i),d=await this.createDataset(u,{description:c.description,dataType:c.data_type||"kv",inputsSchema:c.inputs_schema_definition??void 0,outputsSchema:c.outputs_schema_definition??void 0});try{await this.createExamples({inputs:l.map(f=>f.inputs),outputs:l.flatMap(f=>f.outputs?[f.outputs]:[]),datasetId:d.id})}catch(f){throw console.error(`An error occurred while creating dataset ${u}. You should delete it manually.`),f}}parseTokenOrUrl(e,r,n=2,a="dataset"){try{return J(e),[r,e]}catch{}try{const i=new URL(e).pathname.split("/").filter(o=>o!=="");if(i.length>=n){const o=i[i.length-n];return[r,o]}else throw new Error(`Invalid public ${a} URL: ${e}`)}catch{throw new Error(`Invalid public ${a} URL or token: ${e}`)}}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await Mf()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function jo(t){return"dataset_id"in t||"dataset_name"in t}const Gh=t=>!!["TRACING_V2","TRACING"].find(r=>Re(r)==="true"),_t=Symbol.for("lc:context_variables"),ka=Symbol.for("langsmith:replica_trace_roots");function Do(t,e){if(_t in t)return t[_t][e]}function Hh(t,e,r){const n=_t in t?t[_t]:{};n[e]=r,t[_t]=n}const sr="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function Uo(t){const r=Object.keys(t).sort().map(n=>`${n}:${t[n]??""}`).join("|");return ar(r,sr)}function Zh(t){return t.replace(/[-:.]/g,"")}function hu(t,e=1){const r=e.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(t).toISOString().slice(0,-1)}${r}Z`}function pu(t,e,r=1){const n=hu(t,r);return{dottedOrder:Zh(n)+e,microsecondPrecisionDatestring:n}}class cn{constructor(e,r,n,a){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=r,this.project_name=n,this.replicas=a}static fromHeader(e){const r=e.split(",");let n={},a=[],s,i;for(const o of r){const[c,u]=o.split("="),l=decodeURIComponent(u);c==="langsmith-metadata"?n=JSON.parse(l):c==="langsmith-tags"?a=l.split(","):c==="langsmith-project"?s=l:c==="langsmith-replicas"&&(i=JSON.parse(l))}return new cn(n,a,s,i)}toHeader(){const e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}}class $e{constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Vh(e)){Object.assign(this,{...e});return}const r=$e.getDefaultConfig(),{metadata:n,...a}=e,s=a.client??$e.getSharedClient(),i={...n,...a?.extra?.metadata};if(a.extra={...a.extra,metadata:i},"id"in a&&a.id==null&&delete a.id,Object.assign(this,{...r,...a,client:s}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=hu(this.start_time,this.execution_order)),this.id||(this.id=Ef(this._serialized_start_time??this.start_time)),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=Yh(this.replicas),!this.dotted_order){const{dottedOrder:o}=pu(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+o:this.dotted_order=o}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){const e=Date.now();return{run_type:"chain",project_name:Qc(),child_runs:[],api_url:et("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:et("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return $e.sharedClient||($e.sharedClient=new wr),$e.sharedClient}createChild(e){const r=this.child_execution_order+1,n=this.replicas?.map(l=>{const{reroot:d,...f}=l;return f}),a=e.replicas??n,s=new $e({...e,parent_run:this,project_name:this.project_name,replicas:a,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:r,child_execution_order:r});_t in this&&(s[_t]=this[_t]);const i=Symbol.for("lc:child_config"),o=e.extra?.[i]??this.extra[i];if(Jh(o)){const l={...o},d=Wh(l.callbacks)?l.callbacks.copy?.():void 0;d&&(Object.assign(d,{_parentRunId:s.id}),d.handlers?.find(mu)?.updateFromRunTree?.(s),l.callbacks=d),s.extra[i]=l}const c=new Set;let u=this;for(;u!=null&&!c.has(u.id);)c.add(u.id),u.child_execution_order=Math.max(u.child_execution_order,r),u=u.parent_run;return this.child_runs.push(s),s}async end(e,r,n=Date.now(),a){this.outputs=this.outputs??e,this.error=this.error??r,this.end_time=this.end_time??n,a&&Object.keys(a).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...a}}:{metadata:a})}_convertToCreate(e,r,n=!0){const a=e.extra??{};if(a?.runtime?.library===void 0&&(a.runtime||(a.runtime={}),r))for(const[o,c]of Object.entries(r))a.runtime[o]||(a.runtime[o]=c);let s,i;return n?(i=e.parent_run?.id??e.parent_run_id,s=[]):(s=e.child_runs.map(o=>this._convertToCreate(o,r,n)),i=void 0),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:a,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:s,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_sliceParentId(e,r){if(r.dotted_order){const n=r.dotted_order.split(".");let a=null;for(let s=0;s<n.length;s++)if(n[s].slice(-36)===e){a=s;break}if(a!==null){const s=n.slice(a+1);r.dotted_order=s.join("."),s.length>0?r.trace_id=s[0].slice(-36):r.trace_id=r.id}}r.parent_run_id===e&&(r.parent_run_id=void 0)}_setReplicaTraceRoot(e,r){const n=Do(this,ka)??{};n[e]=r,Hh(this,ka,n);for(const a of this.child_runs)a._setReplicaTraceRoot(e,r)}_remapForProject(e){const{projectName:r,runtimeEnv:n,excludeChildRuns:a=!0,reroot:s=!1,distributedParentId:i,apiUrl:o,apiKey:c,workspaceId:u}=e,l=this._convertToCreate(this,n,a);if(r===this.project_name)return{...l,session_name:r};if(s){if(i)this._sliceParentId(i,l);else if(l.parent_run_id=void 0,l.dotted_order){const v=l.dotted_order.split(".");v.length>0&&(l.dotted_order=v[v.length-1],l.trace_id=l.id)}const y=Uo({projectName:r,apiUrl:o,apiKey:c,workspaceId:u});this._setReplicaTraceRoot(y,l.id)}let d;if(!s){const y=Do(this,ka)??{},v=Uo({projectName:r,apiUrl:o,apiKey:c,workspaceId:u});if(d=y[v],d&&(l.trace_id=d,l.dotted_order)){const _=l.dotted_order.split(".");let S=null;for(let R=0;R<_.length;R++)if(_[R].slice(-36)===d){S=R;break}if(S!==null){const R=_.slice(S);l.dotted_order=R.join(".")}}}const f=l.id,h=ar(`${f}:${r}`,sr);let p;l.trace_id?p=ar(`${l.trace_id}:${r}`,sr):p=h;let m;l.parent_run_id&&(m=ar(`${l.parent_run_id}:${r}`,sr));let g;return l.dotted_order&&(g=l.dotted_order.split(".").map(_=>{const S=_.slice(-36),R=ar(`${S}:${r}`,sr);return _.slice(0,-36)+R}).join(".")),{...l,id:h,trace_id:p,parent_run_id:m,dotted_order:g,session_name:r}}async postRun(e=!0){try{const r=ru();if(this.replicas&&this.replicas.length>0)for(const{projectName:n,apiKey:a,apiUrl:s,workspaceId:i,reroot:o}of this.replicas){const c=this._remapForProject({projectName:n??this.project_name,runtimeEnv:r,excludeChildRuns:!0,reroot:o,distributedParentId:this.distributedParentId,apiUrl:s,apiKey:a,workspaceId:i});await this.client.createRun(c,{apiKey:a,apiUrl:s,workspaceId:i})}else{const n=this._convertToCreate(this,r,e);await this.client.createRun(n)}if(!e){Ja("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const n of this.child_runs)await n.postRun(!1)}}catch(r){console.error(`Error in postRun for run ${this.id}:`,r)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(const{projectName:r,apiKey:n,apiUrl:a,workspaceId:s,updates:i,reroot:o}of this.replicas){const c=this._remapForProject({projectName:r??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:o,distributedParentId:this.distributedParentId,apiUrl:a,apiKey:n,workspaceId:s}),u={id:c.id,name:c.name,run_type:c.run_type,start_time:c.start_time,outputs:c.outputs,error:c.error,parent_run_id:c.parent_run_id,session_name:c.session_name,reference_example_id:c.reference_example_id,end_time:c.end_time,dotted_order:c.dotted_order,trace_id:c.trace_id,events:c.events,tags:c.tags,extra:c.extra,attachments:this.attachments,...i};e?.excludeInputs||(u.inputs=c.inputs),await this.client.updateRun(c.id,u,{apiKey:n,apiUrl:a,workspaceId:s})}else try{const r={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e?.excludeInputs||(r.inputs=this.inputs),await this.client.updateRun(this.id,r)}catch(r){console.error(`Error in patchRun for run ${this.id}`,r)}}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,r){const n=e?.callbacks;let a,s,i,o=Gh();if(n){const u=n?.getParentRunId?.()??"",l=n?.handlers?.find(d=>d?.name=="langchain_tracer");a=l?.getRun?.(u),s=l?.projectName,i=l?.client,o=o||!!l}return a?new $e({name:a.name,id:a.id,trace_id:a.trace_id,dotted_order:a.dotted_order,client:i,tracingEnabled:o,project_name:s,tags:[...new Set((a?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...a?.extra?.metadata,...e?.metadata}}}).createChild(r):new $e({...r,client:i,tracingEnabled:o,project_name:s})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,r){const n="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,a=n["langsmith-trace"];if(!a||typeof a!="string")return;const s=a.trim(),i=s.split(".").map(l=>{const[d,f]=l.split("Z");return{strTime:d,time:Date.parse(d+"Z"),uuid:f}}),o=i[0].uuid,c={...r,name:r?.name??"parent",run_type:r?.run_type??"chain",start_time:r?.start_time??Date.now(),id:i.at(-1)?.uuid,trace_id:o,dotted_order:s};if(n.baggage&&typeof n.baggage=="string"){const l=cn.fromHeader(n.baggage);c.metadata=l.metadata,c.tags=l.tags,c.project_name=l.project_name,c.replicas=l.replicas}const u=new $e(c);return u.distributedParentId=u.id,u}toHeaders(e){const r={"langsmith-trace":this.dotted_order,baggage:new cn(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(const[n,a]of Object.entries(r))e.set(n,a);return r}}Object.defineProperty($e,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function Vh(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}function mu(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}function Fo(t){return Array.isArray(t)&&t.some(e=>mu(e))}function Wh(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}function Jh(t){const e=t?.callbacks;return t!=null&&typeof e=="object"&&(Fo(e?.handlers)||Fo(e))}function Kh(){const t=et("LANGSMITH_RUNS_ENDPOINTS");if(!t)return[];try{const e=JSON.parse(t);if(Array.isArray(e)){const r=[];for(const n of e){if(typeof n!="object"||n===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}r.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key})}return r}else if(typeof e=="object"&&e!==null){Qh(e);const r=[];for(const[n,a]of Object.entries(e)){const s=n.replace(/\/$/,"");if(typeof a=="string")r.push({apiUrl:s,apiKey:a});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof a}`);continue}}return r}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof e}`),[]}catch(e){if(Oh(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function Yh(t){return t?t.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):Kh()}function Qh(t){if(Object.keys(t).length>0&&Re("ENDPOINT"))throw new Rh}var Xh={};ge(Xh,{BaseTracer:()=>Xt,isBaseTracer:()=>Ut});const ep=t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t};function Qa(t,e){if(t)return new $e({...t,start_time:t._serialized_start_time??t.start_time,parent_run:Qa(e),child_runs:t.child_runs.map(r=>Qa(r)).filter(r=>r!==void 0),extra:{...t.extra,runtime:Wc()},tracingEnabled:!1})}function Ca(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}function Ut(t){return typeof t._addRunToRunMap=="function"}var Xt=class extends Rr{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(t){super(...arguments)}copy(){return this}getRunById(t){if(t!==void 0)return this.usesRunTreeMap?ep(this.runTreeMap.get(t)):this.runMap.get(t)}stringifyError(t){return t instanceof Error?t.message+(t?.stack?`
|
|
50
|
+
|
|
51
|
+
${t.stack}`:""):typeof t=="string"?t:`${t}`}_addChildRun(t,e){t.child_runs.push(e)}_addRunToRunMap(t){const{dottedOrder:e,microsecondPrecisionDatestring:r}=pu(new Date(t.start_time).getTime(),t.id,t.execution_order),n={...t},a=this.getRunById(n.parent_run_id);if(n.parent_run_id!==void 0?a?(this._addChildRun(a,n),a.child_execution_order=Math.max(a.child_execution_order,n.child_execution_order),n.trace_id=a.trace_id,a.dotted_order!==void 0&&(n.dotted_order=[a.dotted_order,e].join("."),n._serialized_start_time=r)):n.parent_run_id=void 0:(n.trace_id=n.id,n.dotted_order=e,n._serialized_start_time=r),this.usesRunTreeMap){const s=Qa(n,a);s!==void 0&&this.runTreeMap.set(n.id,s)}else this.runMap.set(n.id,n);return n}async _endTrace(t){const e=t.parent_run_id!==void 0&&this.getRunById(t.parent_run_id);e?e.child_execution_order=Math.max(e.child_execution_order,t.child_execution_order):await this.persistRun(t),await this.onRunUpdate?.(t),this.usesRunTreeMap?this.runTreeMap.delete(t.id):this.runMap.delete(t.id)}_getExecutionOrder(t){const e=t!==void 0&&this.getRunById(t);return e?e.child_execution_order+1:1}_createRunForLLMStart(t,e,r,n,a,s,i,o){const c=this._getExecutionOrder(n),u=Date.now(),l=i?{...a,metadata:i}:a,d={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:e},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:l??{},tags:s||[]};return this._addRunToRunMap(d)}async handleLLMStart(t,e,r,n,a,s,i,o){const c=this.getRunById(r)??this._createRunForLLMStart(t,e,r,n,a,s,i,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(t,e,r,n,a,s,i,o){const c=this._getExecutionOrder(n),u=Date.now(),l=i?{...a,metadata:i}:a,d={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:e},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:l??{},tags:s||[]};return this._addRunToRunMap(d)}async handleChatModelStart(t,e,r,n,a,s,i,o){const c=this.getRunById(r)??this._createRunForChatModelStart(t,e,r,n,a,s,i,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(t,e,r,n,a){const s=this.getRunById(e);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.outputs=t,s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...a},await this.onLLMEnd?.(s),await this._endTrace(s),s}async handleLLMError(t,e,r,n,a){const s=this.getRunById(e);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(t),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...a},await this.onLLMError?.(s),await this._endTrace(s),s}_createRunForChainStart(t,e,r,n,a,s,i,o){const c=this._getExecutionOrder(n),u=Date.now(),l={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:e,execution_order:c,child_execution_order:c,run_type:i??"chain",child_runs:[],extra:s?{metadata:s}:{},tags:a||[]};return this._addRunToRunMap(l)}async handleChainStart(t,e,r,n,a,s,i,o){const c=this.getRunById(r)??this._createRunForChainStart(t,e,r,n,a,s,i,o);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(t,e,r,n,a){const s=this.getRunById(e);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.outputs=Ca(t,"output"),s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),a?.inputs!==void 0&&(s.inputs=Ca(a.inputs,"input")),await this.onChainEnd?.(s),await this._endTrace(s),s}async handleChainError(t,e,r,n,a){const s=this.getRunById(e);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(t),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),a?.inputs!==void 0&&(s.inputs=Ca(a.inputs,"input")),await this.onChainError?.(s),await this._endTrace(s),s}_createRunForToolStart(t,e,r,n,a,s,i){const o=this._getExecutionOrder(n),c=Date.now(),u={id:r,name:i??t.id[t.id.length-1],parent_run_id:n,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:e},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:s?{metadata:s}:{},tags:a||[]};return this._addRunToRunMap(u)}async handleToolStart(t,e,r,n,a,s,i){const o=this.getRunById(r)??this._createRunForToolStart(t,e,r,n,a,s,i);return await this.onRunCreate?.(o),await this.onToolStart?.(o),o}async handleToolEnd(t,e){const r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(t,e){const r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(t,e){const r=this.getRunById(e);if(!r||r?.run_type!=="chain")return;const n=r;n.actions=n.actions||[],n.actions.push(t),n.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentAction?.(r)}async handleAgentEnd(t,e){const r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(t,e,r,n,a,s,i){const o=this._getExecutionOrder(n),c=Date.now(),u={id:r,name:i??t.id[t.id.length-1],parent_run_id:n,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:e},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:s?{metadata:s}:{},tags:a||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(t,e,r,n,a,s,i){const o=this.getRunById(r)??this._createRunForRetrieverStart(t,e,r,n,a,s,i);return await this.onRunCreate?.(o),await this.onRetrieverStart?.(o),o}async handleRetrieverEnd(t,e){const r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(t,e){const r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(t,e){const r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:t}}),await this.onText?.(r))}async handleLLMNewToken(t,e,r,n,a,s){const i=this.getRunById(r);if(!i||i?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return i.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:t,idx:e,chunk:s?.chunk}}),await this.onLLMNewToken?.(i,t,{chunk:s?.chunk}),i}},Kr={exports:{}};Kr.exports;var Bo;function tp(){return Bo||(Bo=1,(function(t){const r=(s=0)=>i=>`\x1B[${38+s};5;${i}m`,n=(s=0)=>(i,o,c)=>`\x1B[${38+s};2;${i};${o};${c}m`;function a(){const s=new Map,i={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};i.color.gray=i.color.blackBright,i.bgColor.bgGray=i.bgColor.bgBlackBright,i.color.grey=i.color.blackBright,i.bgColor.bgGrey=i.bgColor.bgBlackBright;for(const[o,c]of Object.entries(i)){for(const[u,l]of Object.entries(c))i[u]={open:`\x1B[${l[0]}m`,close:`\x1B[${l[1]}m`},c[u]=i[u],s.set(l[0],l[1]);Object.defineProperty(i,o,{value:c,enumerable:!1})}return Object.defineProperty(i,"codes",{value:s,enumerable:!1}),i.color.close="\x1B[39m",i.bgColor.close="\x1B[49m",i.color.ansi256=r(),i.color.ansi16m=n(),i.bgColor.ansi256=r(10),i.bgColor.ansi16m=n(10),Object.defineProperties(i,{rgbToAnsi256:{value:(o,c,u)=>o===c&&c===u?o<8?16:o>248?231:Math.round((o-8)/247*24)+232:16+36*Math.round(o/255*5)+6*Math.round(c/255*5)+Math.round(u/255*5),enumerable:!1},hexToRgb:{value:o=>{const c=/(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(o.toString(16));if(!c)return[0,0,0];let{colorString:u}=c.groups;u.length===3&&(u=u.split("").map(d=>d+d).join(""));const l=Number.parseInt(u,16);return[l>>16&255,l>>8&255,l&255]},enumerable:!1},hexToAnsi256:{value:o=>i.rgbToAnsi256(...i.hexToRgb(o)),enumerable:!1}}),i}Object.defineProperty(t,"exports",{enumerable:!0,get:a})})(Kr)),Kr.exports}var rp=tp();const gu=gn(rp);var np={};ge(np,{ConsoleCallbackHandler:()=>Xa});function Ee(t,e){return`${t.open}${e}${t.close}`}function Le(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}function zo(t){return typeof t=="string"?t.trim():t==null?t:Le(t,t.toString())}function ht(t){if(!t.end_time)return"";const e=t.end_time-t.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}const{color:Ae}=gu;var Xa=class extends Xt{name="console_callback_handler";persistRun(t){return Promise.resolve()}getParents(t){const e=[];let r=t;for(;r.parent_run_id;){const n=this.runMap.get(r.parent_run_id);if(n)e.push(n),r=n;else break}return e}getBreadcrumbs(t){const r=[...this.getParents(t).reverse(),t].map((n,a,s)=>{const i=`${n.execution_order}:${n.run_type}:${n.name}`;return a===s.length-1?Ee(gu.bold,i):i}).join(" > ");return Ee(Ae.grey,r)}onChainStart(t){const e=this.getBreadcrumbs(t);console.log(`${Ee(Ae.green,"[chain/start]")} [${e}] Entering Chain run with input: ${Le(t.inputs,"[inputs]")}`)}onChainEnd(t){const e=this.getBreadcrumbs(t);console.log(`${Ee(Ae.cyan,"[chain/end]")} [${e}] [${ht(t)}] Exiting Chain run with output: ${Le(t.outputs,"[outputs]")}`)}onChainError(t){const e=this.getBreadcrumbs(t);console.log(`${Ee(Ae.red,"[chain/error]")} [${e}] [${ht(t)}] Chain run errored with error: ${Le(t.error,"[error]")}`)}onLLMStart(t){const e=this.getBreadcrumbs(t),r="prompts"in t.inputs?{prompts:t.inputs.prompts.map(n=>n.trim())}:t.inputs;console.log(`${Ee(Ae.green,"[llm/start]")} [${e}] Entering LLM run with input: ${Le(r,"[inputs]")}`)}onLLMEnd(t){const e=this.getBreadcrumbs(t);console.log(`${Ee(Ae.cyan,"[llm/end]")} [${e}] [${ht(t)}] Exiting LLM run with output: ${Le(t.outputs,"[response]")}`)}onLLMError(t){const e=this.getBreadcrumbs(t);console.log(`${Ee(Ae.red,"[llm/error]")} [${e}] [${ht(t)}] LLM run errored with error: ${Le(t.error,"[error]")}`)}onToolStart(t){const e=this.getBreadcrumbs(t);console.log(`${Ee(Ae.green,"[tool/start]")} [${e}] Entering Tool run with input: "${zo(t.inputs.input)}"`)}onToolEnd(t){const e=this.getBreadcrumbs(t);console.log(`${Ee(Ae.cyan,"[tool/end]")} [${e}] [${ht(t)}] Exiting Tool run with output: "${zo(t.outputs?.output)}"`)}onToolError(t){const e=this.getBreadcrumbs(t);console.log(`${Ee(Ae.red,"[tool/error]")} [${e}] [${ht(t)}] Tool run errored with error: ${Le(t.error,"[error]")}`)}onRetrieverStart(t){const e=this.getBreadcrumbs(t);console.log(`${Ee(Ae.green,"[retriever/start]")} [${e}] Entering Retriever run with input: ${Le(t.inputs,"[inputs]")}`)}onRetrieverEnd(t){const e=this.getBreadcrumbs(t);console.log(`${Ee(Ae.cyan,"[retriever/end]")} [${e}] [${ht(t)}] Exiting Retriever run with output: ${Le(t.outputs,"[outputs]")}`)}onRetrieverError(t){const e=this.getBreadcrumbs(t);console.log(`${Ee(Ae.red,"[retriever/error]")} [${e}] [${ht(t)}] Retriever run errored with error: ${Le(t.error,"[error]")}`)}onAgentAction(t){const e=t,r=this.getBreadcrumbs(t);console.log(`${Ee(Ae.blue,"[agent/action]")} [${r}] Agent selected action: ${Le(e.actions[e.actions.length-1],"[action]")}`)}};let Na;const yu=()=>{if(Na===void 0){const t=It("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};Na=new wr(t)}return Na};let ap=class{getStore(){}run(e,r){return r()}};const Pa=Symbol.for("ls:tracing_async_local_storage"),sp=new ap;let ip=class{getInstance(){return globalThis[Pa]??sp}initializeGlobalInstance(e){globalThis[Pa]===void 0&&(globalThis[Pa]=e)}};const op=new ip;function cp(t=!1){const e=op.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree.
|
|
52
|
+
|
|
53
|
+
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function Bs(t){return typeof t=="function"&&"langsmith:traceable"in t}var up={};ge(up,{LangChainTracer:()=>Yr});var Yr=class _u extends Xt{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;constructor(e={}){super(e);const{exampleId:r,projectName:n,client:a,replicas:s}=e;this.projectName=n??Qc(),this.replicas=s,this.exampleId=r,this.client=a??yu();const i=_u.getTraceableRunTree();i&&this.updateFromRunTree(i)}async persistRun(e){}async onRunCreate(e){await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){await this.getRunTreeWithTracingConfig(e.id)?.patchRun()}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let r=e;const n=new Set;for(;r.parent_run&&!(n.has(r.id)||(n.add(r.id),!r.parent_run));)r=r.parent_run;n.clear();const a=[r];for(;a.length>0;){const s=a.shift();!s||n.has(s.id)||(n.add(s.id),this.runTreeMap.set(s.id,s),s.child_runs&&a.push(...s.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(e){const r=this.runTreeMap.get(e);if(r)return new $e({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return cp(!0)}catch{return}}};let At;function lp(){const t="default"in st?st.default:st;return new t({autoStart:!0,concurrency:1})}function dp(){return typeof At>"u"&&(At=lp()),At}async function fe(t,e){if(e===!0){const r=vr();r!==void 0?await r.run(void 0,async()=>t()):await t()}else At=dp(),At.add(async()=>{const r=vr();r!==void 0?await r.run(void 0,async()=>t()):await t()})}async function fp(){const t=yu();await Promise.allSettled([typeof At<"u"?At.onIdle():Promise.resolve(),t.awaitPendingTraceBatches()])}var hp={};ge(hp,{awaitAllCallbacks:()=>fp,consumeCallback:()=>fe});const pp=t=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(r=>It(r)==="true");function vu(t){const e=vr();return e===void 0?void 0:e.getStore()?.[ur]?.[t]}const mp=Symbol("lc:configure_hooks"),gp=()=>vu(mp)||[];var yp={};ge(yp,{BaseCallbackManager:()=>wu,BaseRunManager:()=>kr,CallbackManager:()=>Lt,CallbackManagerForChainRun:()=>Eu,CallbackManagerForLLMRun:()=>es,CallbackManagerForRetrieverRun:()=>bu,CallbackManagerForToolRun:()=>Su,ensureHandler:()=>br,parseCallbackConfigArg:()=>_p});function _p(t){return t?Array.isArray(t)||"name"in t?{callbacks:t}:t:{}}var wu=class{setHandler(t){return this.setHandlers([t])}},kr=class{constructor(t,e,r,n,a,s,i,o){this.runId=t,this.handlers=e,this.inheritableHandlers=r,this.tags=n,this.inheritableTags=a,this.metadata=s,this.inheritableMetadata=i,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(e=>fe(async()=>{try{await e.handleText?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleText: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleCustomEvent(t,e,r,n,a){await Promise.all(this.handlers.map(s=>fe(async()=>{try{await s.handleCustomEvent?.(t,e,this.runId,this.tags,this.metadata)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleCustomEvent: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}},bu=class extends kr{getChild(t){const e=new Lt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleRetrieverEnd(t){await Promise.all(this.handlers.map(e=>fe(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetriever`),e.raiseError)throw r}},e.awaitHandlers)))}async handleRetrieverError(t){await Promise.all(this.handlers.map(e=>fe(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetrieverError: ${r}`),e.raiseError)throw t}},e.awaitHandlers)))}},es=class extends kr{async handleLLMNewToken(t,e,r,n,a,s){await Promise.all(this.handlers.map(i=>fe(async()=>{if(!i.ignoreLLM)try{await i.handleLLMNewToken?.(t,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,s)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMNewToken: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleLLMError(t,e,r,n,a){await Promise.all(this.handlers.map(s=>fe(async()=>{if(!s.ignoreLLM)try{await s.handleLLMError?.(t,this.runId,this._parentRunId,this.tags,a)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMError: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}async handleLLMEnd(t,e,r,n,a){await Promise.all(this.handlers.map(s=>fe(async()=>{if(!s.ignoreLLM)try{await s.handleLLMEnd?.(t,this.runId,this._parentRunId,this.tags,a)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMEnd: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}},Eu=class extends kr{getChild(t){const e=new Lt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleChainError(t,e,r,n,a){await Promise.all(this.handlers.map(s=>fe(async()=>{if(!s.ignoreChain)try{await s.handleChainError?.(t,this.runId,this._parentRunId,this.tags,a)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainError: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}async handleChainEnd(t,e,r,n,a){await Promise.all(this.handlers.map(s=>fe(async()=>{if(!s.ignoreChain)try{await s.handleChainEnd?.(t,this.runId,this._parentRunId,this.tags,a)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainEnd: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(e=>fe(async()=>{if(!e.ignoreAgent)try{await e.handleAgentAction?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentAction: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleAgentEnd(t){await Promise.all(this.handlers.map(e=>fe(async()=>{if(!e.ignoreAgent)try{await e.handleAgentEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},Su=class extends kr{getChild(t){const e=new Lt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleToolError(t){await Promise.all(this.handlers.map(e=>fe(async()=>{if(!e.ignoreAgent)try{await e.handleToolError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolError: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEnd(t){await Promise.all(this.handlers.map(e=>fe(async()=>{if(!e.ignoreAgent)try{await e.handleToolEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},Lt=class ir extends wu{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(e,r){super(),this.handlers=r?.handlers??this.handlers,this.inheritableHandlers=r?.inheritableHandlers??this.inheritableHandlers,this.tags=r?.tags??this.tags,this.inheritableTags=r?.inheritableTags??this.inheritableTags,this.metadata=r?.metadata??this.metadata,this.inheritableMetadata=r?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,r,n=void 0,a=void 0,s=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(r.map(async(u,l)=>{const d=l===0&&n?n:mt();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return Ut(f)&&f._createRunForLLMStart(e,[u],d,this._parentRunId,s,this.tags,this.metadata,c),fe(async()=>{try{await f.handleLLMStart?.(e,[u],d,this._parentRunId,s,this.tags,this.metadata,c)}catch(h){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${h}`),f.raiseError)throw h}},f.awaitHandlers)})),new es(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,r,n=void 0,a=void 0,s=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(r.map(async(u,l)=>{const d=l===0&&n?n:mt();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return Ut(f)&&f._createRunForChatModelStart(e,[u],d,this._parentRunId,s,this.tags,this.metadata,c),fe(async()=>{try{if(f.handleChatModelStart)await f.handleChatModelStart?.(e,[u],d,this._parentRunId,s,this.tags,this.metadata,c);else if(f.handleLLMStart){const h=Os(u);await f.handleLLMStart?.(e,[h],d,this._parentRunId,s,this.tags,this.metadata,c)}}catch(h){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${h}`),f.raiseError)throw h}},f.awaitHandlers)})),new es(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,r,n=mt(),a=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreChain)return Ut(c)&&c._createRunForChainStart(e,r,n,this._parentRunId,this.tags,this.metadata,a,o),fe(async()=>{try{await c.handleChainStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,a,o)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleChainStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new Eu(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,r,n=mt(),a=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreAgent)return Ut(c)&&c._createRunForToolStart(e,r,n,this._parentRunId,this.tags,this.metadata,o),fe(async()=>{try{await c.handleToolStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,o)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleToolStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new Su(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,r,n=mt(),a=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return Ut(c)&&c._createRunForRetrieverStart(e,r,n,this._parentRunId,this.tags,this.metadata,o),fe(async()=>{try{await c.handleRetrieverStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,o)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new bu(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,r,n,a,s){await Promise.all(this.handlers.map(i=>fe(async()=>{if(!i.ignoreCustomEvent)try{await i.handleCustomEvent?.(e,r,n,this.tags,this.metadata)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}addHandler(e,r=!0){this.handlers.push(e),r&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(r=>r!==e),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==e)}setHandlers(e,r=!0){this.handlers=[],this.inheritableHandlers=[];for(const n of e)this.addHandler(n,r)}addTags(e,r=!0){this.removeTags(e),this.tags.push(...e),r&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(r=>!e.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!e.includes(r))}addMetadata(e,r=!0){this.metadata={...this.metadata,...e},r&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(const r of Object.keys(e))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(e=[],r=!0){const n=new ir(this._parentRunId);for(const a of this.handlers){const s=this.inheritableHandlers.includes(a);n.addHandler(a,s)}for(const a of this.tags){const s=this.inheritableTags.includes(a);n.addTags([a],s)}for(const a of Object.keys(this.metadata)){const s=Object.keys(this.inheritableMetadata).includes(a);n.addMetadata({[a]:this.metadata[a]},s)}for(const a of e)n.handlers.filter(s=>s.name==="console_callback_handler").some(s=>s.name===a.name)||n.addHandler(a,r);return n}static fromHandlers(e){class r extends Rr{name=mt();constructor(){super(),Object.assign(this,e)}}const n=new this;return n.addHandler(new r),n}static configure(e,r,n,a,s,i,o){return this._configureSync(e,r,n,a,s,i,o)}static _configureSync(e,r,n,a,s,i,o){let c;(e||r)&&(Array.isArray(e)||!e?(c=new ir,c.setHandlers(e?.map(br)??[],!0)):c=e,c=c.copy(Array.isArray(r)?r.map(br):r?.handlers,!1));const u=It("LANGCHAIN_VERBOSE")==="true"||o?.verbose,l=Yr.getTraceableRunTree()?.tracingEnabled||pp(),d=l||(It("LANGCHAIN_TRACING")??!1);if(u||d){if(c||(c=new ir),u&&!c.handlers.some(f=>f.name===Xa.prototype.name)){const f=new Xa;c.addHandler(f,!0)}if(d&&!c.handlers.some(f=>f.name==="langchain_tracer")&&l){const f=new Yr;c.addHandler(f,!0)}if(l){const f=Yr.getTraceableRunTree();f&&c._parentRunId===void 0&&(c._parentRunId=f.id,c.handlers.find(p=>p.name==="langchain_tracer")?.updateFromRunTree(f))}}for(const{contextVar:f,inheritable:h=!0,handlerClass:p,envVar:m}of gp()){const g=m&&It(m)==="true"&&p;let y;const v=f!==void 0?vu(f):void 0;v&&Kc(v)?y=v:g&&(y=new p({})),y!==void 0&&(c||(c=new ir),c.handlers.some(_=>_.name===y.name)||c.addHandler(y,h))}return(n||a)&&c&&(c.addTags(n??[]),c.addTags(a??[],!1)),(s||i)&&c&&(c.addMetadata(s??{}),c.addMetadata(i??{},!1)),c}};function br(t){return"name"in t?t:Rr.fromMethods(t)}var Tu=class{getStore(){}run(t,e){return e()}enterWith(t){}};const vp=new Tu,qo=Symbol.for("lc:child_config");var wp=class{getInstance(){return vr()??vp}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[qo]}runWithConfig(t,e,r){const n=Lt._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata),a=this.getInstance(),s=a.getStore(),i=n?.getParentRunId(),o=n?.handlers?.find(u=>u?.name==="langchain_tracer");let c;return o&&i?c=o.getRunTreeWithTracingConfig(i):r||(c=new $e({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[qo]:t}),s!==void 0&&s[ur]!==void 0&&(c===void 0&&(c={}),c[ur]=s[ur]),a.run(c,e)}initializeGlobalInstance(t){vr()===void 0&&Ad(t)}};const lt=new wp;var bp={};ge(bp,{AsyncLocalStorageProviderSingleton:()=>lt,MockAsyncLocalStorage:()=>Tu,_CONTEXT_VARIABLES_KEY:()=>ur});const La=25;async function qe(t){return Lt._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata)}function Go(...t){const e={};for(const r of t.filter(n=>!!n))for(const n of Object.keys(r))if(n==="metadata")e[n]={...e[n],...r[n]};else if(n==="tags"){const a=e[n]??[];e[n]=[...new Set(a.concat(r[n]??[]))]}else if(n==="configurable")e[n]={...e[n],...r[n]};else if(n==="timeout")e.timeout===void 0?e.timeout=r.timeout:r.timeout!==void 0&&(e.timeout=Math.min(e.timeout,r.timeout));else if(n==="signal")e.signal===void 0?e.signal=r.signal:r.signal!==void 0&&("any"in AbortSignal?e.signal=AbortSignal.any([e.signal,r.signal]):e.signal=r.signal);else if(n==="callbacks"){const a=e.callbacks,s=r.callbacks;if(Array.isArray(s))if(!a)e.callbacks=s;else if(Array.isArray(a))e.callbacks=a.concat(s);else{const i=a.copy();for(const o of s)i.addHandler(br(o),!0);e.callbacks=i}else if(s)if(!a)e.callbacks=s;else if(Array.isArray(a)){const i=s.copy();for(const o of a)i.addHandler(br(o),!0);e.callbacks=i}else e.callbacks=new Lt(s._parentRunId,{handlers:a.handlers.concat(s.handlers),inheritableHandlers:a.inheritableHandlers.concat(s.inheritableHandlers),tags:Array.from(new Set(a.tags.concat(s.tags))),inheritableTags:Array.from(new Set(a.inheritableTags.concat(s.inheritableTags))),metadata:{...a.metadata,...s.metadata}})}else{const a=n;e[a]=r[a]??e[a]}return e}const Ep=new Set(["string","number","boolean"]);function ie(t){const e=lt.getRunnableConfig();let r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){const{runId:n,runName:a,...s}=e;r=Object.entries(s).reduce((i,[o,c])=>(c!==void 0&&(i[o]=c),i),r)}if(t&&(r=Object.entries(t).reduce((n,[a,s])=>(s!==void 0&&(n[a]=s),n),r)),r?.configurable)for(const n of Object.keys(r.configurable))Ep.has(typeof r.configurable[n])&&!r.metadata?.[n]&&(r.metadata||(r.metadata={}),r.metadata[n]=r.configurable[n]);if(r.timeout!==void 0){if(r.timeout<=0)throw new Error("Timeout must be a positive number");const n=r.timeout,a=AbortSignal.timeout(n);r.metadata||(r.metadata={}),r.metadata.timeoutMs===void 0&&(r.metadata.timeoutMs=n),r.signal!==void 0?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,a])):r.signal=a,delete r.timeout}return r}function be(t={},{callbacks:e,maxConcurrency:r,recursionLimit:n,runName:a,configurable:s,runId:i}={}){const o=ie(t);return e!==void 0&&(delete o.runName,o.callbacks=e),n!==void 0&&(o.recursionLimit=n),r!==void 0&&(o.maxConcurrency=r),a!==void 0&&(o.runName=a),s!==void 0&&(o.configurable={...o.configurable,...s}),i!==void 0&&delete o.runId,o}function Jt(t){if(t)return{configurable:t.configurable,recursionLimit:t.recursionLimit,callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,maxConcurrency:t.maxConcurrency,timeout:t.timeout,signal:t.signal,store:t.store}}async function wt(t,e){if(e===void 0)return t;let r;return Promise.race([t.catch(n=>{if(!e?.aborted)throw n}),new Promise((n,a)=>{r=()=>{a(un(e))},e.addEventListener("abort",r),e.aborted&&a(un(e))})]).finally(()=>e.removeEventListener("abort",r))}function un(t){return t?.reason instanceof Error?t.reason:typeof t?.reason=="string"?new Error(t.reason):new Error("Aborted")}var Sp={};ge(Sp,{AsyncGeneratorWithSetup:()=>Mt,IterableReadableStream:()=>Ge,atee:()=>zs,concat:()=>qs,pipeGeneratorWithSetup:()=>xu});var Ge=class ts extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){const r=this.reader.cancel();this.reader.releaseLock(),await r}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){const r=e.getReader();return new ts({start(n){return a();function a(){return r.read().then(({done:s,value:i})=>{if(s){n.close();return}return n.enqueue(i),a()})}},cancel(){r.releaseLock()}})}static fromAsyncGenerator(e){return new ts({async pull(r){const{value:n,done:a}=await e.next();a&&r.close(),r.enqueue(n)},async cancel(r){await e.return(r)}})}};function zs(t,e=2){const r=Array.from({length:e},()=>[]);return r.map(async function*(a){for(;;)if(a.length===0){const s=await t.next();for(const i of r)i.push(s)}else{if(a[0].done)return;yield a.shift().value}})}function qs(t,e){if(Array.isArray(t)&&Array.isArray(e))return t.concat(e);if(typeof t=="string"&&typeof e=="string")return t+e;if(typeof t=="number"&&typeof e=="number")return t+e;if("concat"in t&&typeof t.concat=="function")return t.concat(e);if(typeof t=="object"&&typeof e=="object"){const r={...t};for(const[n,a]of Object.entries(e))n in r&&!Array.isArray(r[n])?r[n]=qs(r[n],a):r[n]=a;return r}else throw new Error(`Cannot concat ${typeof t} and ${typeof e}`)}var Mt=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(t){this.generator=t.generator,this.config=t.config,this.signal=t.signal??this.config?.signal,this.setup=new Promise((e,r)=>{lt.runWithConfig(Jt(t.config),async()=>{this.firstResult=t.generator.next(),t.startSetup?this.firstResult.then(t.startSetup).then(e,r):this.firstResult.then(n=>e(void 0),r)},!0)})}async next(...t){return this.signal?.throwIfAborted(),this.firstResultUsed?lt.runWithConfig(Jt(this.config),this.signal?async()=>wt(this.generator.next(...t),this.signal):async()=>this.generator.next(...t),!0):(this.firstResultUsed=!0,this.firstResult)}async return(t){return this.generator.return(t)}async throw(t){return this.generator.throw(t)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function xu(t,e,r,n,...a){const s=new Mt({generator:e,startSetup:r,signal:n}),i=await s.setup;return{output:t(s,i,...a),setup:i}}const Tp=Object.prototype.hasOwnProperty;function xp(t,e){return Tp.call(t,e)}function Ip(t){if(Array.isArray(t)){const r=new Array(t.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(t);let e=[];for(let r in t)xp(t,r)&&e.push(r);return e}function kt(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function rs(t){let e=0;const r=t.length;let n;for(;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function cy(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function Ap(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function ns(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(ns(t[r]))return!0}else if(typeof t=="object"){const r=Ip(t),n=r.length;for(var e=0;e<n;e++)if(ns(t[r[e]]))return!0}}return!1}function Ho(t,e){const r=[t];for(const n in e){const a=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof a<"u"&&r.push(`${n}: ${a}`)}return r.join(`
|
|
54
|
+
`)}var $p=class extends Error{constructor(t,e,r,n,a){super(Ho(t,{name:e,index:r,operation:n,tree:a})),this.name=e,this.index=r,this.operation=n,this.tree=a,Object.setPrototypeOf(this,new.target.prototype),this.message=Ho(t,{name:e,index:r,operation:n,tree:a})}},Iu={};ge(Iu,{JsonPatchError:()=>ue,_areEquals:()=>Sr,applyOperation:()=>$t,applyPatch:()=>Er,applyReducer:()=>kp,deepClone:()=>Rp,getValueByPointer:()=>ln,validate:()=>Au,validator:()=>dn});const ue=$p,Rp=kt;function Ma(t){return Object.getOwnPropertyNames(Object.prototype).includes(t)}const Bt={add:function(t,e,r){if(Ma(e))throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");return t[e]=this.value,{newDocument:r}},remove:function(t,e,r){if(Ma(e))throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");var n=t[e];return delete t[e],{newDocument:r,removed:n}},replace:function(t,e,r){if(Ma(e))throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:function(t,e,r){let n=ln(r,this.path);n&&(n=kt(n));const a=$t(r,{op:"remove",path:this.from}).removed;return $t(r,{op:"add",path:this.path,value:a}),{newDocument:r,removed:n}},copy:function(t,e,r){const n=ln(r,this.from);return $t(r,{op:"add",path:this.path,value:kt(n)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:Sr(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}};var Op={add:function(t,e,r){return rs(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:Bt.move,copy:Bt.copy,test:Bt.test,_get:Bt._get};function ln(t,e){if(e=="")return t;var r={op:"_get",path:e};return $t(t,r),r.value}function $t(t,e,r=!1,n=!0,a=!0,s=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):dn(e,0)),e.path===""){let i={newDocument:t};if(e.op==="add")return i.newDocument=e.value,i;if(e.op==="replace")return i.newDocument=e.value,i.removed=t,i;if(e.op==="move"||e.op==="copy")return i.newDocument=ln(t,e.from),e.op==="move"&&(i.removed=t),i;if(e.op==="test"){if(i.test=Sr(t,e.value),i.test===!1)throw new ue("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i.newDocument=t,i}else{if(e.op==="remove")return i.removed=t,i.newDocument=null,i;if(e.op==="_get")return e.value=t,i;if(r)throw new ue("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,t);return i}}else{n||(t=kt(t));const o=(e.path||"").split("/");let c=t,u=1,l=o.length,d,f,h;for(typeof r=="function"?h=r:h=dn;;){if(f=o[u],f&&f.indexOf("~")!=-1&&(f=Ap(f)),a&&(f=="__proto__"||f=="prototype"&&u>0&&o[u-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&&d===void 0&&(c[f]===void 0?d=o.slice(0,u).join("/"):u==l-1&&(d=e.path),d!==void 0&&h(e,0,t,d)),u++,Array.isArray(c)){if(f==="-")f=c.length;else{if(r&&!rs(f))throw new ue("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);rs(f)&&(f=~~f)}if(u>=l){if(r&&e.op==="add"&&f>c.length)throw new ue("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,t);const p=Op[e.op].call(e,c,f,t);if(p.test===!1)throw new ue("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return p}}else if(u>=l){const p=Bt[e.op].call(e,c,f,t);if(p.test===!1)throw new ue("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return p}if(c=c[f],r&&u<l&&(!c||typeof c!="object"))throw new ue("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,t)}}}function Er(t,e,r,n=!0,a=!0){if(r&&!Array.isArray(e))throw new ue("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=kt(t));const s=new Array(e.length);for(let i=0,o=e.length;i<o;i++)s[i]=$t(t,e[i],r,!0,a,i),t=s[i].newDocument;return s.newDocument=t,s}function kp(t,e,r){const n=$t(t,e);if(n.test===!1)throw new ue("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function dn(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new ue("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(Bt[t.op]){if(typeof t.path!="string")throw new ue("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new ue('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 ue("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 ue("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")&&ns(t.value))throw new ue("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 a=t.path.split("/").length,s=n.split("/").length;if(a!==s+1&&a!==s)throw new ue("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 ue("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 i={op:"_get",path:t.from,value:void 0},o=Au([i],r);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new ue("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new ue("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function Au(t,e,r){try{if(!Array.isArray(t))throw new ue("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Er(kt(e),kt(t),r||!0);else{r=r||dn;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(a){if(a instanceof ue)return a;throw a}}function Sr(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),a,s,i;if(r&&n){if(s=t.length,s!=e.length)return!1;for(a=s;a--!==0;)if(!Sr(t[a],e[a]))return!1;return!0}if(r!=n)return!1;var o=Object.keys(t);if(s=o.length,s!==Object.keys(e).length)return!1;for(a=s;a--!==0;)if(!e.hasOwnProperty(o[a]))return!1;for(a=s;a--!==0;)if(i=o[a],!Sr(t[i],e[i]))return!1;return!0}return t!==t&&e!==e}({...Iu});var Cp={};ge(Cp,{LogStreamCallbackHandler:()=>ss,RunLog:()=>Gs,RunLogPatch:()=>rt,isLogStreamHandler:()=>$u});var rt=class{ops;constructor(t){this.ops=t.ops??[]}concat(t){const e=this.ops.concat(t.ops),r=Er({},e);return new Gs({ops:e,state:r[r.length-1].newDocument})}},Gs=class as extends rt{state;constructor(e){super(e),this.state=e.state}concat(e){const r=this.ops.concat(e.ops),n=Er(this.state,e.ops);return new as({ops:r,state:n[n.length-1].newDocument})}static fromRunLogPatch(e){const r=Er({},e.ops);return new as({ops:e.ops,state:r[r.length-1].newDocument})}};const $u=t=>t.name==="log_stream_tracer";async function Zo(t,e){if(e==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:r}=t;if(["retriever","llm","prompt"].includes(t.run_type))return r;if(!(Object.keys(r).length===1&&r?.input===""))return r.input}async function Vo(t,e){const{outputs:r}=t;return e==="original"||["retriever","llm","prompt"].includes(t.run_type)?r:r!==void 0&&Object.keys(r).length===1&&r?.output!==void 0?r.output:r}function Np(t){return t!==void 0&&t.message!==void 0}var ss=class extends Xt{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat="original";rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name="log_stream_tracer";lc_prefer_streaming=!0;constructor(t){super({_awaitHandler:!0,...t}),this.autoClose=t?.autoClose??!0,this.includeNames=t?.includeNames,this.includeTypes=t?.includeTypes,this.includeTags=t?.includeTags,this.excludeNames=t?.excludeNames,this.excludeTypes=t?.excludeTypes,this.excludeTags=t?.excludeTags,this._schemaFormat=t?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Ge.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(t){}_includeRun(t){if(t.id===this.rootId)return!1;const e=t.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(t.run_type)),this.includeTags!==void 0&&(r=r||e.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(t.run_type)),this.excludeTags!==void 0&&(r=r&&e.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(t,e){for await(const r of e){if(t!==this.rootId){const n=this.keyMapByRunId[t];n&&await this.writer.write(new rt({ops:[{op:"add",path:`/logs/${n}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(t){if(this.rootId===void 0&&(this.rootId=t.id,await this.writer.write(new rt({ops:[{op:"replace",path:"",value:{id:t.id,name:t.name,type:t.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(t))return;this.counterMapByRunName[t.name]===void 0&&(this.counterMapByRunName[t.name]=0),this.counterMapByRunName[t.name]+=1;const e=this.counterMapByRunName[t.name];this.keyMapByRunId[t.id]=e===1?t.name:`${t.name}:${e}`;const r={id:t.id,name:t.name,type:t.run_type,tags:t.tags??[],metadata:t.extra?.metadata??{},start_time:new Date(t.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(r.inputs=await Zo(t,this._schemaFormat)),await this.writer.write(new rt({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[t.id]}`,value:r}]}))}async onRunUpdate(t){try{const e=this.keyMapByRunId[t.id];if(e===void 0)return;const r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${e}/inputs`,value:await Zo(t,this._schemaFormat)}),r.push({op:"add",path:`/logs/${e}/final_output`,value:await Vo(t,this._schemaFormat)}),t.end_time!==void 0&&r.push({op:"add",path:`/logs/${e}/end_time`,value:new Date(t.end_time).toISOString()});const n=new rt({ops:r});await this.writer.write(n)}finally{if(t.id===this.rootId){const e=new rt({ops:[{op:"replace",path:"/final_output",value:await Vo(t,this._schemaFormat)}]});await this.writer.write(e),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(t,e,r){const n=this.keyMapByRunId[t.id];if(n===void 0)return;const a=t.inputs.messages!==void 0;let s;a?Np(r?.chunk)?s=r?.chunk:s=new Pt({id:`run-${t.id}`,content:e}):s=e;const i=new rt({ops:[{op:"add",path:`/logs/${n}/streamed_output_str/-`,value:e},{op:"add",path:`/logs/${n}/streamed_output/-`,value:s}]});await this.writer.write(i)}},Pp={};ge(Pp,{ChatGenerationChunk:()=>Mp,GenerationChunk:()=>fn,RUN_KEY:()=>Lp});const Lp="__run";var fn=class Ru{text;generationInfo;constructor(e){this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new Ru({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}},Mp=class Ou extends fn{message;constructor(e){super(e),this.message=e.message}concat(e){return new Ou({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo},message:this.message.concat(e.message)})}};function Vr({name:t,serialized:e}){return t!==void 0?t:e?.name!==void 0?e.name:e?.id!==void 0&&Array.isArray(e?.id)?e.id[e.id.length-1]:"Unnamed"}const jp=t=>t.name==="event_stream_tracer";var Dp=class extends Xt{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;name="event_stream_tracer";lc_prefer_streaming=!0;constructor(t){super({_awaitHandler:!0,...t}),this.autoClose=t?.autoClose??!0,this.includeNames=t?.includeNames,this.includeTypes=t?.includeTypes,this.includeTags=t?.includeTags,this.excludeNames=t?.excludeNames,this.excludeTypes=t?.excludeTypes,this.excludeTags=t?.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Ge.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(t){}_includeRun(t){const e=t.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(t.runType)),this.includeTags!==void 0&&(r=r||e.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(t.runType)),this.excludeTags!==void 0&&(r=r&&e.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(t,e){const r=await e.next();if(r.done)return;const n=this.runInfoMap.get(t);if(n===void 0){yield r.value;return}function a(i,o){return i==="llm"&&typeof o=="string"?new fn({text:o}):o}let s=this.tappedPromises.get(t);if(s===void 0){let i;s=new Promise(o=>{i=o}),this.tappedPromises.set(t,s);try{const o={event:`on_${n.runType}_stream`,run_id:t,name:n.name,tags:n.tags,metadata:n.metadata,data:{}};await this.send({...o,data:{chunk:a(n.runType,r.value)}},n),yield r.value;for await(const c of e)n.runType!=="tool"&&n.runType!=="retriever"&&await this.send({...o,data:{chunk:a(n.runType,c)}},n),yield c}finally{i?.()}}else{yield r.value;for await(const i of e)yield i}}async send(t,e){this._includeRun(e)&&await this.writer.write(t)}async sendEndEvent(t,e){const r=this.tappedPromises.get(t.run_id);r!==void 0?r.then(()=>{this.send(t,e)}):await this.send(t,e)}async onLLMStart(t){const e=Vr(t),r=t.inputs.messages!==void 0?"chat_model":"llm",n={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:r,inputs:t.inputs};this.runInfoMap.set(t.id,n);const a=`on_${r}_start`;await this.send({event:a,data:{input:t.inputs},name:e,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},n)}async onLLMNewToken(t,e,r){const n=this.runInfoMap.get(t.id);let a,s;if(n===void 0)throw new Error(`onLLMNewToken: Run ID ${t.id} not found in run map.`);if(this.runInfoMap.size!==1){if(n.runType==="chat_model")s="on_chat_model_stream",r?.chunk===void 0?a=new Pt({content:e,id:`run-${t.id}`}):a=r.chunk.message;else if(n.runType==="llm")s="on_llm_stream",r?.chunk===void 0?a=new fn({text:e}):a=r.chunk;else throw new Error(`Unexpected run type ${n.runType}`);await this.send({event:s,data:{chunk:a},run_id:t.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}}async onLLMEnd(t){const e=this.runInfoMap.get(t.id);this.runInfoMap.delete(t.id);let r;if(e===void 0)throw new Error(`onLLMEnd: Run ID ${t.id} not found in run map.`);const n=t.outputs?.generations;let a;if(e.runType==="chat_model"){for(const s of n??[]){if(a!==void 0)break;a=s[0]?.message}r="on_chat_model_end"}else if(e.runType==="llm")a={generations:n?.map(s=>s.map(i=>({text:i.text,generationInfo:i.generationInfo}))),llmOutput:t.outputs?.llmOutput??{}},r="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${e.runType}`);await this.sendEndEvent({event:r,data:{output:a,input:e.inputs},run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata},e)}async onChainStart(t){const e=Vr(t),r=t.run_type??"chain",n={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:t.run_type};let a={};t.inputs.input===""&&Object.keys(t.inputs).length===1?(a={},n.inputs={}):t.inputs.input!==void 0?(a.input=t.inputs.input,n.inputs=t.inputs.input):(a.input=t.inputs,n.inputs=t.inputs),this.runInfoMap.set(t.id,n),await this.send({event:`on_${r}_start`,data:a,name:e,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},n)}async onChainEnd(t){const e=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),e===void 0)throw new Error(`onChainEnd: Run ID ${t.id} not found in run map.`);const r=`on_${t.run_type}_end`,n=t.inputs??e.inputs??{},s={output:t.outputs?.output??t.outputs,input:n};n.input&&Object.keys(n).length===1&&(s.input=n.input,e.inputs=n.input),await this.sendEndEvent({event:r,data:s,run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata??{}},e)}async onToolStart(t){const e=Vr(t),r={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:"tool",inputs:t.inputs??{}};this.runInfoMap.set(t.id,r),await this.send({event:"on_tool_start",data:{input:t.inputs??{}},name:e,run_id:t.id,tags:t.tags??[],metadata:t.extra?.metadata??{}},r)}async onToolEnd(t){const e=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),e===void 0)throw new Error(`onToolEnd: Run ID ${t.id} not found in run map.`);if(e.inputs===void 0)throw new Error(`onToolEnd: Run ID ${t.id} is a tool call, and is expected to have traced inputs.`);const r=t.outputs?.output===void 0?t.outputs:t.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:e.inputs},run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata},e)}async onRetrieverStart(t){const e=Vr(t),n={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:"retriever",inputs:{query:t.inputs.query}};this.runInfoMap.set(t.id,n),await this.send({event:"on_retriever_start",data:{input:{query:t.inputs.query}},name:e,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},n)}async onRetrieverEnd(t){const e=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),e===void 0)throw new Error(`onRetrieverEnd: Run ID ${t.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:t.outputs?.documents??t.outputs,input:e.inputs},run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata},e)}async handleCustomEvent(t,e,r){const n=this.runInfoMap.get(r);if(n===void 0)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:t,tags:n.tags,metadata:n.metadata,data:e},n)}async finish(){const t=[...this.tappedPromises.values()];Promise.all(t).finally(()=>{this.writer.close()})}};const Up=Object.prototype.toString,Fp=t=>Up.call(t)==="[object Error]",Bp=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function zp(t){if(!(t&&Fp(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;const{message:r,stack:n}=t;return r==="Load failed"?n===void 0||"__sentry_captured__"in t:r.startsWith("error sending request for url")?!0:Bp.has(r)}function qp(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Wr(t,e,{min:r=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<r)throw new TypeError(`Expected \`${t}\` to be ≥ ${r}.`)}}var Gp=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}};function Hp(t,e){const r=Math.max(1,t+1),n=e.randomize?Math.random()+1:1;let a=Math.round(n*e.minTimeout*e.factor**(r-1));return a=Math.min(a,e.maxTimeout),a}function Wo(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}async function Zp({error:t,attemptNumber:e,retriesConsumed:r,startTime:n,options:a}){const s=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(s instanceof Gp)throw s.originalError;const i=Number.isFinite(a.retries)?Math.max(0,a.retries-r):a.retries,o=a.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:r});if(await a.onFailedAttempt(c),Wo(n,o)<=0)throw s;const u=await a.shouldConsumeRetry(c),l=Wo(n,o);if(l<=0||i<=0)throw s;if(s instanceof TypeError&&!zp(s)){if(u)throw s;return a.signal?.throwIfAborted(),!1}if(!await a.shouldRetry(c))throw s;if(!u)return a.signal?.throwIfAborted(),!1;const d=Hp(r,a),f=Math.min(d,l);return f>0&&await new Promise((h,p)=>{const m=()=>{clearTimeout(g),a.signal?.removeEventListener("abort",m),p(a.signal.reason)},g=setTimeout(()=>{a.signal?.removeEventListener("abort",m),h()},f);a.unref&&g.unref?.(),a.signal?.addEventListener("abort",m,{once:!0})}),a.signal?.throwIfAborted(),!0}async function is(t,e={}){if(e={...e},qp(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,Wr("factor",e.factor,{min:0,allowInfinity:!1}),Wr("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Wr("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Wr("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let r=0,n=0;const a=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){r++;try{e.signal?.throwIfAborted();const s=await t(r);return e.signal?.throwIfAborted(),s}catch(s){await Zp({error:s,attemptNumber:r,retriesConsumed:n,startTime:a,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Vp={};ge(Vp,{AsyncCaller:()=>ku});const Wp=[400,401,402,403,404,405,406,407,409],Jp=t=>{if(t.message.startsWith("Cancel")||t.message.startsWith("AbortError")||t.name==="AbortError"||t?.code==="ECONNABORTED")throw t;const e=t?.response?.status??t?.status;if(e&&Wp.includes(+e))throw t;if(t?.error?.code==="insufficient_quota"){const r=new Error(t?.message);throw r.name="InsufficientQuotaError",r}};var ku=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(t){this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,this.onFailedAttempt=t.onFailedAttempt??Jp;const e="default"in st?st.default:st;this.queue=new e({concurrency:this.maxConcurrency})}async call(t,...e){return this.queue.add(()=>is(()=>t(...e).catch(r=>{throw r instanceof Error?r:new Error(r)}),{onFailedAttempt:({error:r})=>this.onFailedAttempt?.(r),retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(t,e,...r){if(t.signal){let n;return Promise.race([this.call(e,...r),new Promise((a,s)=>{n=()=>{s(un(t.signal))},t.signal?.addEventListener("abort",n)})]).finally(()=>{t.signal&&n&&t.signal.removeEventListener("abort",n)})}return this.call(e,...r)}fetch(...t){return this.call(()=>fetch(...t).then(e=>e.ok?e:Promise.reject(e)))}},Cu=class extends Xt{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:t,onStart:e,onEnd:r,onError:n}){super({_awaitHandler:!0}),this.config=t,this.argOnStart=e,this.argOnEnd=r,this.argOnError=n}persistRun(t){return Promise.resolve()}async onRunCreate(t){this.rootId||(this.rootId=t.id,this.argOnStart&&await this.argOnStart(t,this.config))}async onRunUpdate(t){t.id===this.rootId&&(t.error?this.argOnError&&await this.argOnError(t,this.config):this.argOnEnd&&await this.argOnEnd(t,this.config))}};function Hs(t){return t?t.lc_runnable:!1}var Kp=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(t){this.includeNames=t.includeNames,this.includeTypes=t.includeTypes,this.includeTags=t.includeTags,this.excludeNames=t.excludeNames,this.excludeTypes=t.excludeTypes,this.excludeTags=t.excludeTags}includeEvent(t,e){let r=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0;const n=t.tags??[];return this.includeNames!==void 0&&(r=r||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e)),this.includeTags!==void 0&&(r=r||n.some(a=>this.includeTags?.includes(a))),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e)),this.excludeTags!==void 0&&(r=r&&n.every(a=>!this.excludeTags?.includes(a))),r}};const Yp=t=>btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");function le(t){if(typeof t!="object"||t===null)return!1;const e=t;if(!("_zod"in e))return!1;const r=e._zod;return typeof r=="object"&&r!==null&&"def"in r}function ye(t){if(typeof t!="object"||t===null)return!1;const e=t;if(!("_def"in e)||"_zod"in e)return!1;const r=e._def;return typeof r=="object"&&r!=null&&"typeName"in r}function uy(t){return le(t)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),ye(t)}function Nu(t){return!t||typeof t!="object"||Array.isArray(t)?!1:!!(le(t)||ye(t))}function Qp(t){return typeof t=="object"&&t!==null&&"_def"in t&&typeof t._def=="object"&&t._def!==null&&"typeName"in t._def&&t._def.typeName==="ZodLiteral"}function Xp(t){return le(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="literal":!1}function ly(t){return!!(Qp(t)||Xp(t))}async function dy(t,e){if(le(t))try{return{success:!0,data:await uc(t,e)}}catch(r){return{success:!1,error:r}}if(ye(t))return await t.safeParseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function em(t,e){if(le(t))return await uc(t,e);if(ye(t))return await t.parseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function fy(t,e){if(le(t))try{return{success:!0,data:ls(t,e)}}catch(r){return{success:!1,error:r}}if(ye(t))return t.safeParse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function hy(t,e){if(le(t))return ls(t,e);if(ye(t))return t.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function tm(t){if(le(t))return Pe.get(t)?.description;if(ye(t)||"description"in t&&typeof t.description=="string")return t.description}function py(t){if(!Nu(t))return!1;if(ye(t)){const e=t._def;if(e.typeName==="ZodObject"){const r=t;return!r.shape||Object.keys(r.shape).length===0}if(e.typeName==="ZodRecord")return!0}if(le(t)){const e=t._zod.def;if(e.type==="object"){const r=t;return!r.shape||Object.keys(r.shape).length===0}if(e.type==="record")return!0}return typeof t=="object"&&t!==null&&!("shape"in t)}function rm(t){return Nu(t)?ye(t)?t._def.typeName==="ZodString":le(t)?t._zod.def.type==="string":!1:!1}function Pu(t){return typeof t=="object"&&t!==null&&"_def"in t&&typeof t._def=="object"&&t._def!==null&&"typeName"in t._def&&t._def.typeName==="ZodObject"}function it(t){return le(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="object":!1}function Zs(t){return le(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="array":!1}function nm(t){return le(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="optional":!1}function am(t){return le(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="nullable":!1}function my(t){return!!(Pu(t)||it(t))}function Jo(t){if(ye(t))return t.shape;if(le(t))return t._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function gy(t,e){if(ye(t))return t.extend(e);if(le(t))return cl(t,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function yy(t){if(ye(t))return t.partial();if(le(t))return ul(lc,t,void 0);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function os(t,e=!1){if(ye(t))return t.strict();if(it(t)){const r=t._zod.def.shape;if(e)for(const[s,i]of Object.entries(t._zod.def.shape)){if(it(i)){const c=os(i,e);r[s]=c}else if(Zs(i)){let c=i._zod.def.element;it(c)&&(c=os(c,e)),r[s]=nt(i,{...i._zod.def,element:c})}else r[s]=i;const o=Pe.get(i);o&&Pe.add(r[s],o)}const n=nt(t,{...t._zod.def,shape:r,catchall:il(ol)}),a=Pe.get(t);return a&&Pe.add(n,a),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Ko(t,e=!1){if(Pu(t))return t.passthrough();if(it(t)){const r=t._zod.def.shape;if(e)for(const[s,i]of Object.entries(t._zod.def.shape)){if(it(i)){const c=Ko(i,e);r[s]=c}else if(Zs(i)){let c=i._zod.def.element;it(c)&&(c=Ko(c,e)),r[s]=nt(i,{...i._zod.def,element:c})}else r[s]=i;const o=Pe.get(i);o&&Pe.add(r[s],o)}const n=nt(t,{...t._zod.def,shape:r,catchall:ll(dl)}),a=Pe.get(t);return a&&Pe.add(n,a),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function _y(t){if(ye(t))try{const e=t.parse(void 0);return()=>e}catch{return}if(le(t))try{const e=ls(t,void 0);return()=>e}catch{return}}function sm(t){return ye(t)&&"typeName"in t._def&&t._def.typeName==="ZodEffects"}function im(t){return le(t)&&t._zod.def.type==="pipe"}function St(t,e,r){const n=r.get(t);if(n!==void 0)return n;if(ye(t))return sm(t)?St(t._def.schema,e,r):t;if(le(t)){let a=t;if(im(t)&&(a=St(t._zod.def.in,e,r)),e){if(it(a)){const i={};for(const[o,c]of Object.entries(a._zod.def.shape))i[o]=St(c,e,r);a=nt(a,{...a._zod.def,shape:i})}else if(Zs(a)){const i=St(a._zod.def.element,e,r);a=nt(a,{...a._zod.def,element:i})}else if(nm(a)){const i=St(a._zod.def.innerType,e,r);a=nt(a,{...a._zod.def,innerType:i})}else if(am(a)){const i=St(a._zod.def.innerType,e,r);a=nt(a,{...a._zod.def,innerType:i})}}const s=Pe.get(t);return s&&Pe.add(a,s),r.set(t,a),a}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function om(t,e=!1){return St(t,e,new WeakMap)}function vy(t,e){if(ye(t)){const r=Jo(t),n={};for(const[a,s]of Object.entries(r))e(a,s)?n[a]=s.optional():n[a]=s;return t.extend(n)}if(le(t)){const r=Jo(t),n={...t._zod.def.shape};for(const[i,o]of Object.entries(r))e(i,o)&&(n[i]=new lc({type:"optional",innerType:o}));const a=nt(t,{...t._zod.def,shape:n}),s=Pe.get(t);return s&&Pe.add(a,s),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function wy(t){return t instanceof Error&&(t.constructor.name==="ZodError"||t.constructor.name==="$ZodError")}function ja(t){return t.replace(/[^a-zA-Z-_0-9]/g,"_")}const cm=["*","_","`"];function um(t){let e="";for(const[r,n]of Object.entries(t))e+=` classDef ${r} ${n};
|
|
55
|
+
`;return e}function lm(t,e,r){const{firstNode:n,lastNode:a,nodeColors:s,withStyles:i=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=r??{};let u=i?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
|
|
56
|
+
graph TD;
|
|
57
|
+
`:`graph TD;
|
|
58
|
+
`;if(i){const p="default",m={[p]:"{0}({1})"};n!==void 0&&(m[n]="{0}([{1}]):::first"),a!==void 0&&(m[a]="{0}([{1}]):::last");for(const[g,y]of Object.entries(t)){const v=y.name.split(":").pop()??"";let S=cm.some(U=>v.startsWith(U)&&v.endsWith(U))?`<p>${v}</p>`:v;Object.keys(y.metadata??{}).length&&(S+=`<hr/><small><em>${Object.entries(y.metadata??{}).map(([U,z])=>`${U} = ${z}`).join(`
|
|
59
|
+
`)}</em></small>`);const R=(m[g]??m[p]).replace("{0}",ja(g)).replace("{1}",S);u+=` ${R}
|
|
60
|
+
`}}const l={};for(const p of e){const m=p.source.split(":"),g=p.target.split(":"),y=m.filter((v,_)=>v===g[_]).join(":");l[y]||(l[y]=[]),l[y].push(p)}const d=new Set;function f(p){return[...p].sort((m,g)=>m.split(":").length-g.split(":").length)}function h(p,m){const g=p.length===1&&p[0].source===p[0].target;if(m&&!g){const v=m.split(":").pop();if(d.has(m))throw new Error(`Found duplicate subgraph '${v}' at '${m} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(m),u+=` subgraph ${v}
|
|
61
|
+
`}const y=f(Object.keys(l).filter(v=>v.startsWith(`${m}:`)&&v!==m&&v.split(":").length===m.split(":").length+1));for(const v of y)h(l[v],v);for(const v of p){const{source:_,target:S,data:R,conditional:U}=v;let z="";if(R!==void 0){let I=R;const oe=I.split(" ");oe.length>c&&(I=Array.from({length:Math.ceil(oe.length/c)},(he,we)=>oe.slice(we*c,(we+1)*c).join(" ")).join(" <br> ")),z=U?` -. ${I} .-> `:` -- ${I} --> `}else z=U?" -.-> ":" --> ";u+=` ${ja(_)}${z}${ja(S)};
|
|
62
|
+
`}m&&!g&&(u+=` end
|
|
63
|
+
`)}h(l[""]??[],"");for(const p in l)!p.includes(":")&&p!==""&&h(l[p],p);return i&&(u+=um(s??{})),u}async function dm(t,e){let r=e?.backgroundColor??"white";const n=e?.imageType??"png",a=Yp(t);r!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));const s=`https://mermaid.ink/img/${a}?bgColor=${r}&type=${n}`,i=await fetch(s);if(!i.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join(`
|
|
64
|
+
`));return await i.blob()}const fm=Symbol("Let zodToJsonSchema decide on which parser to use"),hm={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},pm=t=>({...hm,...t}),mm=t=>{const e=pm(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,a])=>[a._def,{def:a._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}},Lu=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function Ce(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Lu(e,t.currentPath):e.join("/")}}function Mu(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ae(t,e,r,n,a){t[e]=r,Mu(t,e,n,a)}function gm(t,e){const r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==b.ZodAny&&(r.items=re(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ae(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ae(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ae(r,"minItems",t.exactLength.value,t.exactLength.message,e),ae(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function ym(t,e){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ae(r,"minimum",n.value,n.message,e):ae(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ae(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ae(r,"maximum",n.value,n.message,e):ae(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ae(r,"maximum",n.value,n.message,e));break;case"multipleOf":ae(r,"multipleOf",n.value,n.message,e);break}return r}function _m(){return{type:"boolean"}}function ju(t,e){return re(t.type._def,e)}const vm=(t,e)=>re(t.innerType._def,e);function Du(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(a=>Du(t,e,a))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return wm(t,e)}}const wm=(t,e)=>{const r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(const n of t.checks)switch(n.kind){case"min":ae(r,"minimum",n.value,n.message,e);break;case"max":ae(r,"maximum",n.value,n.message,e);break}return r};function bm(t,e){return{...re(t.innerType._def,e),default:t.defaultValue()}}function Em(t,e){return e.effectStrategy==="input"?re(t.schema._def,e):Ce(e)}function Sm(t){return{type:"string",enum:Array.from(t.values)}}const Tm=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function xm(t,e){const r=[re(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),re(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const a=[];return r.forEach(s=>{if(Tm(s))a.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:o,...c}=s;i=c}else n=void 0;a.push(i)}}),a.length?{allOf:a,...n}:void 0}function Im(t,e){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}let Da;const Ue={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Da===void 0&&(Da=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Da),uuid:/^[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}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Uu(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":ae(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ae(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Fe(r,"email",n.message,e);break;case"format:idn-email":Fe(r,"idn-email",n.message,e);break;case"pattern:zod":Se(r,Ue.email,n.message,e);break}break;case"url":Fe(r,"uri",n.message,e);break;case"uuid":Fe(r,"uuid",n.message,e);break;case"regex":Se(r,n.regex,n.message,e);break;case"cuid":Se(r,Ue.cuid,n.message,e);break;case"cuid2":Se(r,Ue.cuid2,n.message,e);break;case"startsWith":Se(r,RegExp(`^${Ua(n.value,e)}`),n.message,e);break;case"endsWith":Se(r,RegExp(`${Ua(n.value,e)}$`),n.message,e);break;case"datetime":Fe(r,"date-time",n.message,e);break;case"date":Fe(r,"date",n.message,e);break;case"time":Fe(r,"time",n.message,e);break;case"duration":Fe(r,"duration",n.message,e);break;case"length":ae(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ae(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":Se(r,RegExp(Ua(n.value,e)),n.message,e);break;case"ip":n.version!=="v6"&&Fe(r,"ipv4",n.message,e),n.version!=="v4"&&Fe(r,"ipv6",n.message,e);break;case"base64url":Se(r,Ue.base64url,n.message,e);break;case"jwt":Se(r,Ue.jwt,n.message,e);break;case"cidr":n.version!=="v6"&&Se(r,Ue.ipv4Cidr,n.message,e),n.version!=="v4"&&Se(r,Ue.ipv6Cidr,n.message,e);break;case"emoji":Se(r,Ue.emoji(),n.message,e);break;case"ulid":Se(r,Ue.ulid,n.message,e);break;case"base64":switch(e.base64Strategy){case"format:binary":Fe(r,"binary",n.message,e);break;case"contentEncoding:base64":ae(r,"contentEncoding","base64",n.message,e);break;case"pattern:zod":Se(r,Ue.base64,n.message,e);break}break;case"nanoid":Se(r,Ue.nanoid,n.message,e);break}return r}function Ua(t,e){return e.patternStrategy==="escape"?$m(t):t}const Am=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function $m(t){let e="";for(let r=0;r<t.length;r++)Am.has(t[r])||(e+="\\"),e+=t[r];return e}function Fe(t,e,r,n){t.format||t.anyOf?.some(a=>a.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ae(t,"format",e,r,n)}function Se(t,e,r,n){t.pattern||t.allOf?.some(a=>a.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Yo(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ae(t,"pattern",Yo(e,n),r,n)}function Yo(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source;let a="",s=!1,i=!1,o=!1;for(let c=0;c<n.length;c++){if(s){a+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){o?(a+=n[c],a+=`${n[c-2]}-${n[c]}`.toUpperCase(),o=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(a+=n[c],o=!0):a+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){a+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){a+=`(^|(?<=[\r
|
|
65
|
+
]))`;continue}else if(n[c]==="$"){a+=`($|(?=[\r
|
|
66
|
+
]))`;continue}}if(r.s&&n[c]==="."){a+=i?`${n[c]}\r
|
|
67
|
+
`:`[${n[c]}\r
|
|
68
|
+
]`;continue}a+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return a}function Fu(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===b.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,a)=>({...n,[a]:re(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",a]})??Ce(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const r={type:"object",additionalProperties:re(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===b.ZodString&&t.keyType._def.checks?.length){const{type:n,...a}=Uu(t.keyType._def,e);return{...r,propertyNames:a}}else{if(t.keyType?._def.typeName===b.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===b.ZodBranded&&t.keyType._def.type._def.typeName===b.ZodString&&t.keyType._def.type._def.checks?.length){const{type:n,...a}=ju(t.keyType._def,e);return{...r,propertyNames:a}}}return r}function Rm(t,e){if(e.mapStrategy==="record")return Fu(t,e);const r=re(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ce(e),n=re(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ce(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Om(t){const e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),a=Array.from(new Set(n.map(s=>typeof s)));return{type:a.length===1?a[0]==="string"?"string":"number":["string","number"],enum:n}}function km(t){return t.target==="openAi"?void 0:{not:Ce({...t,currentPath:[...t.currentPath,"not"]})}}function Cm(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const hn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Nm(t,e){if(e.target==="openApi3")return Qo(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in hn&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((a,s)=>{const i=hn[s._def.typeName];return i&&!a.includes(i)?[...a,i]:a},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((a,s)=>{const i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...a,i];case"bigint":return[...a,"integer"];case"object":return s._def.value===null?[...a,"null"]:a;case"symbol":case"undefined":case"function":default:return a}},[]);if(n.length===r.length){const a=n.filter((s,i,o)=>o.indexOf(s)===i);return{type:a.length>1?a:a[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,a)=>[...n,...a._def.values.filter(s=>!n.includes(s))],[])};return Qo(t,e)}const Qo=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,a)=>re(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${a}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Pm(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:hn[t.innerType._def.typeName],nullable:!0}:{type:[hn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=re(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=re(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Lm(t,e){const r={type:"number"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"int":r.type="integer",Mu(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ae(r,"minimum",n.value,n.message,e):ae(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ae(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ae(r,"maximum",n.value,n.message,e):ae(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ae(r,"maximum",n.value,n.message,e));break;case"multipleOf":ae(r,"multipleOf",n.value,n.message,e);break}return r}function Mm(t,e){const r=e.target==="openAi",n={type:"object",properties:{}},a=[],s=t.shape();for(const o in s){let c=s[o];if(c===void 0||c._def===void 0)continue;let u=Dm(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=re(c._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});l!==void 0&&(n.properties[o]=l,u||a.push(o))}a.length&&(n.required=a);const i=jm(t,e);return i!==void 0&&(n.additionalProperties=i),n}function jm(t,e){if(t.catchall._def.typeName!=="ZodNever")return re(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Dm(t){try{return t.isOptional()}catch{return!0}}const Um=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return re(t.innerType._def,e);const r=re(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ce(e)},r]}:Ce(e)},Fm=(t,e)=>{if(e.pipeStrategy==="input")return re(t.in._def,e);if(e.pipeStrategy==="output")return re(t.out._def,e);const r=re(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=re(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(a=>a!==void 0)}};function Bm(t,e){return re(t.type._def,e)}function zm(t,e){const n={type:"array",uniqueItems:!0,items:re(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ae(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ae(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function qm(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>re(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:re(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>re(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Gm(t){return{not:Ce(t)}}function Hm(t){return Ce(t)}const Zm=(t,e)=>re(t.innerType._def,e),Vm=(t,e,r)=>{switch(e){case b.ZodString:return Uu(t,r);case b.ZodNumber:return Lm(t,r);case b.ZodObject:return Mm(t,r);case b.ZodBigInt:return ym(t,r);case b.ZodBoolean:return _m();case b.ZodDate:return Du(t,r);case b.ZodUndefined:return Gm(r);case b.ZodNull:return Cm(r);case b.ZodArray:return gm(t,r);case b.ZodUnion:case b.ZodDiscriminatedUnion:return Nm(t,r);case b.ZodIntersection:return xm(t,r);case b.ZodTuple:return qm(t,r);case b.ZodRecord:return Fu(t,r);case b.ZodLiteral:return Im(t,r);case b.ZodEnum:return Sm(t);case b.ZodNativeEnum:return Om(t);case b.ZodNullable:return Pm(t,r);case b.ZodOptional:return Um(t,r);case b.ZodMap:return Rm(t,r);case b.ZodSet:return zm(t,r);case b.ZodLazy:return()=>t.getter()._def;case b.ZodPromise:return Bm(t,r);case b.ZodNaN:case b.ZodNever:return km(r);case b.ZodEffects:return Em(t,r);case b.ZodAny:return Ce(r);case b.ZodUnknown:return Hm(r);case b.ZodDefault:return bm(t,r);case b.ZodBranded:return ju(t,r);case b.ZodReadonly:return Zm(t,r);case b.ZodCatch:return vm(t,r);case b.ZodPipeline:return Fm(t,r);case b.ZodFunction:case b.ZodVoid:case b.ZodSymbol:return;default:return(n=>{})()}};function re(t,e,r=!1){const n=e.seen.get(t);if(e.override){const o=e.override?.(t,e,n,r);if(o!==fm)return o}if(n&&!r){const o=Wm(n,e);if(o!==void 0)return o}const a={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,a);const s=Vm(t,t.typeName,e),i=typeof s=="function"?re(s(),e):s;if(i&&Jm(t,e,i),e.postProcess){const o=e.postProcess(i,t,e);return a.jsonSchema=i,o}return a.jsonSchema=i,i}const Wm=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Lu(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Ce(e)):e.$refStrategy==="seen"?Ce(e):void 0}},Jm=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),Km=(t,e)=>{const r=mm(e);let n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((o,[c,u])=>({...o,[c]:re(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??Ce(r)}),{}):void 0;const a=typeof e=="string"?e:e?.name,s=re(t._def,r,!1)??Ce(r);r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const i=a===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,a].join("/"),[r.definitionPath]:{...n,[a]:s}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};function qt(t,e){const r=typeof t;if(r!==typeof e)return!1;if(Array.isArray(t)){if(!Array.isArray(e))return!1;const n=t.length;if(n!==e.length)return!1;for(let a=0;a<n;a++)if(!qt(t[a],e[a]))return!1;return!0}if(r==="object"){if(!t||!e)return t===e;const n=Object.keys(t),a=Object.keys(e);if(n.length!==a.length)return!1;for(const i of n)if(!qt(t[i],e[i]))return!1;return!0}return t===e}function Be(t){return encodeURI(Ym(t))}function Ym(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}const Qm={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Xm={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},eg={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};let tg=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function gt(t,e=Object.create(null),r=tg,n=""){if(t&&typeof t=="object"&&!Array.isArray(t)){const s=t.$id||t.id;if(s){const i=new URL(s,r.href);i.hash.length>1?e[i.href]=t:(i.hash="",n===""?r=i:gt(t,e,r))}}else if(t!==!0&&t!==!1)return e;const a=r.href+(n?"#"+n:"");if(e[a]!==void 0)throw new Error(`Duplicate schema URI "${a}".`);if(e[a]=t,t===!0||t===!1)return e;if(t.__absolute_uri__===void 0&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:a}),t.$ref&&t.__absolute_ref__===void 0){const s=new URL(t.$ref,r.href);s.hash=s.hash,Object.defineProperty(t,"__absolute_ref__",{enumerable:!1,value:s.href})}if(t.$recursiveRef&&t.__absolute_recursive_ref__===void 0){const s=new URL(t.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(t,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(t.$anchor){const s=new URL("#"+t.$anchor,r.href);e[s.href]=t}for(let s in t){if(eg[s])continue;const i=`${n}/${Be(s)}`,o=t[s];if(Array.isArray(o)){if(Qm[s]){const c=o.length;for(let u=0;u<c;u++)gt(o[u],e,r,`${i}/${u}`)}}else if(Xm[s])for(let c in o)gt(o[c],e,r,`${i}/${Be(c)}`);else gt(o,e,r,i)}return e}const rg=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,ng=[0,31,28,31,30,31,30,31,31,30,31,30,31],ag=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,sg=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ig=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,og=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,cg=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,ug=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,lg=/^(?:\/(?:[^~/]|~0|~1)*)*$/,dg=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,fg=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,hg=t=>{if(t[0]==='"')return!1;const[e,r,...n]=t.split("@");return!e||!r||n.length!==0||e.length>64||r.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:r.split(".").every(a=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(a))},pg=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,mg=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,gg=t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t));function Je(t){return t.test.bind(t)}const Xo={date:Bu,time:zu.bind(void 0,!1),"date-time":vg,duration:gg,uri:Eg,"uri-reference":Je(ig),"uri-template":Je(og),url:Je(cg),email:hg,hostname:Je(sg),ipv4:Je(pg),ipv6:Je(mg),regex:Tg,uuid:Je(ug),"json-pointer":Je(lg),"json-pointer-uri-fragment":Je(dg),"relative-json-pointer":Je(fg)};function yg(t){return t%4===0&&(t%100!==0||t%400===0)}function Bu(t){const e=t.match(rg);if(!e)return!1;const r=+e[1],n=+e[2],a=+e[3];return n>=1&&n<=12&&a>=1&&a<=(n==2&&yg(r)?29:ng[n])}function zu(t,e){const r=e.match(ag);if(!r)return!1;const n=+r[1],a=+r[2],s=+r[3],i=!!r[5];return(n<=23&&a<=59&&s<=59||n==23&&a==59&&s==60)&&(!t||i)}const _g=/t|\s/i;function vg(t){const e=t.split(_g);return e.length==2&&Bu(e[0])&&zu(!0,e[1])}const wg=/\/|:/,bg=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Eg(t){return wg.test(t)&&bg.test(t)}const Sg=/[^\\]\\Z/;function Tg(t){if(Sg.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}function xg(t){let e=0,r=t.length,n=0,a;for(;n<r;)e++,a=t.charCodeAt(n++),a>=55296&&a<=56319&&n<r&&(a=t.charCodeAt(n),(a&64512)==56320&&n++);return e}function ce(t,e,r="2019-09",n=gt(e),a=!0,s=null,i="#",o="#",c=Object.create(null)){if(e===!0)return{valid:!0,errors:[]};if(e===!1)return{valid:!1,errors:[{instanceLocation:i,keyword:"false",keywordLocation:i,error:"False boolean schema."}]};const u=typeof t;let l;switch(u){case"boolean":case"number":case"string":l=u;break;case"object":t===null?l="null":Array.isArray(t)?l="array":l="object";break;default:throw new Error(`Instances of "${u}" type are not supported.`)}const{$ref:d,$recursiveRef:f,$recursiveAnchor:h,type:p,const:m,enum:g,required:y,not:v,anyOf:_,allOf:S,oneOf:R,if:U,then:z,else:I,format:oe,properties:he,patternProperties:we,additionalProperties:je,unevaluatedProperties:jt,minProperties:A,maxProperties:E,propertyNames:F,dependentRequired:P,dependentSchemas:B,dependencies:L,prefixItems:H,items:X,additionalItems:Y,unevaluatedItems:se,contains:pe,minContains:ne,maxContains:Ve,minItems:xn,maxItems:In,uniqueItems:al,minimum:bt,maximum:Et,exclusiveMinimum:er,exclusiveMaximum:tr,multipleOf:Nr,minLength:Pr,maxLength:Lr,pattern:Ks,__absolute_ref__:Mr,__absolute_recursive_ref__:sl}=e,$=[];if(h===!0&&s===null&&(s=e),f==="#"){const q=s===null?n[sl]:s,j=`${o}/$recursiveRef`,W=ce(t,s===null?e:s,r,n,a,q,i,j,c);W.valid||$.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:j,error:"A subschema had errors."},...W.errors)}if(d!==void 0){const j=n[Mr||d];if(j===void 0){let T=`Unresolved $ref "${d}".`;throw Mr&&Mr!==d&&(T+=` Absolute URI "${Mr}".`),T+=`
|
|
69
|
+
Known schemas:
|
|
70
|
+
- ${Object.keys(n).join(`
|
|
71
|
+
- `)}`,new Error(T)}const W=`${o}/$ref`,C=ce(t,j,r,n,a,s,i,W,c);if(C.valid||$.push({instanceLocation:i,keyword:"$ref",keywordLocation:W,error:"A subschema had errors."},...C.errors),r==="4"||r==="7")return{valid:$.length===0,errors:$}}if(Array.isArray(p)){let q=p.length,j=!1;for(let W=0;W<q;W++)if(l===p[W]||p[W]==="integer"&&l==="number"&&t%1===0&&t===t){j=!0;break}j||$.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${p.join('", "')}".`})}else p==="integer"?(l!=="number"||t%1||t!==t)&&$.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${p}".`}):p!==void 0&&l!==p&&$.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${p}".`});if(m!==void 0&&(l==="object"||l==="array"?qt(t,m)||$.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(m)}.`}):t!==m&&$.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(m)}.`})),g!==void 0&&(l==="object"||l==="array"?g.some(q=>qt(t,q))||$.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(q=>t===q)||$.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),v!==void 0){const q=`${o}/not`;ce(t,v,r,n,a,s,i,q).valid&&$.push({instanceLocation:i,keyword:"not",keywordLocation:q,error:'Instance matched "not" schema.'})}let jr=[];if(_!==void 0){const q=`${o}/anyOf`,j=$.length;let W=!1;for(let C=0;C<_.length;C++){const T=_[C],Z=Object.create(c),G=ce(t,T,r,n,a,h===!0?s:null,i,`${q}/${C}`,Z);$.push(...G.errors),W=W||G.valid,G.valid&&jr.push(Z)}W?$.length=j:$.splice(j,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:q,error:"Instance does not match any subschemas."})}if(S!==void 0){const q=`${o}/allOf`,j=$.length;let W=!0;for(let C=0;C<S.length;C++){const T=S[C],Z=Object.create(c),G=ce(t,T,r,n,a,h===!0?s:null,i,`${q}/${C}`,Z);$.push(...G.errors),W=W&&G.valid,G.valid&&jr.push(Z)}W?$.length=j:$.splice(j,0,{instanceLocation:i,keyword:"allOf",keywordLocation:q,error:"Instance does not match every subschema."})}if(R!==void 0){const q=`${o}/oneOf`,j=$.length,W=R.filter((C,T)=>{const Z=Object.create(c),G=ce(t,C,r,n,a,h===!0?s:null,i,`${q}/${T}`,Z);return $.push(...G.errors),G.valid&&jr.push(Z),G.valid}).length;W===1?$.length=j:$.splice(j,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:q,error:`Instance does not match exactly one subschema (${W} matches).`})}if((l==="object"||l==="array")&&Object.assign(c,...jr),U!==void 0){const q=`${o}/if`;if(ce(t,U,r,n,a,s,i,q,c).valid){if(z!==void 0){const W=ce(t,z,r,n,a,s,i,`${o}/then`,c);W.valid||$.push({instanceLocation:i,keyword:"if",keywordLocation:q,error:'Instance does not match "then" schema.'},...W.errors)}}else if(I!==void 0){const W=ce(t,I,r,n,a,s,i,`${o}/else`,c);W.valid||$.push({instanceLocation:i,keyword:"if",keywordLocation:q,error:'Instance does not match "else" schema.'},...W.errors)}}if(l==="object"){if(y!==void 0)for(const C of y)C in t||$.push({instanceLocation:i,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${C}".`});const q=Object.keys(t);if(A!==void 0&&q.length<A&&$.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${A} properties.`}),E!==void 0&&q.length>E&&$.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${E} properties.`}),F!==void 0){const C=`${o}/propertyNames`;for(const T in t){const Z=`${i}/${Be(T)}`,G=ce(T,F,r,n,a,s,Z,C);G.valid||$.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:C,error:`Property name "${T}" does not match schema.`},...G.errors)}}if(P!==void 0){const C=`${o}/dependantRequired`;for(const T in P)if(T in t){const Z=P[T];for(const G of Z)G in t||$.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:C,error:`Instance has "${T}" but does not have "${G}".`})}}if(B!==void 0)for(const C in B){const T=`${o}/dependentSchemas`;if(C in t){const Z=ce(t,B[C],r,n,a,s,i,`${T}/${Be(C)}`,c);Z.valid||$.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:T,error:`Instance has "${C}" but does not match dependant schema.`},...Z.errors)}}if(L!==void 0){const C=`${o}/dependencies`;for(const T in L)if(T in t){const Z=L[T];if(Array.isArray(Z))for(const G of Z)G in t||$.push({instanceLocation:i,keyword:"dependencies",keywordLocation:C,error:`Instance has "${T}" but does not have "${G}".`});else{const G=ce(t,Z,r,n,a,s,i,`${C}/${Be(T)}`);G.valid||$.push({instanceLocation:i,keyword:"dependencies",keywordLocation:C,error:`Instance has "${T}" but does not match dependant schema.`},...G.errors)}}}const j=Object.create(null);let W=!1;if(he!==void 0){const C=`${o}/properties`;for(const T in he){if(!(T in t))continue;const Z=`${i}/${Be(T)}`,G=ce(t[T],he[T],r,n,a,s,Z,`${C}/${Be(T)}`);if(G.valid)c[T]=j[T]=!0;else if(W=a,$.push({instanceLocation:i,keyword:"properties",keywordLocation:C,error:`Property "${T}" does not match schema.`},...G.errors),W)break}}if(!W&&we!==void 0){const C=`${o}/patternProperties`;for(const T in we){const Z=new RegExp(T,"u"),G=we[T];for(const Ie in t){if(!Z.test(Ie))continue;const Ys=`${i}/${Be(Ie)}`,Qs=ce(t[Ie],G,r,n,a,s,Ys,`${C}/${Be(T)}`);Qs.valid?c[Ie]=j[Ie]=!0:(W=a,$.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:C,error:`Property "${Ie}" matches pattern "${T}" but does not match associated schema.`},...Qs.errors))}}}if(!W&&je!==void 0){const C=`${o}/additionalProperties`;for(const T in t){if(j[T])continue;const Z=`${i}/${Be(T)}`,G=ce(t[T],je,r,n,a,s,Z,C);G.valid?c[T]=!0:(W=a,$.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:C,error:`Property "${T}" does not match additional properties schema.`},...G.errors))}}else if(!W&&jt!==void 0){const C=`${o}/unevaluatedProperties`;for(const T in t)if(!c[T]){const Z=`${i}/${Be(T)}`,G=ce(t[T],jt,r,n,a,s,Z,C);G.valid?c[T]=!0:$.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:C,error:`Property "${T}" does not match unevaluated properties schema.`},...G.errors)}}}else if(l==="array"){In!==void 0&&t.length>In&&$.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${t.length} > ${In}).`}),xn!==void 0&&t.length<xn&&$.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${t.length} < ${xn}).`});const q=t.length;let j=0,W=!1;if(H!==void 0){const C=`${o}/prefixItems`,T=Math.min(H.length,q);for(;j<T;j++){const Z=ce(t[j],H[j],r,n,a,s,`${i}/${j}`,`${C}/${j}`);if(c[j]=!0,!Z.valid&&(W=a,$.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:C,error:"Items did not match schema."},...Z.errors),W))break}}if(X!==void 0){const C=`${o}/items`;if(Array.isArray(X)){const T=Math.min(X.length,q);for(;j<T;j++){const Z=ce(t[j],X[j],r,n,a,s,`${i}/${j}`,`${C}/${j}`);if(c[j]=!0,!Z.valid&&(W=a,$.push({instanceLocation:i,keyword:"items",keywordLocation:C,error:"Items did not match schema."},...Z.errors),W))break}}else for(;j<q;j++){const T=ce(t[j],X,r,n,a,s,`${i}/${j}`,C);if(c[j]=!0,!T.valid&&(W=a,$.push({instanceLocation:i,keyword:"items",keywordLocation:C,error:"Items did not match schema."},...T.errors),W))break}if(!W&&Y!==void 0){const T=`${o}/additionalItems`;for(;j<q;j++){const Z=ce(t[j],Y,r,n,a,s,`${i}/${j}`,T);c[j]=!0,Z.valid||(W=a,$.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:T,error:"Items did not match additional items schema."},...Z.errors))}}}if(pe!==void 0)if(q===0&&ne===void 0)$.push({instanceLocation:i,keyword:"contains",keywordLocation:`${o}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(ne!==void 0&&q<ne)$.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array has less items (${q}) than minContains (${ne}).`});else{const C=`${o}/contains`,T=$.length;let Z=0;for(let G=0;G<q;G++){const Ie=ce(t[G],pe,r,n,a,s,`${i}/${G}`,C);Ie.valid?(c[G]=!0,Z++):$.push(...Ie.errors)}Z>=(ne||0)&&($.length=T),ne===void 0&&Ve===void 0&&Z===0?$.splice(T,0,{instanceLocation:i,keyword:"contains",keywordLocation:C,error:"Array does not contain item matching schema."}):ne!==void 0&&Z<ne?$.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array must contain at least ${ne} items matching schema. Only ${Z} items were found.`}):Ve!==void 0&&Z>Ve&&$.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${Ve} items matching schema. ${Z} items were found.`})}if(!W&&se!==void 0){const C=`${o}/unevaluatedItems`;for(j;j<q;j++){if(c[j])continue;const T=ce(t[j],se,r,n,a,s,`${i}/${j}`,C);c[j]=!0,T.valid||$.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:C,error:"Items did not match unevaluated items schema."},...T.errors)}}if(al)for(let C=0;C<q;C++){const T=t[C],Z=typeof T=="object"&&T!==null;for(let G=0;G<q;G++){if(C===G)continue;const Ie=t[G];(T===Ie||Z&&(typeof Ie=="object"&&Ie!==null)&&qt(T,Ie))&&($.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${o}/uniqueItems`,error:`Duplicate items at indexes ${C} and ${G}.`}),C=Number.MAX_SAFE_INTEGER,G=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(r==="4"?(bt!==void 0&&(er===!0&&t<=bt||t<bt)&&$.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${t} is less than ${er?"or equal to ":""} ${bt}.`}),Et!==void 0&&(tr===!0&&t>=Et||t>Et)&&$.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${t} is greater than ${tr?"or equal to ":""} ${Et}.`})):(bt!==void 0&&t<bt&&$.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${t} is less than ${bt}.`}),Et!==void 0&&t>Et&&$.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${t} is greater than ${Et}.`}),er!==void 0&&t<=er&&$.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${t} is less than ${er}.`}),tr!==void 0&&t>=tr&&$.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${t} is greater than or equal to ${tr}.`})),Nr!==void 0){const q=t%Nr;Math.abs(0-q)>=11920929e-14&&Math.abs(Nr-q)>=11920929e-14&&$.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${t} is not a multiple of ${Nr}.`})}}else if(l==="string"){const q=Pr===void 0&&Lr===void 0?0:xg(t);Pr!==void 0&&q<Pr&&$.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${q} < ${Pr}).`}),Lr!==void 0&&q>Lr&&$.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${q} > ${Lr}).`}),Ks!==void 0&&!new RegExp(Ks,"u").test(t)&&$.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),oe!==void 0&&Xo[oe]&&!Xo[oe](t)&&$.push({instanceLocation:i,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${oe}".`})}return{valid:$.length===0,errors:$}}class Ig{schema;draft;shortCircuit;lookup;constructor(e,r="2019-09",n=!0){this.schema=e,this.draft=r,this.shortCircuit=n,this.lookup=gt(e)}validate(e){return ce(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,r){r&&(e={...e,$id:r}),gt(e,this.lookup)}}var Ag={};ge(Ag,{Validator:()=>Ig,deepCompareStrict:()=>qt,toJsonSchema:()=>qu,validatesOnlyStrings:()=>Qr});function qu(t,e){if(le(t)){const r=om(t,!0);if(it(r)){const n=os(r,!0);return Xs(n,e)}else return Xs(t,e)}return ye(t)?Km(t):t}function Qr(t){if(!t||typeof t!="object"||Object.keys(t).length===0||Array.isArray(t))return!1;if("type"in t)return typeof t.type=="string"?t.type==="string":Array.isArray(t.type)?t.type.every(e=>e==="string"):!1;if("enum"in t)return Array.isArray(t.enum)&&t.enum.length>0&&t.enum.every(e=>typeof e=="string");if("const"in t)return typeof t.const=="string";if("allOf"in t&&Array.isArray(t.allOf))return t.allOf.some(e=>Qr(e));if("anyOf"in t&&Array.isArray(t.anyOf)||"oneOf"in t&&Array.isArray(t.oneOf)){const e="anyOf"in t?t.anyOf:t.oneOf;return e.length>0&&e.every(r=>Qr(r))}if("not"in t)return!1;if("$ref"in t&&typeof t.$ref=="string"){const e=t.$ref,r=gt(t);return r[e]?Qr(r[e]):!1}return!1}var $g={};ge($g,{Graph:()=>Vs});function Rg(t,e){if(t!==void 0&&!lr(t))return t;if(Hs(e))try{let r=e.getName();return r=r.startsWith("Runnable")?r.slice(8):r,r}catch{return e.getName()}else return e.name??"UnknownSchema"}function Og(t){return Hs(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...qu(t.data.schema),title:t.data.name}}}var Vs=class Gu{nodes={};edges=[];constructor(e){this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach((r,n)=>{e[r.id]=lr(r.id)?n:r.id}),{nodes:Object.values(this.nodes).map(r=>({id:e[r.id],...Og(r)})),edges:this.edges.map(r=>{const n={source:e[r.source],target:e[r.target]};return typeof r.data<"u"&&(n.data=r.data),typeof r.conditional<"u"&&(n.conditional=r.conditional),n})}}addNode(e,r,n){if(r!==void 0&&this.nodes[r]!==void 0)throw new Error(`Node with id ${r} already exists`);const a=r??Tt(),s={id:a,data:e,name:Rg(r,e),metadata:n};return this.nodes[a]=s,s}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(r=>r.source!==e.id&&r.target!==e.id)}addEdge(e,r,n,a){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[r.id]===void 0)throw new Error(`Target node ${r.id} not in graph`);const s={source:e.id,target:r.id,data:n,conditional:a};return this.edges.push(s),s}firstNode(){return ec(this)}lastNode(){return tc(this)}extend(e,r=""){let n=r;Object.values(e.nodes).map(u=>u.id).every(lr)&&(n="");const s=u=>n?`${n}:${u}`:u;Object.entries(e.nodes).forEach(([u,l])=>{this.nodes[s(u)]={...l,id:s(u)}});const i=e.edges.map(u=>({...u,source:s(u.source),target:s(u.target)}));this.edges=[...this.edges,...i];const o=e.firstNode(),c=e.lastNode();return[o?{id:s(o.id),data:o.data}:void 0,c?{id:s(c.id),data:c.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&ec(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&tc(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map(a=>[a.id,a.name])),r=new Map;Object.values(e).forEach(a=>{r.set(a,(r.get(a)||0)+1)});const n=a=>{const s=e[a];return lr(a)&&r.get(s)===1?s:a};return new Gu({nodes:Object.fromEntries(Object.entries(this.nodes).map(([a,s])=>[n(a),{...s,id:n(a)}])),edges:this.edges.map(a=>({...a,source:n(a.source),target:n(a.target)}))})}drawMermaid(e){const{withStyles:r,curveStyle:n,nodeColors:a={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:s}=e??{},i=this.reid(),o=i.firstNode(),c=i.lastNode();return lm(i.nodes,i.edges,{firstNode:o?.id,lastNode:c?.id,withStyles:r,curveStyle:n,nodeColors:a,wrapLabelNWords:s})}async drawMermaidPng(e){const r=this.drawMermaid(e);return dm(r,{backgroundColor:e?.backgroundColor})}};function ec(t,e=[]){const r=new Set(t.edges.filter(a=>!e.includes(a.source)).map(a=>a.target)),n=[];for(const a of Object.values(t.nodes))!e.includes(a.id)&&!r.has(a.id)&&n.push(a);return n.length===1?n[0]:void 0}function tc(t,e=[]){const r=new Set(t.edges.filter(a=>!e.includes(a.target)).map(a=>a.source)),n=[];for(const a of Object.values(t.nodes))!e.includes(a.id)&&!r.has(a.id)&&n.push(a);return n.length===1?n[0]:void 0}function kg(t){const e=new TextEncoder,r=new ReadableStream({async start(n){for await(const a of t)n.enqueue(e.encode(`event: data
|
|
72
|
+
data: ${JSON.stringify(a)}
|
|
73
|
+
|
|
74
|
+
`));n.enqueue(e.encode(`event: end
|
|
75
|
+
|
|
76
|
+
`)),n.close()}});return Ge.fromReadableStream(r)}function rc(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}const Cg=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function";function cs(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*nc(t,e){for(;;){const{value:r,done:n}=lt.runWithConfig(Jt(t),e.next.bind(e),!0);if(n)break;yield r}}async function*us(t,e){const r=e[Symbol.asyncIterator]();for(;;){const{value:n,done:a}=await lt.runWithConfig(Jt(t),r.next.bind(e),!0);if(a)break;yield n}}function me(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}var Oe=class extends gr{lc_runnable=!0;name;getName(t){const e=this.name??this.constructor.lc_name()??this.constructor.name;return t?`${e}${t}`:e}withRetry(t){return new Vu({bound:this,kwargs:{},config:{},maxAttemptNumber:t?.stopAfterAttempt,...t})}withConfig(t){return new pn({bound:this,config:t,kwargs:{}})}withFallbacks(t){const e=Array.isArray(t)?t:t.fallbacks;return new Lg({runnable:this,fallbacks:e})}_getOptionsList(t,e=0){if(Array.isArray(t)&&t.length!==e)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${t.length} options for ${e} inputs`);if(Array.isArray(t))return t.map(ie);if(e>1&&!Array.isArray(t)&&t.runId){console.warn("Provided runId will be used only for the first element of the batch.");const r=Object.fromEntries(Object.entries(t).filter(([n])=>n!=="runId"));return Array.from({length:e},(n,a)=>ie(a===0?t:r))}return Array.from({length:e},()=>ie(t))}async batch(t,e,r){const n=this._getOptionsList(e??{},t.length),a=n[0]?.maxConcurrency??r?.maxConcurrency,s=new ku({maxConcurrency:a,onFailedAttempt:o=>{throw o}}),i=t.map((o,c)=>s.call(async()=>{try{return await this.invoke(o,n[c])}catch(u){if(r?.returnExceptions)return u;throw u}}));return Promise.all(i)}async*_streamIterator(t,e){yield this.invoke(t,e)}async stream(t,e){const r=ie(e),n=new Mt({generator:this._streamIterator(t,r),config:r});return await n.setup,Ge.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(t){let e;t===void 0?e=ie(t):e=ie({callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,runName:t.runName,configurable:t.configurable,recursionLimit:t.recursionLimit,maxConcurrency:t.maxConcurrency,runId:t.runId,timeout:t.timeout,signal:t.signal});const r={...t};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[e,r]}async _callWithConfig(t,e,r){const n=ie(r),s=await(await qe(n))?.handleChainStart(this.toJSON(),me(e,"input"),n.runId,n?.runType,void 0,void 0,n?.runName??this.getName());delete n.runId;let i;try{const o=t.call(this,e,n,s);i=await wt(o,r?.signal)}catch(o){throw await s?.handleChainError(o),o}return await s?.handleChainEnd(me(i,"output")),i}async _batchWithConfig(t,e,r,n){const a=this._getOptionsList(r??{},e.length),s=await Promise.all(a.map(qe)),i=await Promise.all(s.map(async(c,u)=>{const l=await c?.handleChainStart(this.toJSON(),me(e[u],"input"),a[u].runId,a[u].runType,void 0,void 0,a[u].runName??this.getName());return delete a[u].runId,l}));let o;try{const c=t.call(this,e,a,i,n);o=await wt(c,a?.[0]?.signal)}catch(c){throw await Promise.all(i.map(u=>u?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(me(o,"output")))),o}_concatOutputChunks(t,e){return qs(t,e)}async*_transformStreamWithConfig(t,e,r){let n,a=!0,s,i=!0;const o=ie(r),c=await qe(o),u=this;async function*l(){for await(const f of t){if(a)if(n===void 0)n=f;else try{n=u._concatOutputChunks(n,f)}catch{n=void 0,a=!1}yield f}}let d;try{const f=await xu(e.bind(this),l(),async()=>c?.handleChainStart(this.toJSON(),{input:""},o.runId,o.runType,void 0,void 0,o.runName??this.getName()),r?.signal,o);delete o.runId,d=f.setup;const h=d?.handlers.find(jp);let p=f.output;h!==void 0&&d!==void 0&&(p=h.tapOutputIterable(d.runId,p));const m=d?.handlers.find($u);m!==void 0&&d!==void 0&&(p=m.tapOutputIterable(d.runId,p));for await(const g of p)if(yield g,i)if(s===void 0)s=g;else try{s=this._concatOutputChunks(s,g)}catch{s=void 0,i=!1}}catch(f){throw await d?.handleChainError(f,void 0,void 0,void 0,{inputs:me(n,"input")}),f}await d?.handleChainEnd(s??{},void 0,void 0,void 0,{inputs:me(n,"input")})}getGraph(t){const e=new Vs,r=e.addNode({name:`${this.getName()}Input`,schema:fi()}),n=e.addNode(this),a=e.addNode({name:`${this.getName()}Output`,schema:fi()});return e.addEdge(r,n),e.addEdge(n,a),e}pipe(t){return new Wu({first:this,last:xt(t)})}pick(t){return this.pipe(new jg(t))}assign(t){return this.pipe(new Mg(new Tn({steps:t})))}async*transform(t,e){let r;for await(const n of t)r===void 0?r=n:r=this._concatOutputChunks(r,n);yield*this._streamIterator(r,ie(e))}async*streamLog(t,e,r){const n=new ss({...r,autoClose:!1,_schemaFormat:"original"}),a=ie(e);yield*this._streamLog(t,n,a)}async*_streamLog(t,e,r){const{callbacks:n}=r;if(n===void 0)r.callbacks=[e];else if(Array.isArray(n))r.callbacks=n.concat([e]);else{const o=n.copy();o.addHandler(e,!0),r.callbacks=o}const a=this.stream(t,r);async function s(){try{const o=await a;for await(const c of o){const u=new rt({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await e.writer.write(u)}}finally{await e.writer.close()}}const i=s();try{for await(const o of e)yield o}finally{await i}}streamEvents(t,e,r){let n;if(e.version==="v1")n=this._streamEventsV1(t,e,r);else if(e.version==="v2")n=this._streamEventsV2(t,e,r);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return e.encoding==="text/event-stream"?kg(n):Ge.fromAsyncGenerator(n)}async*_streamEventsV2(t,e,r){const n=new Dp({...r,autoClose:!1}),a=ie(e),s=a.runId??Tt();a.runId=s;const i=a.callbacks;if(i===void 0)a.callbacks=[n];else if(Array.isArray(i))a.callbacks=i.concat(n);else{const h=i.copy();h.addHandler(n,!0),a.callbacks=h}const o=new AbortController,c=this;async function u(){let h,p=null;try{e?.signal?"any"in AbortSignal?h=AbortSignal.any([o.signal,e.signal]):(h=e.signal,p=()=>{o.abort()},e.signal.addEventListener("abort",p,{once:!0})):h=o.signal;const m=await c.stream(t,{...a,signal:h}),g=n.tapOutputIterable(s,m);for await(const y of g)if(o.signal.aborted)break}finally{await n.finish(),h&&p&&h.removeEventListener("abort",p)}}const l=u();let d=!1,f;try{for await(const h of n){if(!d){h.data.input=t,d=!0,f=h.run_id,yield h;continue}h.run_id===f&&h.event.endsWith("_end")&&h.data?.input&&delete h.data.input,yield h}}finally{o.abort(),await l}}async*_streamEventsV1(t,e,r){let n,a=!1;const s=ie(e),i=s.tags??[],o=s.metadata??{},c=s.runName??this.getName(),u=new ss({...r,autoClose:!1,_schemaFormat:"streaming_events"}),l=new Kp({...r}),d=this._streamLog(t,u,s);for await(const h of d){if(n?n=n.concat(h):n=Gs.fromRunLogPatch(h),n.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!a){a=!0;const y={...n.state},v={run_id:y.id,event:`on_${y.type}_start`,name:c,tags:i,metadata:o,data:{input:t}};l.includeEvent(v,y.type)&&(yield v)}const p=h.ops.filter(y=>y.path.startsWith("/logs/")).map(y=>y.path.split("/")[2]),m=[...new Set(p)];for(const y of m){let v,_={};const S=n.state.logs[y];if(S.end_time===void 0?S.streamed_output.length>0?v="stream":v="start":v="end",v==="start")S.inputs!==void 0&&(_.input=S.inputs);else if(v==="end")S.inputs!==void 0&&(_.input=S.inputs),_.output=S.final_output;else if(v==="stream"){const R=S.streamed_output.length;if(R!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${R} instead. Encountered in: "${S.name}"`);_={chunk:S.streamed_output[0]},S.streamed_output=[]}yield{event:`on_${S.type}_${v}`,name:S.name,run_id:S.id,tags:S.tags,metadata:S.metadata,data:_}}const{state:g}=n;if(g.streamed_output.length>0){const y=g.streamed_output.length;if(y!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${y} instead. Encountered in: "${g.name}"`);const v={chunk:g.streamed_output[0]};g.streamed_output=[];const _={event:`on_${g.type}_stream`,run_id:g.id,tags:i,metadata:o,name:c,data:v};l.includeEvent(_,g.type)&&(yield _)}}const f=n?.state;if(f!==void 0){const h={event:`on_${f.type}_end`,name:c,run_id:f.id,tags:i,metadata:o,data:{output:f.final_output}};l.includeEvent(h,f.type)&&(yield h)}}static isRunnable(t){return Hs(t)}withListeners({onStart:t,onEnd:e,onError:r}){return new pn({bound:this,config:{},configFactories:[n=>({callbacks:[new Cu({config:n,onStart:t,onEnd:e,onError:r})]})]})}asTool(t){return Dg(this,t)}},pn=class Hu extends Oe{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(e){super(e),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){const r=Go(this.config,...e);return Go(r,...this.configFactories?await Promise.all(this.configFactories.map(async n=>await n(r))):[])}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new Vu({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,r){return this.bound.invoke(e,await this._mergeConfig(r,this.kwargs))}async batch(e,r,n){const a=Array.isArray(r)?await Promise.all(r.map(async s=>this._mergeConfig(ie(s),this.kwargs))):await this._mergeConfig(ie(r),this.kwargs);return this.bound.batch(e,a,n)}_concatOutputChunks(e,r){return this.bound._concatOutputChunks(e,r)}async*_streamIterator(e,r){yield*this.bound._streamIterator(e,await this._mergeConfig(ie(r),this.kwargs))}async stream(e,r){return this.bound.stream(e,await this._mergeConfig(ie(r),this.kwargs))}async*transform(e,r){yield*this.bound.transform(e,await this._mergeConfig(ie(r),this.kwargs))}streamEvents(e,r,n){const a=this,s=async function*(){yield*a.bound.streamEvents(e,{...await a._mergeConfig(ie(r),a.kwargs),version:r.version},n)};return Ge.fromAsyncGenerator(s())}static isRunnableBinding(e){return e.bound&&Oe.isRunnable(e.bound)}withListeners({onStart:e,onEnd:r,onError:n}){return new Hu({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[a=>({callbacks:[new Cu({config:a,onStart:e,onEnd:r,onError:n})]})]})}},by=class Zu extends Oe{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(e){super(e),this.bound=e.bound}async invoke(e,r){return this._callWithConfig(this._invoke.bind(this),e,r)}async _invoke(e,r,n){return this.bound.batch(e,be(r,{callbacks:n?.getChild()}))}withListeners({onStart:e,onEnd:r,onError:n}){return new Zu({bound:this.bound.withListeners({onStart:e,onEnd:r,onError:n})})}},Vu=class extends pn{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(t){super(t),this.maxAttemptNumber=t.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=t.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(t,e,r){const n=t>1?`retry:attempt:${t}`:void 0;return be(e,{callbacks:r?.getChild(n)})}async _invoke(t,e,r){return is(n=>super.invoke(t,this._patchConfigForRetry(n,e,r)),{onFailedAttempt:({error:n})=>this.onFailedAttempt(n,t),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(t,e){return this._callWithConfig(this._invoke.bind(this),t,e)}async _batch(t,e,r,n){const a={};try{await is(async s=>{const i=t.map((d,f)=>f).filter(d=>a[d.toString()]===void 0||a[d.toString()]instanceof Error),o=i.map(d=>t[d]),c=i.map(d=>this._patchConfigForRetry(s,e?.[d],r?.[d])),u=await super.batch(o,c,{...n,returnExceptions:!0});let l;for(let d=0;d<u.length;d+=1){const f=u[d],h=i[d];f instanceof Error&&l===void 0&&(l=f,l.input=o[d]),a[h.toString()]=f}if(l)throw l;return u},{onFailedAttempt:({error:s})=>this.onFailedAttempt(s,s.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(s){if(n?.returnExceptions!==!0)throw s}return Object.keys(a).sort((s,i)=>parseInt(s,10)-parseInt(i,10)).map(s=>a[parseInt(s,10)])}async batch(t,e,r){return this._batchWithConfig(this._batch.bind(this),t,e,r)}},Wu=class or extends Oe{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(e){super(e),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,r){const n=ie(r),s=await(await qe(n))?.handleChainStart(this.toJSON(),me(e,"input"),n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let i=e,o;try{const c=[this.first,...this.middle];for(let u=0;u<c.length;u+=1){const d=c[u].invoke(i,be(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${u+1}`)}));i=await wt(d,r?.signal)}if(r?.signal?.aborted)throw un(r.signal);o=await this.last.invoke(i,be(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(c){throw await s?.handleChainError(c),c}return await s?.handleChainEnd(me(o,"output")),o}async batch(e,r,n){const a=this._getOptionsList(r??{},e.length),s=await Promise.all(a.map(qe)),i=await Promise.all(s.map(async(c,u)=>{const l=await c?.handleChainStart(this.toJSON(),me(e[u],"input"),a[u].runId,void 0,void 0,void 0,a[u].runName);return delete a[u].runId,l}));let o=e;try{for(let c=0;c<this.steps.length;c+=1){const l=this.steps[c].batch(o,i.map((d,f)=>{const h=d?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return be(a[f],{callbacks:h})}),n);o=await wt(l,a[0]?.signal)}}catch(c){throw await Promise.all(i.map(u=>u?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(me(o,"output")))),o}_concatOutputChunks(e,r){return this.last._concatOutputChunks(e,r)}async*_streamIterator(e,r){const n=await qe(r),{runId:a,...s}=r??{},i=await n?.handleChainStart(this.toJSON(),me(e,"input"),a,void 0,void 0,void 0,s?.runName),o=[this.first,...this.middle,this.last];let c=!0,u;async function*l(){yield e}try{let d=o[0].transform(l(),be(s,{callbacks:i?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let f=1;f<o.length;f+=1)d=await o[f].transform(d,be(s,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${f+1}`)}));for await(const f of d)if(r?.signal?.throwIfAborted(),yield f,c)if(u===void 0)u=f;else try{u=this._concatOutputChunks(u,f)}catch{u=void 0,c=!1}}catch(d){throw await i?.handleChainError(d),d}await i?.handleChainEnd(me(u,"output"))}getGraph(e){const r=new Vs;let n=null;return this.steps.forEach((a,s)=>{const i=a.getGraph(e);s!==0&&i.trimFirstNode(),s!==this.steps.length-1&&i.trimLastNode(),r.extend(i);const o=i.firstNode();if(!o)throw new Error(`Runnable ${a} has no first node`);n&&r.addEdge(n,o),n=i.lastNode()}),r}pipe(e){return or.isRunnableSequence(e)?new or({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new or({first:this.first,middle:[...this.middle,this.last],last:xt(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&Oe.isRunnable(e)}static from([e,...r],n){let a={};return typeof n=="string"?a.name=n:n!==void 0&&(a=n),new or({...a,first:xt(e),middle:r.slice(0,-1).map(xt),last:xt(r[r.length-1])})}},Tn=class Ju extends Oe{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),this.steps={};for(const[r,n]of Object.entries(e.steps))this.steps[r]=xt(n)}static from(e){return new Ju({steps:e})}async invoke(e,r){const n=ie(r),s=await(await qe(n))?.handleChainStart(this.toJSON(),{input:e},n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;const i={};try{const o=Object.entries(this.steps).map(async([c,u])=>{i[c]=await u.invoke(e,be(n,{callbacks:s?.getChild(`map:key:${c}`)}))});await wt(Promise.all(o),r?.signal)}catch(o){throw await s?.handleChainError(o),o}return await s?.handleChainEnd(i),i}async*_transform(e,r,n){const a={...this.steps},s=zs(e,Object.keys(a).length),i=new Map(Object.entries(a).map(([o,c],u)=>{const l=c.transform(s[u],be(n,{callbacks:r?.getChild(`map:key:${o}`)}));return[o,l.next().then(d=>({key:o,gen:l,result:d}))]}));for(;i.size;){const o=Promise.race(i.values()),{key:c,result:u,gen:l}=await wt(o,n?.signal);i.delete(c),u.done||(yield{[c]:u.value},i.set(c,l.next().then(d=>({key:c,gen:l,result:d}))))}}transform(e,r){return this._transformStreamWithConfig(e,this._transform.bind(this),r)}async stream(e,r){async function*n(){yield e}const a=ie(r),s=new Mt({generator:this.transform(n(),a),config:a});return await s.setup,Ge.fromAsyncGenerator(s)}},Ng=class Ku extends Oe{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(e){if(super(e),!Bs(e.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,r){const[n]=this._getOptionsList(r??{},1),a=await qe(n),s=this.func(be(n,{callbacks:a}),e);return wt(s,n?.signal)}async*_streamIterator(e,r){const[n]=this._getOptionsList(r??{},1),a=await this.invoke(e,r);if(cs(a)){for await(const s of a)n?.signal?.throwIfAborted(),yield s;return}if(Cg(a)){for(;;){n?.signal?.throwIfAborted();const s=a.next();if(s.done)break;yield s.value}return}yield a}static from(e){return new Ku({func:e})}};function Pg(t){if(Bs(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var Cr=class Yu extends Oe{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(e){if(Bs(e.func))return Ng.from(e.func);super(e),Pg(e.func),this.func=e.func}static from(e){return new Yu({func:e})}async _invoke(e,r,n){return new Promise((a,s)=>{const i=be(r,{callbacks:n?.getChild(),recursionLimit:(r?.recursionLimit??La)-1});lt.runWithConfig(Jt(i),async()=>{try{let o=await this.func(e,{...i});if(o&&Oe.isRunnable(o)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(e,{...i,recursionLimit:(i.recursionLimit??La)-1})}else if(cs(o)){let c;for await(const u of us(i,o))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}o=c}else if(rc(o)){let c;for(const u of nc(i,o))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}o=c}a(o)}catch(o){s(o)}})})}async invoke(e,r){return this._callWithConfig(this._invoke.bind(this),e,r)}async*_transform(e,r,n){let a;for await(const o of e)if(a===void 0)a=o;else try{a=this._concatOutputChunks(a,o)}catch{a=o}const s=be(n,{callbacks:r?.getChild(),recursionLimit:(n?.recursionLimit??La)-1}),i=await new Promise((o,c)=>{lt.runWithConfig(Jt(s),async()=>{try{const u=await this.func(a,{...s,config:s});o(u)}catch(u){c(u)}})});if(i&&Oe.isRunnable(i)){if(n?.recursionLimit===0)throw new Error("Recursion limit reached.");const o=await i.stream(a,s);for await(const c of o)yield c}else if(cs(i))for await(const o of us(s,i))n?.signal?.throwIfAborted(),yield o;else if(rc(i))for(const o of nc(s,i))n?.signal?.throwIfAborted(),yield o;else yield i}transform(e,r){return this._transformStreamWithConfig(e,this._transform.bind(this),r)}async stream(e,r){async function*n(){yield e}const a=ie(r),s=new Mt({generator:this.transform(n(),a),config:a});return await s.setup,Ge.fromAsyncGenerator(s)}},Ey=class extends Tn{},Lg=class extends Oe{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(t){super(t),this.runnable=t.runnable,this.fallbacks=t.fallbacks}*runnables(){yield this.runnable;for(const t of this.fallbacks)yield t}async invoke(t,e){const r=ie(e),n=await qe(r),{runId:a,...s}=r,i=await n?.handleChainStart(this.toJSON(),me(t,"input"),a,void 0,void 0,void 0,s?.runName),o=be(s,{callbacks:i?.getChild()});return await lt.runWithConfig(o,async()=>{let u;for(const l of this.runnables()){r?.signal?.throwIfAborted();try{const d=await l.invoke(t,o);return await i?.handleChainEnd(me(d,"output")),d}catch(d){u===void 0&&(u=d)}}throw u===void 0?new Error("No error stored at end of fallback."):(await i?.handleChainError(u),u)})}async*_streamIterator(t,e){const r=ie(e),n=await qe(r),{runId:a,...s}=r,i=await n?.handleChainStart(this.toJSON(),me(t,"input"),a,void 0,void 0,void 0,s?.runName);let o,c;for(const l of this.runnables()){r?.signal?.throwIfAborted();const d=be(s,{callbacks:i?.getChild()});try{const f=await l.stream(t,d);c=us(d,f);break}catch(f){o===void 0&&(o=f)}}if(c===void 0){const l=o??new Error("No error stored at end of fallback.");throw await i?.handleChainError(l),l}let u;try{for await(const l of c){yield l;try{u=u===void 0?u:this._concatOutputChunks(u,l)}catch{u=void 0}}}catch(l){throw await i?.handleChainError(l),l}await i?.handleChainEnd(me(u,"output"))}async batch(t,e,r){if(r?.returnExceptions)throw new Error("Not implemented.");const n=this._getOptionsList(e??{},t.length),a=await Promise.all(n.map(o=>qe(o))),s=await Promise.all(a.map(async(o,c)=>{const u=await o?.handleChainStart(this.toJSON(),me(t[c],"input"),n[c].runId,void 0,void 0,void 0,n[c].runName);return delete n[c].runId,u}));let i;for(const o of this.runnables()){n[0].signal?.throwIfAborted();try{const c=await o.batch(t,s.map((u,l)=>be(n[l],{callbacks:u?.getChild()})),r);return await Promise.all(s.map((u,l)=>u?.handleChainEnd(me(c[l],"output")))),c}catch(c){i===void 0&&(i=c)}}throw i?(await Promise.all(s.map(o=>o?.handleChainError(i))),i):new Error("No error stored at end of fallbacks.")}};function xt(t){if(typeof t=="function")return new Cr({func:t});if(Oe.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){const e={};for(const[r,n]of Object.entries(t))e[r]=xt(n);return new Tn({steps:e})}else throw new Error(`Expected a Runnable, function or object.
|
|
77
|
+
Instead got an unsupported type.`)}var Mg=class extends Oe{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(t){t instanceof Tn&&(t={mapper:t}),super(t),this.mapper=t.mapper}async invoke(t,e){const r=await this.mapper.invoke(t,e);return{...t,...r}}async*_transform(t,e,r){const n=this.mapper.getStepsKeys(),[a,s]=zs(t),i=this.mapper.transform(s,be(r,{callbacks:e?.getChild()})),o=i.next();for await(const c of a){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);const u=Object.fromEntries(Object.entries(c).filter(([l])=>!n.includes(l)));Object.keys(u).length>0&&(yield u)}yield(await o).value;for await(const c of i)yield c}transform(t,e){return this._transformStreamWithConfig(t,this._transform.bind(this),e)}async stream(t,e){async function*r(){yield t}const n=ie(e),a=new Mt({generator:this.transform(r(),n),config:n});return await a.setup,Ge.fromAsyncGenerator(a)}},jg=class extends Oe{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(t){(typeof t=="string"||Array.isArray(t))&&(t={keys:t}),super(t),this.keys=t.keys}async _pick(t){if(typeof this.keys=="string")return t[this.keys];{const e=this.keys.map(r=>[r,t[r]]).filter(r=>r[1]!==void 0);return e.length===0?void 0:Object.fromEntries(e)}}async invoke(t,e){return this._callWithConfig(this._pick.bind(this),t,e)}async*_transform(t){for await(const e of t){const r=await this._pick(e);r!==void 0&&(yield r)}}transform(t,e){return this._transformStreamWithConfig(t,this._transform.bind(this),e)}async stream(t,e){async function*r(){yield t}const n=ie(e),a=new Mt({generator:this.transform(r(),n),config:n});return await a.setup,Ge.fromAsyncGenerator(a)}},ac=class extends pn{name;description;schema;constructor(t){const e=Wu.from([Cr.from(async r=>{let n;if(Nc(r))try{n=await em(this.schema,r.args)}catch{throw new gd("Received tool input did not match expected schema",JSON.stringify(r.args))}else n=r;return n}).withConfig({runName:`${t.name}:parse_input`}),t.bound]).withConfig({runName:t.name});super({bound:e,config:t.config??{}}),this.name=t.name,this.description=t.description,this.schema=t.schema}static lc_name(){return"RunnableToolLike"}};function Dg(t,e){const r=e.name??t.getName(),n=e.description??tm(e.schema);return rm(e.schema)?new ac({name:r,description:n,schema:Dl({input:jl()}).transform(a=>a.input),bound:t}):new ac({name:r,description:n,schema:e.schema,bound:t})}const mn=(t,e)=>{const r=[...new Set(e?.map(a=>{if(typeof a=="string")return a;const s=new a({});if(!("getType"in s)||typeof s.getType!="function")throw new Error("Invalid type provided.");return s.getType()}))],n=t.getType();return r.some(a=>a===n)};function Qu(t,e){return Array.isArray(t)?sc(t,e):Cr.from(r=>sc(r,t))}function sc(t,e={}){const{includeNames:r,excludeNames:n,includeTypes:a,excludeTypes:s,includeIds:i,excludeIds:o}=e,c=[];for(const u of t)if(!(n&&u.name&&n.includes(u.name))){{if(s&&mn(u,s))continue;if(o&&u.id&&o.includes(u.id))continue}a||i||r?(r&&u.name&&r.some(l=>l===u.name)||a&&mn(u,a)||i&&u.id&&i.some(l=>l===u.id))&&c.push(u):c.push(u)}return c}function Xu(t){return Array.isArray(t)?ic(t):Cr.from(ic)}function ic(t){if(!t.length)return[];const e=[];for(const r of t){const n=r,a=e.pop();if(!a)e.push(n);else if(n.getType()==="tool"||n.getType()!==a.getType())e.push(a,n);else{const s=sn(a),i=sn(n),o=s.concat(i);typeof s.content=="string"&&typeof i.content=="string"&&(o.content=`${s.content}
|
|
78
|
+
${i.content}`),e.push(Fg(o))}}return e}function el(t,e){if(Array.isArray(t)){const r=t;if(!e)throw new Error("Options parameter is required when providing messages.");return oc(r,e)}else{const r=t;return Cr.from(n=>oc(n,r)).withConfig({runName:"trim_messages"})}}async function oc(t,e){const{maxTokens:r,tokenCounter:n,strategy:a="last",allowPartial:s=!1,endOn:i,startOn:o,includeSystem:c=!1,textSplitter:u}=e;if(o&&a==="first")throw new Error("`startOn` should only be specified if `strategy` is 'last'.");if(c&&a==="first")throw new Error("`includeSystem` should only be specified if `strategy` is 'last'.");let l;"getNumTokens"in n?l=async f=>(await Promise.all(f.map(p=>n.getNumTokens(p.content)))).reduce((p,m)=>p+m,0):l=async f=>n(f);let d=Js;if(u&&("splitText"in u?d=u.splitText:d=async f=>u(f)),a==="first")return tl(t,{maxTokens:r,tokenCounter:l,textSplitter:d,partialStrategy:s?"first":void 0,endOn:i});if(a==="last")return Ug(t,{maxTokens:r,tokenCounter:l,textSplitter:d,allowPartial:s,includeSystem:c,startOn:o,endOn:i});throw new Error(`Unrecognized strategy: '${a}'. Must be one of 'first' or 'last'.`)}async function tl(t,e){const{maxTokens:r,tokenCounter:n,textSplitter:a,partialStrategy:s,endOn:i}=e;let o=[...t],c=0;for(let u=0;u<o.length;u+=1){const l=u>0?o.slice(0,-u):o;if(await n(l)<=r){c=o.length-u;break}}if(c<o.length&&s){let u=!1;if(Array.isArray(o[c].content)){const l=o[c];if(typeof l.content=="string")throw new Error("Expected content to be an array.");const d=l.content.length,f=s==="last"?[...l.content].reverse():l.content;for(let h=1;h<=d;h+=1){const p=s==="first"?f.slice(0,h):f.slice(-h),m=Object.fromEntries(Object.entries(l).filter(([v])=>v!=="type"&&!v.startsWith("lc_"))),g=Ws(l.getType(),{...m,content:p}),y=[...o.slice(0,c),g];if(await n(y)<=r)o=y,c+=1,u=!0;else break}u&&s==="last"&&(l.content=[...f].reverse())}if(!u){const l=o[c];let d;if(Array.isArray(l.content)&&l.content.some(f=>typeof f=="string"||f.type==="text")?d=l.content.find(h=>h.type==="text"&&h.text)?.text:typeof l.content=="string"&&(d=l.content),d){const f=await a(d),h=f.length;s==="last"&&f.reverse();for(let p=0;p<h-1;p+=1)if(f.pop(),l.content=f.join(""),await n([...o.slice(0,c),l])<=r){s==="last"&&(l.content=[...f].reverse().join("")),o=[...o.slice(0,c),l],c+=1;break}}}}if(i){const u=Array.isArray(i)?i:[i];for(;c>0&&!mn(o[c-1],u);)c-=1}return o.slice(0,c)}async function Ug(t,e){const{allowPartial:r=!1,includeSystem:n=!1,endOn:a,startOn:s,...i}=e;let o=t.map(l=>{const d=Object.fromEntries(Object.entries(l).filter(([f])=>f!=="type"&&!f.startsWith("lc_")));return Ws(l.getType(),d,Ss(l))});if(a){const l=Array.isArray(a)?a:[a];for(;o.length>0&&!mn(o[o.length-1],l);)o=o.slice(0,-1)}const c=n&&o[0]?.getType()==="system";let u=c?o.slice(0,1).concat(o.slice(1).reverse()):o.reverse();return u=await tl(u,{...i,partialStrategy:r?"last":void 0,endOn:s}),c?[u[0],...u.slice(1).reverse()]:u.reverse()}const cc={human:{message:Nt,messageChunk:$r},ai:{message:Ot,messageChunk:Pt},system:{message:ut,messageChunk:Rt},developer:{message:ut,messageChunk:Rt},tool:{message:Ct,messageChunk:Tr},function:{message:Ir,messageChunk:Ar},generic:{message:Yt,messageChunk:xr},remove:{message:_r,messageChunk:_r}};function Ws(t,e,r){let n,a;switch(t){case"human":r?n=new $r(e):a=new Nt(e);break;case"ai":if(r){let s={...e};"tool_calls"in s&&(s={...s,tool_call_chunks:s.tool_calls?.map(i=>({...i,type:"tool_call_chunk",index:void 0,args:JSON.stringify(i.args)}))}),n=new Pt(s)}else a=new Ot(e);break;case"system":r?n=new Rt(e):a=new ut(e);break;case"developer":r?n=new Rt({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}}):a=new ut({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in e)r?n=new Tr(e):a=new Ct(e);else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if(r)n=new Ar(e);else{if(!e.name)throw new Error("FunctionMessage must have a 'name' field");a=new Ir(e)}break;case"generic":if("role"in e)r?n=new xr(e):a=new Yt(e);else throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");break;default:throw new Error(`Unrecognized message type ${t}`)}if(r&&n)return n;if(a)return a;throw new Error(`Unrecognized message type ${t}`)}function Fg(t){const e=t.getType();let r;const n=Object.fromEntries(Object.entries(t).filter(([a])=>!["type","tool_call_chunks"].includes(a)&&!a.startsWith("lc_")));if(e in cc&&(r=Ws(e,n)),!r)throw new Error(`Unrecognized message chunk class ${e}. Supported classes are ${Object.keys(cc)}`);return r}function Js(t){const e=t.split(`
|
|
79
|
+
`);return Promise.resolve([...e.slice(0,-1).map(r=>`${r}
|
|
80
|
+
`),e[e.length-1]])}const Bg=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"],zg=["image","video","audio","text-plain","file"],rl=["text","reasoning",...Bg,...zg];var nl={};ge(nl,{AIMessage:()=>Ot,AIMessageChunk:()=>Pt,BaseMessage:()=>tt,BaseMessageChunk:()=>dt,ChatMessage:()=>Yt,ChatMessageChunk:()=>xr,FunctionMessage:()=>Ir,FunctionMessageChunk:()=>Ar,HumanMessage:()=>Nt,HumanMessageChunk:()=>$r,KNOWN_BLOCK_TYPES:()=>rl,RemoveMessage:()=>_r,SystemMessage:()=>ut,SystemMessageChunk:()=>Rt,ToolMessage:()=>Ct,ToolMessageChunk:()=>Tr,_isMessageFieldWithRole:()=>bs,_mergeDicts:()=>ve,_mergeLists:()=>Kt,_mergeObj:()=>ws,_mergeStatus:()=>vs,coerceMessageLikeToMessage:()=>Uc,collapseToolCallChunks:()=>Cs,convertToChunk:()=>sn,convertToOpenAIImageBlock:()=>mc,convertToProviderContentBlock:()=>yc,defaultTextSplitter:()=>Js,defaultToolCallParser:()=>yn,filterMessages:()=>Qu,getBufferString:()=>Os,iife:()=>Dc,isAIMessage:()=>Mc,isAIMessageChunk:()=>jc,isBase64ContentBlock:()=>hs,isBaseMessage:()=>Es,isBaseMessageChunk:()=>Ss,isChatMessage:()=>xc,isChatMessageChunk:()=>Ic,isDataContentBlock:()=>ct,isDirectToolOutput:()=>Is,isFunctionMessage:()=>Ac,isFunctionMessageChunk:()=>$c,isHumanMessage:()=>Rc,isHumanMessageChunk:()=>Oc,isIDContentBlock:()=>ps,isMessage:()=>ms,isOpenAIToolCallArray:()=>bc,isPlainTextContentBlock:()=>pc,isSystemMessage:()=>kc,isSystemMessageChunk:()=>Cc,isToolMessage:()=>As,isToolMessageChunk:()=>$s,isURLContentBlock:()=>fs,mapChatMessagesToStoredMessages:()=>Bc,mapStoredMessageToChatMessage:()=>ks,mapStoredMessagesToChatMessages:()=>Fc,mergeContent:()=>Xe,mergeMessageRuns:()=>Xu,mergeResponseMetadata:()=>Ts,mergeUsageMetadata:()=>xs,parseBase64DataUrl:()=>an,parseMimeType:()=>gc,trimMessages:()=>el});const Sy=Object.freeze(Object.defineProperty({__proto__:null,AIMessage:Ot,AIMessageChunk:Pt,BaseMessage:tt,BaseMessageChunk:dt,ChatMessage:Yt,ChatMessageChunk:xr,FunctionMessage:Ir,FunctionMessageChunk:Ar,HumanMessage:Nt,HumanMessageChunk:$r,KNOWN_BLOCK_TYPES:rl,RemoveMessage:_r,SystemMessage:ut,SystemMessageChunk:Rt,ToolMessage:Ct,ToolMessageChunk:Tr,_isMessageFieldWithRole:bs,_mergeDicts:ve,_mergeLists:Kt,_mergeObj:ws,_mergeStatus:vs,coerceMessageLikeToMessage:Uc,collapseToolCallChunks:Cs,convertToChunk:sn,convertToOpenAIImageBlock:mc,convertToProviderContentBlock:yc,defaultTextSplitter:Js,defaultToolCallParser:yn,filterMessages:Qu,getBufferString:Os,iife:Dc,isAIMessage:Mc,isAIMessageChunk:jc,isBase64ContentBlock:hs,isBaseMessage:Es,isBaseMessageChunk:Ss,isChatMessage:xc,isChatMessageChunk:Ic,isDataContentBlock:ct,isDirectToolOutput:Is,isFunctionMessage:Ac,isFunctionMessageChunk:$c,isHumanMessage:Rc,isHumanMessageChunk:Oc,isIDContentBlock:ps,isMessage:ms,isOpenAIToolCallArray:bc,isPlainTextContentBlock:pc,isSystemMessage:kc,isSystemMessageChunk:Cc,isToolMessage:As,isToolMessageChunk:$s,isURLContentBlock:fs,mapChatMessagesToStoredMessages:Bc,mapStoredMessageToChatMessage:ks,mapStoredMessagesToChatMessages:Fc,mergeContent:Xe,mergeMessageRuns:Xu,mergeResponseMetadata:Ts,mergeUsageMetadata:xs,messages_exports:nl,parseBase64DataUrl:an,parseMimeType:gc,trimMessages:el},Symbol.toStringTag,{value:"Module"}));export{am as $,lt as A,Ot as B,Lt as C,Mp as D,Pt as E,Yt as F,fn as G,As as H,ct as I,yc as J,an as K,It as L,Wu as M,Ip as N,xp as O,cy as P,kt as Q,Lp as R,Oe as S,gd as T,le as U,ye as V,uy as W,nm as X,it as Y,Pu as Z,Nc as _,em as a,ut as a$,Xp as a0,Qp as a1,Zs as a2,py as a3,my as a4,ly as a5,om as a6,os as a7,Ko as a8,yy as a9,Vu as aA,jg as aB,Ey as aC,by as aD,md as aE,Ss as aF,sn as aG,qt as aH,Er as aI,ny as aJ,Vc as aK,b as aL,$r as aM,Rt as aN,Ar as aO,Tr as aP,xr as aQ,gc as aR,Dc as aS,Jc as aT,Ns as aU,kd as aV,Mt as aW,Ge as aX,Ig as aY,ar as aZ,wr as a_,vy as aa,fy as ab,hy as ac,tm as ad,Jo as ae,_y as af,gy as ag,Nt as ah,Os as ai,gr as aj,ks as ak,Uc as al,Mg as am,Tn as an,jc as ao,Cr as ap,fs as aq,hs as ar,mc as as,xt as at,qe as au,me as av,pn as aw,wt as ax,Lg as ay,ac as az,wy as b,tt as b0,Xt as b1,Sp as b2,Ag as b3,Rd as b4,Vp as b5,up as b6,Cp as b7,np as b8,Xh as b9,_r as bA,el as bB,Xg as bC,Kg as bD,Zg as bE,Gg as bF,Qu as bG,dt as bH,Sy as bI,bp as ba,$g as bb,Pp as bc,pd as bd,nl as be,Wl as bf,hp as bg,yp as bh,Fd as bi,gs as bj,Vl as bk,ty as bl,Rr as bm,Vs as bn,lr as bo,Tt as bp,Ml as bq,ee as br,Jg as bs,Qg as bt,Vg as bu,fi as bv,Yg as bw,Wg as bx,Hg as by,ey as bz,ry as c,Is as d,ie as e,Ct as f,ge as g,rm as h,Nu as i,Qr as j,be as k,Jt as l,Go as m,un as n,Dl as o,_p as p,ku as q,dy as r,jl as s,Mc as t,Pc as u,ce as v,zd as w,qs as x,qu as y,Es as z};
|