@mcp-use/inspector 0.14.3-canary.0 → 0.14.3
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 +11 -3
- package/dist/server/{chunk-R5QBLPYB.js → chunk-7ILBF6EL.js} +1 -1
- package/dist/server/{chunk-OSJXVY3O.js → chunk-F2FWROJ2.js} +2 -2
- package/dist/server/{chunk-PUX4EJWH.js → chunk-O7EUTZ5E.js} +1 -1
- package/dist/server/{chunk-Z5QIR3IS.js → chunk-SFZ4CU6U.js} +10 -2
- package/dist/server/{chunk-GDZFYTRE.js → chunk-W5XB3CR5.js} +10 -2
- package/dist/server/{chunk-QCDOO2RF.js → chunk-Z2X4KZ3J.js} +3 -3
- package/dist/server/cli.js +5 -5
- package/dist/server/index.js +6 -6
- package/dist/server/middleware.js +6 -6
- package/dist/server/server.js +5 -5
- package/dist/server/shared-routes.js +3 -3
- package/dist/server/shared-static.js +2 -2
- package/dist/server/shared-utils-browser.d.ts.map +1 -1
- package/dist/server/shared-utils-browser.js +1 -1
- package/dist/server/shared-utils.d.ts.map +1 -1
- package/dist/server/shared-utils.js +1 -1
- package/dist/server/utils.d.ts.map +1 -1
- package/dist/server/utils.js +1 -1
- package/dist/web/assets/browser-CrZmtltD.js +423 -0
- package/dist/web/assets/{client-CBVDiOq1.js → client-CsMGnuwC.js} +6 -6
- package/dist/web/assets/{display-A5IEINAP-DUaOR-3m.js → display-A5IEINAP-D8OCMEUd.js} +2 -2
- package/dist/web/assets/{embeddings-DBkvyXXr.js → embeddings-By0Dfnxp.js} +1 -1
- package/dist/web/assets/{index-nULKD42X.js → index-BvMdqfyu.js} +11 -11
- package/dist/web/assets/{index-CpzEQlXL.js → index-BxMZcKR4.js} +14 -14
- package/dist/web/assets/{index-1YTmX4QT.js → index-CaVm3fHm.js} +2 -2
- package/dist/web/assets/{index-hu1QYxMc.js → index-Cze4GuPX.js} +1 -1
- package/dist/web/assets/index-D7mhOTIc.js +80 -0
- package/dist/web/assets/{index-CvL4NMn9.js → index-DYa4NhVm.js} +1 -1
- package/dist/web/assets/index-DjkfvIWz.js +1783 -0
- package/dist/web/assets/index-DlhqMiEp.css +1 -0
- package/dist/web/assets/index-DwWeVml5.js +7 -0
- package/dist/web/assets/{index-BpbjNRUs.js → index-o8LZS9ZF.js} +6 -6
- package/dist/web/assets/{llms-DLjfslEu.js → llms-DCC0HMlB.js} +1 -1
- package/dist/web/index.html +3 -3
- package/package.json +5 -5
- package/dist/web/assets/browser-CJMCg3ZC.js +0 -410
- package/dist/web/assets/index-C314DwyM.js +0 -40
- package/dist/web/assets/index-CW3Avs3Z.js +0 -80
- package/dist/web/assets/index-CqlJu5dO.js +0 -1753
- package/dist/web/assets/index-G80eS8Oh.css +0 -1
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import{bl as gn,bL as Pe,bM as fc,bN as nt,bO as ll,bP as dl,bQ as hc,bJ as fs,bR as fl,bS as hl,bT as pl,bU as ml,bI as ei}from"./index-DjkfvIWz.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 ti;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(ti||(ti={}));const R=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 R.undefined;case"string":return R.string;case"number":return Number.isNaN(t)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(t)?R.array:t===null?R.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?R.promise:typeof Map<"u"&&t instanceof Map?R.map:typeof Set<"u"&&t instanceof Set?R.set:typeof Date<"u"&&t instanceof Date?R.date:R.object;default:return R.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 Le 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 Le))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()}}Le.create=t=>new Le(t);const dr=(t,e)=>{let r;switch(t.code){case w.invalid_type:t.received===R.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 gl=dr;function Ba(){return gl}const qa=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=Ba(),n=qa({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}),ri=t=>t.status==="aborted",ni=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 ai=(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 Le(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 ai(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 ai(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 _t.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 Wa({...Q(this._def),innerType:this,defaultValue:r,typeName:b.ZodDefault})}brand(){return new Ul({typeName:b.ZodBranded,type:this,...Q(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new Ja({...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 hs.create(this,e)}readonly(){return Ka.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const _l=/^c[^\s-]{8,}$/i,yl=/^[0-9a-z]+$/,vl=/^[0-9A-HJKMNP-TV-Z]{26}$/i,wl=/^[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,bl=/^[a-z0-9_-]{21}$/i,El=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Sl=/^[-+]?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)?)??$/,Tl=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,xl="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let On;const Il=/^(?:(?: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])$/,Al=/^(?:(?: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])$/,$l=/^(([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]))$/,Ol=/^(([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])$/,Rl=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,kl=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,pc="((\\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])))",Cl=new RegExp(`^${pc}$`);function mc(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 Nl(t){return new RegExp(`^${mc(t)}$`)}function Pl(t){let e=`${pc}T${mc(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 Ml(t,e){return!!((e==="v4"||!e)&&Il.test(t)||(e==="v6"||!e)&&$l.test(t))}function Ll(t,e){if(!El.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 jl(t,e){return!!((e==="v4"||!e)&&Al.test(t)||(e==="v6"||!e)&&Ol.test(t))}class at extends ee{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){const s=this._getOrReturnCtx(e);return x(s,{code:w.invalid_type,expected:R.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")Tl.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")On||(On=new RegExp(xl,"u")),On.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")wl.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")bl.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")_l.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")yl.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")vl.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"?Pl(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"?Cl.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{code:w.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Nl(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"?Sl.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"duration",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Ml(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"?Ll(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"?jl(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"?Rl.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"base64",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?kl.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 Dl(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)!==R.number){const s=this._getOrReturnCtx(e);return x(s,{code:w.invalid_type,expected:R.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"?Dl(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)!==R.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:R.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 Ga extends ee{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){const n=this._getOrReturnCtx(e);return x(n,{code:w.invalid_type,expected:R.boolean,received:n.parsedType}),V}return ke(e.data)}}Ga.create=t=>new Ga({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)!==R.date){const s=this._getOrReturnCtx(e);return x(s,{code:w.invalid_type,expected:R.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 si extends ee{_parse(e){if(this._getType(e)!==R.symbol){const n=this._getOrReturnCtx(e);return x(n,{code:w.invalid_type,expected:R.symbol,received:n.parsedType}),V}return ke(e.data)}}si.create=t=>new si({typeName:b.ZodSymbol,...Q(t)});class Ha extends ee{_parse(e){if(this._getType(e)!==R.undefined){const n=this._getOrReturnCtx(e);return x(n,{code:w.invalid_type,expected:R.undefined,received:n.parsedType}),V}return ke(e.data)}}Ha.create=t=>new Ha({typeName:b.ZodUndefined,...Q(t)});class ii extends ee{_parse(e){if(this._getType(e)!==R.null){const n=this._getOrReturnCtx(e);return x(n,{code:w.invalid_type,expected:R.null,received:n.parsedType}),V}return ke(e.data)}}ii.create=t=>new ii({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 Bt extends ee{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ke(e.data)}}Bt.create=t=>new Bt({typeName:b.ZodUnknown,...Q(t)});class vt extends ee{_parse(e){const r=this._getOrReturnCtx(e);return x(r,{code:w.invalid_type,expected:R.never,received:r.parsedType}),V}}vt.create=t=>new vt({typeName:b.ZodNever,...Q(t)});class oi extends ee{_parse(e){if(this._getType(e)!==R.undefined){const n=this._getOrReturnCtx(e);return x(n,{code:w.invalid_type,expected:R.void,received:n.parsedType}),V}return ke(e.data)}}oi.create=t=>new oi({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!==R.array)return x(r,{code:w.invalid_type,expected:R.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]=_t.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 _t?_t.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)!==R.object){const u=this._getOrReturnCtx(e);return x(u,{code:w.invalid_type,expected:R.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 _t;)s=s._def.innerType;r[n]=s}return new de({...this._def,shape:()=>r})}keyof(){return gc(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 Le(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 Le(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 Za(t,e){const r=pt(t),n=pt(e);if(t===e)return{valid:!0,data:t};if(r===R.object&&n===R.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=Za(t[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(r===R.array&&n===R.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=Za(i,o);if(!c.valid)return{valid:!1};a.push(c.data)}return{valid:!0,data:a}}else return r===R.date&&n===R.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(ri(s)||ri(i))return V;const o=Za(s.value,i.value);return o.valid?((ni(s)||ni(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!==R.array)return x(n,{code:w.invalid_type,expected:R.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!==R.object)return x(n,{code:w.invalid_type,expected:R.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 ci 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!==R.map)return x(n,{code:w.invalid_type,expected:R.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}}}}ci.create=(t,e,r)=>new ci({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!==R.set)return x(n,{code:w.invalid_type,expected:R.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!==R.function)return x(r,{code:w.invalid_type,expected:R.function,received:r.parsedType}),V;function n(o,c){return qa({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ba(),dr].filter(u=>!!u),issueData:{code:w.invalid_arguments,argumentsError:c}})}function a(o,c){return qa({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ba(),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 Le([]),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 Le([n(c,u.error)]);const l=Reflect.apply(i,this,u.data),d=o._def.returns.safeParse(l,s);if(!d.success)throw new Le([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(Bt.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(Bt.create()),returns:r||Bt.create(),typeName:b.ZodFunction,...Q(n)})}}class ui 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})}}ui.create=(t,e)=>new ui({getter:t,typeName:b.ZodLazy,...Q(e)});class Va 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}}Va.create=(t,e)=>new Va({value:t,typeName:b.ZodLiteral,...Q(e)});function gc(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=gc;class li extends ee{_parse(e){const r=te.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.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}}li.create=(t,e)=>new li({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!==R.promise&&r.common.async===!1)return x(r,{code:w.invalid_type,expected:R.promise,received:r.parsedType}),V;const n=r.parsedType===R.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 _t extends ee{_parse(e){return this._getType(e)===R.undefined?ke(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}_t.create=(t,e)=>new _t({innerType:t,typeName:b.ZodOptional,...Q(e)});class Wt extends ee{_parse(e){return this._getType(e)===R.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 Wa extends ee{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}Wa.create=(t,e)=>new Wa({innerType:t,typeName:b.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Q(e)});class Ja 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 Le(n.common.issues)},input:n.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Le(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Ja.create=(t,e)=>new Ja({innerType:t,typeName:b.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Q(e)});class di extends ee{_parse(e){if(this._getType(e)!==R.nan){const n=this._getOrReturnCtx(e);return x(n,{code:w.invalid_type,expected:R.nan,received:n.parsedType}),V}return{status:"valid",value:e.data}}}di.create=t=>new di({typeName:b.ZodNaN,...Q(t)});class Ul 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 hs 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 hs({in:e,out:r,typeName:b.ZodPipeline})}}class Ka 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}}Ka.create=(t,e)=>new Ka({innerType:t,typeName:b.ZodReadonly,...Q(e)});function fi(t,e){const r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Fl(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=fi(e,n),c=o.fatal??r??!0;a.addIssue({code:"custom",...o,fatal:c})}});if(!s){const i=fi(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 s_=(t,e={message:`Input not instance of ${t.name}`})=>Fl(r=>r instanceof t,e),zl=at.create,i_=Ht.create,o_=Ga.create,c_=Ha.create,hi=hr.create;Bt.create;vt.create;const u_=Ke.create,Bl=de.create,l_=tn.create;rn.create;ot.create;const d_=nn.create,f_=cr.create,h_=Va.create,p_=Zt.create,m_=mr.create;_t.create;Wt.create;var ql=Object.defineProperty,ge=(t,e)=>{for(var r in e)ql(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 ps(t){return ct(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function ms(t){return ct(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function _c(t){return ct(t)&&t.source_type==="text"&&"text"in t&&typeof t.text=="string"}function gs(t){return ct(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}function yc(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 vc(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 wc(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 _s(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}var Rn,pi;function Gl(){return pi||(pi=1,Rn=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()}),Rn}var Hl=Gl();const Zl=gn(Hl);var Dr={exports:{}},mi;function Vl(){if(mi)return Dr.exports;mi=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,_=!1;for(let v=0;v<f.length;v++){const y=f[v];m&&t.test(y)?(f=f.slice(0,v)+"-"+f.slice(v),m=!1,_=g,g=!0,v++):g&&_&&e.test(y)?(f=f.slice(0,v-1)+"-"+f.slice(v-1),_=g,g=!1,m=!0):(m=h(y)===y&&p(y)!==y,_=g,g=p(y)===y&&h(y)!==y)}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(_=>_.trim()).filter(_=>_.length).join("-"):f=f.trim(),f.length===0)return"";const p=h.locale===!1?_=>_.toLowerCase():_=>_.toLocaleLowerCase(h.locale),m=h.locale===!1?_=>_.toUpperCase():_=>_.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 Wl=Vl();const Jl=gn(Wl);function Kl(t,e){return e?.[t]||Zl(t)}function g_(t,e){return e?.[t]||Jl(t)}function Yl(t,e,r){const n={};for(const a in t)Object.hasOwn(t,a)&&(n[e(a,r)]=t[a]);return n}const _n="__lc_escaped__";function Ql(t){return"lc"in t||Object.keys(t).length===1&&_n in t}function Xl(t){return{[_n]:t}}function ed(t){return Object.keys(t).length===1&&_n in t}function td(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}function rd(t){let e;return t!==null&&typeof t=="object"?"lc_id"in t&&Array.isArray(t.lc_id)?e=t.lc_id:e=[t.constructor?.name??"Object"]:e=[typeof t],{lc:1,type:"not_implemented",id:e}}function Ya(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return rd(t);if(td(t))return t;e.add(t);const r=t;if(Ql(r))return e.delete(t),Xl(r);const n={};for(const[a,s]of Object.entries(r))n[a]=Ya(s,e);return e.delete(t),n}return Array.isArray(t)?t.map(r=>Ya(r,e)):t}function gi(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){const e=t;if(ed(e))return e[_n];const r={};for(const[n,a]of Object.entries(e))r[n]=gi(a);return r}return Array.isArray(t)?t.map(e=>gi(e)):t}var nd={};ge(nd,{Serializable:()=>gr,get_lc_unique_name:()=>ys});function _i(t){return Array.isArray(t)?[...t]:{...t}}function ad(t,e){const r=_i(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]=_i(o[c]),o=o[c]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[a]})}return r}function ys(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 bc{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,ys(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 bc||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},r={},n=Object.keys(this.lc_kwargs).reduce((c,u)=>(c[u]=u in this?this[u]:this.lc_kwargs[u],c),{});for(let c=Object.getPrototypeOf(this);c;c=Object.getPrototypeOf(c))Object.assign(e,Reflect.get(c,"lc_aliases",this)),Object.assign(r,Reflect.get(c,"lc_secrets",this)),Object.assign(n,Reflect.get(c,"lc_attributes",this));Object.keys(r).forEach(c=>{let u=this,l=n;const[d,...f]=c.split(".").reverse();for(const h of f.reverse()){if(!(h in u)||u[h]===void 0)return;(!(h in l)||l[h]===void 0)&&(typeof u[h]=="object"&&u[h]!=null?l[h]={}:Array.isArray(u[h])&&(l[h]=[])),u=u[h],l=l[h]}d in u&&u[d]!==void 0&&(l[d]=l[d]||u[d])});const a={},s=new WeakSet;s.add(this);for(const[c,u]of Object.entries(n))a[c]=Ya(u,s);const i=Object.keys(r).length?ad(a,r):a,o=Yl(i,Kl,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:o}}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 Be(t){return typeof t=="number"}function vs(t){return t instanceof Uint8Array}function yi(t){try{return JSON.parse(t)}catch{return}}const _r=t=>t();function sd(t){if(t.type==="char_location"&&k(t.document_title)&&Be(t.start_char_index)&&Be(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)&&Be(t.start_page_number)&&Be(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)&&Be(t.start_block_index)&&Be(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)&&Be(t.start_block_index)&&Be(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 Ec(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 id(t){function*e(){for(const r of t){const n=Ec(r);n?yield n:yield r}}return Array.from(e())}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)){const{text:a,citations:s,...i}=n;if(Ye(s)&&s.length){const o=s.reduce((c,u)=>{const l=sd(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(cd(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=_r(()=>{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=yi(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=_r(()=>{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=yi(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=Ec(n);if(a){yield a;continue}}yield{type:"non_standard",value:n}}}return Array.from(e())}const od={translateContent:vi,translateContentChunk:vi};function cd(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}function ud(t){return ps(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:ms(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:gs(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}function ld(t){return t.map(ud)}function dd(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 fd(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 hd(t){const e=[];typeof t.content=="string"?e.push({type:"text",text:t.content}):e.push(...ws(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 pd(t){const e=[];typeof t.content=="string"?e.push({type:"text",text:t.content}):e.push(...ws(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 ws(t){const e=[];for(const r of t)dd(r)?e.push(fd(r)):e.push(r);return e}function md(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 Sc(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(md)}: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=_r(()=>{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 gd(t){function*e(){yield*Sc(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 _d={translateContent:t=>typeof t.content=="string"?hd(t):Sc(t),translateContentChunk:t=>typeof t.content=="string"?pd(t):gd(t)};function yd(t,e="pretty"){return e==="pretty"?vd(t):JSON.stringify(t)}function vd(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 kn=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 bs(t,e){return t==="error"||e==="error"?"error":"success"}function wd(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"}}[kn]=!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[ld,ws,id].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&&kn in t&&t[kn]===!0&&_s(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=wd(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return yd(this,t)}};function Tc(t){return Array.isArray(t)&&t.every(e=>typeof e.index=="number")}function ve(t,e){if(t===void 0&&e===void 0)return;if(t===void 0||e===void 0)return 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]=="number")r[n]=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 Es(t,e){if(!(t===void 0&&e===void 0)){if(t===void 0||e===void 0)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 xc extends tt{static isInstance(e){if(!super.isInstance(e))return!1;let r=Object.getPrototypeOf(e);for(;r!==null;){if(r===xc.prototype)return!0;r=Object.getPrototypeOf(r)}return!1}};function Ss(t){return typeof t.role=="string"}function Ts(t){return typeof t?._getType=="function"}function xs(t){return dt.isInstance(t)}function Is(t,e){return ve(t,e)??{}}function Ic(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 bd(t,e){const r={...Ic(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 Ed(t,e){const r={...Ic(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(r.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),r}function yn(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:bd(t?.input_token_details,e?.input_token_details),output_token_details:Ed(t?.output_token_details,e?.output_token_details)}}var Sd={};ge(Sd,{ToolMessage:()=>Ct,ToolMessageChunk:()=>Tr,defaultToolCallParser:()=>vn,isDirectToolOutput:()=>As,isToolMessage:()=>$s,isToolMessageChunk:()=>Os});function As(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:Es(this.artifact,t.artifact),tool_call_id:this.tool_call_id,id:this.id??t.id,status:bs(this.status,t.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function vn(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 $s(t){return typeof t=="object"&&t!==null&&"getType"in t&&typeof t.getType=="function"&&t.getType()==="tool"}function Os(t){return t._getType()==="tool"}var Yt=class Ac extends tt{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return Ac}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 $c(t){return t._getType()==="generic"}function Oc(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 Rc(t){return t._getType()==="function"}function kc(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 Cc(t){return t.getType()==="human"}function Nc(t){return t.getType()==="human"}var yr=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 Pc(t){return t._getType()==="system"}function Mc(t){return t._getType()==="system"}function Td(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 Lc(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function __(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 xd=class extends Error{output;constructor(t,e){super(t),this.output=e}};function y_(t,e=jc){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 Id(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 jc(t){try{return typeof t>"u"?null:Id(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 Ad(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(vs(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 $d(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(vs(t.image.source.bytes))return{type:"image",mimeType:r,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}function Od(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(vs(t.video.source.bytes))return{type:"video",mimeType:r,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}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,"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=_r(()=>{if(K(o.location)){const l=o.location.documentChar||o.location.documentPage||o.location.documentChunk;if(K(l))return{source:Be(l.documentIndex)?l.documentIndex.toString():void 0,startIndex:Be(l.start)?l.start:void 0,endIndex:Be(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 Ad(n);continue}else if(D(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(D(n,"image")&&K(n.image)){yield $d(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 Od(n);continue}}yield{type:"non_standard",value:n}}}return Array.from(e())}const Rd={translateContent:wi,translateContentChunk:wi};function bi(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 kd={translateContent:bi,translateContentChunk:bi};function Ei(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=_r(()=>{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 Cd={translateContent:Ei,translateContentChunk:Ei};globalThis.lc_block_translators_registry??=new Map([["anthropic",od],["bedrock-converse",Rd],["google-genai",kd],["google-vertexai",Cd],["openai",_d]]);function Dc(t){return globalThis.lc_block_translators_registry.get(t)}var wt=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]=vn(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.tool_calls&&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=Dc(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=>({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 Uc(t){return t._getType()==="ai"}function Fc(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;if(typeof t=="string"||Array.isArray(t))e={content:t,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(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};else{const r=Ns(t.tool_call_chunks??[]);e={...t,tool_call_chunks:r.tool_call_chunks,tool_calls:r.tool_calls,invalid_tool_calls:r.invalid_tool_calls,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=Dc(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:Is(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=yn(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 zc=t=>t();function Nd(t){return Lc(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 Pd(t){return typeof t=="object"&&t!=null&&t.lc===1&&Array.isArray(t.id)&&t.kwargs!=null&&typeof t.kwargs=="object"}function Cn(t){let e,r;if(Pd(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 wt(r);const s=n.map(Nd);return new wt({...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 yr({...r,id:r.id});throw Td(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 Bc(t){if(typeof t=="string")return new Nt(t);if(Ts(t))return t;if(Array.isArray(t)){const[e,r]=t;return Cn({type:e,content:r})}else if(Ss(t)){const{role:e,...r}=t;return Cn({...r,type:e})}else return Cn(t)}function ks(t,e="Human",r="AI"){const n=[];for(const a of t){let s;if(a.type==="human")s=e;else if(a.type==="ai")s=r;else if(a.type==="system")s="System";else if(a.type==="tool")s="Tool";else if(a.type==="generic")s=a.role;else throw new Error(`Got unsupported message type: ${a.type}`);const i=a.name?`${a.name}, `:"",o=a.text;let c=`${s}: ${i}${o}`;if(a.type==="ai"){const u=a;u.tool_calls&&u.tool_calls.length>0?c+=JSON.stringify(u.tool_calls):u.additional_kwargs&&"function_call"in u.additional_kwargs&&(c+=JSON.stringify(u.additional_kwargs.function_call))}n.push(c)}return n.join(`
|
|
17
|
+
`)}function Md(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 Cs(t){const e=Md(t);switch(e.type){case"human":return new Nt(e.data);case"ai":return new wt(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 qc(t){return t.map(Cs)}function Gc(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 Ns(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=jc(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 Hc=Symbol.for("ls:tracing_async_local_storage"),ur=Symbol.for("lc:context_variables"),Ld=t=>{globalThis[Hc]=t},vr=()=>globalThis[Hc];var jd={},Dd={};ge(Dd,{getEnv:()=>Kc,getEnvironmentVariable:()=>At,getRuntimeEnvironment:()=>Yc,isBrowser:()=>Zc,isDeno:()=>wn,isJsDom:()=>Wc,isNode:()=>Jc,isWebWorker:()=>Vc});const Zc=()=>typeof window<"u"&&typeof window.document<"u",Vc=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Wc=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),wn=()=>typeof Deno<"u",Jc=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!wn(),Kc=()=>{let t;return Zc()?t="browser":Jc()?t="node":Vc()?t="webworker":Wc()?t="jsdom":wn()?t="deno":t="other",t};let Nn;function Yc(){return Nn===void 0&&(Nn={library:"langchain-js",runtime:Kc()}),Nn}function At(t){try{return typeof process<"u"?jd?.[t]:wn()?Deno?.env.get(t):void 0}catch{return}}const Ud=/^(?:[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"&&Ud.test(t)}function Fd(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 ye=[];for(var Pn=0;Pn<256;++Pn)ye.push((Pn+256).toString(16).slice(1));function Ps(t,e=0){return(ye[t[e+0]]+ye[t[e+1]]+ye[t[e+2]]+ye[t[e+3]]+"-"+ye[t[e+4]]+ye[t[e+5]]+"-"+ye[t[e+6]]+ye[t[e+7]]+"-"+ye[t[e+8]]+ye[t[e+9]]+"-"+ye[t[e+10]]+ye[t[e+11]]+ye[t[e+12]]+ye[t[e+13]]+ye[t[e+14]]+ye[t[e+15]]).toLowerCase()}var Ur,zd=new Uint8Array(16);function Qc(){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(zd)}function Bd(t){t=unescape(encodeURIComponent(t));for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var qd="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Gd="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Hd(t,e,r){function n(a,s,i,o){var c;if(typeof a=="string"&&(a=Bd(a)),typeof s=="string"&&(s=Fd(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 Ps(u)}try{n.name=t}catch{}return n.DNS=qd,n.URL=Gd,n}var Zd=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Si={randomUUID:Zd};function xt(t,e,r){if(Si.randomUUID&&!t)return Si.randomUUID();t=t||{};var n=t.random||(t.rng||Qc)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,Ps(n)}function Vd(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 Mn(t,e){return t<<e|t>>>32-e}function Wd(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]=Mn(f[p-3]^f[p-8]^f[p-14]^f[p-16],1);for(var m=r[0],g=r[1],_=r[2],v=r[3],y=r[4],S=0;S<80;++S){var O=Math.floor(S/20),U=Mn(m,5)+Vd(O,g,_,v)+y+e[O]+f[S]>>>0;y=v,v=_,_=Mn(g,30)>>>0,g=m,m=U}r[0]=r[0]+m>>>0,r[1]=r[1]+g>>>0,r[2]=r[2]+_>>>0,r[3]=r[3]+v>>>0,r[4]=r[4]+y>>>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=Hd("v5",80,Wd),Ti=null,xi=null,De=0;function mt(t,e,r){t=t||{};var n=0,a=new Uint8Array(16),s=t.random||(t.rng||Qc)(),i=t.msecs!==void 0?t.msecs:Date.now(),o=t.seq!==void 0?t.seq:null,c=xi,u=Ti;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,xi=c,Ti=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],Ps(a)}var Jd={};ge(Jd,{BaseCallbackHandler:()=>Or,callbackHandlerPrefersStreaming:()=>Yd,isBaseCallbackHandler:()=>Xc});var Kd=class{};function Yd(t){return"lc_prefer_streaming"in t&&t.lc_prefer_streaming}var Or=class extends Kd{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,ys(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=At("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 Or{name=mt();constructor(){super(),Object.assign(this,t)}}return new e}};const Xc=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",Xd="gen_ai.system",Ii="gen_ai.request.model",ef="gen_ai.response.model",Ai="gen_ai.usage.input_tokens",$i="gen_ai.usage.output_tokens",Oi="gen_ai.usage.total_tokens",tf="gen_ai.request.max_tokens",rf="gen_ai.request.temperature",nf="gen_ai.request.top_p",af="gen_ai.request.frequency_penalty",sf="gen_ai.request.presence_penalty",of="gen_ai.response.finish_reasons",cf="gen_ai.prompt",uf="gen_ai.completion",lf="gen_ai.request.extra_query",df="gen_ai.request.extra_body",ff="gen_ai.serialized.name",hf="gen_ai.serialized.signature",pf="gen_ai.serialized.doc",mf="gen_ai.response.id",gf="gen_ai.response.service_tier",_f="gen_ai.response.system_fingerprint",yf="gen_ai.usage.input_token_details",vf="gen_ai.usage.output_token_details",wf="langsmith.trace.session_id",bf="langsmith.trace.session_name",Ef="langsmith.span.kind",Sf="langsmith.trace.name",Tf="langsmith.metadata",Ri="langsmith.span.tags",xf="langsmith.request.streaming",If="langsmith.request.headers",Af=(...t)=>fetch(...t),eu=Symbol.for("ls:fetch_implementation"),$f=()=>{const t=globalThis[eu];return t?typeof t=="function"&&"Headers"in t&&"Request"in t&&"Response"in t:!1},Of=t=>async(...e)=>{if(t||Oe("DEBUG")==="true"){const[n,a]=e;console.log(`→ ${a?.method||"GET"} ${n}`)}const r=await(globalThis[eu]??Af)(...e);return(t||Oe("DEBUG")==="true")&&console.log(`← ${r.status} ${r.statusText} ${r.url}`),r},tu=()=>Oe("PROJECT")??et("LANGCHAIN_SESSION")??"default",ki={};function ru(t){ki[t]||(console.warn(t),ki[t]=!0)}const Rf=/^[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(!Rf.test(t)){const r=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(r)}return t}function kf(t){const e=typeof t=="string"?Date.parse(t):t;return mt({msecs:e,seq:0})}function Cf(t,e){throw new Error("dump() is not supported in browser environments.")}function Nf(t){throw new Error("load() is not supported in browser environments.")}function Pf(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}class Mf{constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchFunc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??3600,this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.fetchFunc=e.fetchFunc,this.fetchFunc&&this.ttlSeconds!==null&&this.startRefreshLoop()}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){const e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e){const r=this.cache.get(e);if(!r){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,r),this._metrics.hits+=1,r.value}set(e,r){if(!this.cache.has(e)&&this.cache.size>=this.maxSize){const a=this.cache.keys().next().value;a!==void 0&&this.cache.delete(a)}const n={value:r,createdAt:Date.now()};this.cache.delete(e),this.cache.set(e,n)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(e){for(const[r,n]of this.cache.entries())n.value;Cf()}load(e){const r=Nf();if(!r)return 0;let n=0;const a=Date.now();for(const[s,i]of Object.entries(r)){if(this.cache.size>=this.maxSize)break;const o={value:i,createdAt:a};this.cache.set(s,o),n+=1}return n}startRefreshLoop(){this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn("Unexpected error in cache refresh loop:",e)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref()}getStaleKeys(){const e=[];for(const[r,n]of this.cache.entries())Pf(n,this.ttlSeconds)&&e.push(r);return e}async refreshStaleEntries(){if(!this.fetchFunc)return;const e=this.getStaleKeys();if(e.length!==0)for(const r of e)try{const n=await this.fetchFunc(r);this.set(r,n),this._metrics.refreshes+=1}catch(n){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${r}:`,n)}}}const nu="0.4.5";var Qa={};let We;const Lf=()=>typeof window<"u"&&typeof window.document<"u",jf=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Df=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),au=()=>typeof Deno<"u",Uf=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!au(),su=()=>We||(typeof Bun<"u"?We="bun":Lf()?We="browser":Uf()?We="node":jf()?We="webworker":Df()?We="jsdom":au()?We="deno":We="other",We);let Ln;function iu(){if(Ln===void 0){const t=su(),e=zf();Ln={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:nu,...e}}return Ln}function ou(){const t=Ff(),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 Ff(){const t={};try{if(typeof process<"u"&&Qa)for(const[e,r]of Object.entries(Qa))(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"?Qa?.[t]:void 0}catch{return}}function Oe(t){return et(`LANGSMITH_${t}`)||et(`LANGCHAIN_${t}`)}let jn;function zf(){if(jn!==void 0)return jn;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 jn=e,e}function cu(){return et("OTEL_ENABLED")==="true"||Oe("OTEL_ENABLED")==="true"}class Bf{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...r){!this.hasWarned&&cu()&&(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 qf{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new Bf})}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 Gf{active(){return{}}with(e,r){return r()}}const Dn=Symbol.for("ls:otel_trace"),Un=Symbol.for("ls:otel_context"),Ci=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),Hf=new qf,Zf=new Gf;class Vf{getTraceInstance(){return globalThis[Dn]??Hf}getContextInstance(){return globalThis[Un]??Zf}initializeGlobalInstances(e){globalThis[Dn]===void 0&&(globalThis[Dn]=e.trace),globalThis[Un]===void 0&&(globalThis[Un]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[Ci]=e}getDefaultOTLPTracerComponents(){return globalThis[Ci]??void 0}}const Ms=new Vf;function uu(){return Ms.getTraceInstance()}function Wf(){return Ms.getContextInstance()}function Jf(){return Ms.getDefaultOTLPTracerComponents()}const Kf={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function Yf(t){return Kf[t]||t}class Qf{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&&uu().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(Ef,r.run_type);const o=Yf(r.run_type||"chain");e.setAttribute(Qd,o)}"name"in r&&r.name&&e.setAttribute(Sf,r.name),"session_id"in r&&r.session_id&&e.setAttribute(wf,r.session_id),"session_name"in r&&r.session_name&&e.setAttribute(bf,r.session_name),this.setGenAiSystem(e,r);const a=this.extractModelName(r);a&&e.setAttribute(Ii,a),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&e.setAttribute(Ai,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&e.setAttribute($i,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&e.setAttribute(Oi,r.total_tokens),this.setInvocationParameters(e,r);const s=r.extra?.metadata||{};for(const[o,c]of Object.entries(s))c!=null&&e.setAttribute(`${Tf}.${o}`,String(c));const i=r.tags;if(i&&Array.isArray(i)?e.setAttribute(Ri,i.join(", ")):i&&e.setAttribute(Ri,String(i)),"serialized"in r&&typeof r.serialized=="object"){const o=r.serialized;o.name&&e.setAttribute(ff,String(o.name)),o.signature&&e.setAttribute(hf,String(o.signature)),o.doc&&e.setAttribute(pf,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(Xd,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(tf,n.max_tokens),n.temperature!==void 0&&e.setAttribute(rf,n.temperature),n.top_p!==void 0&&e.setAttribute(nf,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(af,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(sf,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(Ii,n.model),n.stream!==void 0&&e.setAttribute(xf,n.stream),n.extra_headers&&e.setAttribute(If,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(lf,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(df,JSON.stringify(n.extra_body))),e.setAttribute(cf,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(Ai,a[0]),e.setAttribute($i,a[1]),e.setAttribute(Oi,a[0]+a[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(ef,String(n.model)),n.id&&e.setAttribute(mf,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(of,s.join(", "))}if(n.service_tier&&e.setAttribute(gf,n.service_tier),n.system_fingerprint&&e.setAttribute(_f,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){const s=n.usage_metadata;s.input_token_details&&e.setAttribute(yf,JSON.stringify(s.input_token_details)),s.output_token_details&&e.setAttribute(vf,JSON.stringify(s.output_token_details))}}e.setAttribute(uf,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 Xf=Object.prototype.toString,eh=t=>Xf.call(t)==="[object Error]",th=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 rh(t){if(!(t&&eh(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:th.has(r)}function nh(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 ah=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 sh(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 Ni(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}async function ih({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 ah)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),Ni(n,o)<=0)throw s;const u=await a.shouldConsumeRetry(c),l=Ni(n,o);if(l<=0||i<=0)throw s;if(s instanceof TypeError&&!rh(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=sh(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 oh(t,e={}){if(e={...e},nh(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 ih({error:s,attemptNumber:r,retriesConsumed:n,startTime:a,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var zr={},Fn={exports:{}},Pi;function ch(){return Pi||(Pi=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],_=arguments.length,v,y;if(g.fn){switch(g.once&&this.removeListener(u,g.fn,void 0,!0),_){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(y=1,v=new Array(_-1);y<_;y++)v[y-1]=arguments[y];g.fn.apply(g.context,v)}else{var S=g.length,O;for(y=0;y<S;y++)switch(g[y].once&&this.removeListener(u,g[y].fn,void 0,!0),_){case 1:g[y].fn.call(g[y].context);break;case 2:g[y].fn.call(g[y].context,l);break;case 3:g[y].fn.call(g[y].context,l,d);break;case 4:g[y].fn.call(g[y].context,l,d,f);break;default:if(!v)for(O=1,v=new Array(_-1);O<_;O++)v[O-1]=arguments[O];g[y].fn.apply(g[y].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=[],_=p.length;m<_;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})(Fn)),Fn.exports}var rr={exports:{}},zn,Mi;function uh(){return Mi||(Mi=1,zn=(t,e)=>(e=e||(()=>{}),t.then(r=>new Promise(n=>{n(e())}).then(()=>r),r=>new Promise(n=>{n(e())}).then(()=>{throw r})))),zn}var Li;function lh(){if(Li)return rr.exports;Li=1;const t=uh();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 Br={},qr={},ji;function dh(){if(ji)return qr;ji=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 Di;function fh(){if(Di)return Br;Di=1,Object.defineProperty(Br,"__esModule",{value:!0});const t=dh();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 Br.default=e,Br}var Ui;function hh(){if(Ui)return zr;Ui=1,Object.defineProperty(zr,"__esModule",{value:!0});const t=ch(),e=lh(),r=fh(),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 zr.default=s,zr}var ph=hh();const st=gn(ph),mh=[408,425,429,500,502,503,504];let Fi=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(()=>oh(()=>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&&!mh.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 zi(t){return typeof t?._getType=="function"}function Bi(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:{}},Bn,qi;function bn(){if(qi)return Bn;qi=1;const t="2.0.0",e=256,r=Number.MAX_SAFE_INTEGER||9007199254740991,n=16,a=e-6;return Bn={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},Bn}var qn,Gi;function En(){if(Gi)return qn;Gi=1;var t={};return qn=typeof process=="object"&&t&&t.NODE_DEBUG&&/\bsemver\b/i.test(t.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{},qn}var Hi;function Rr(){return Hi||(Hi=1,(function(t,e){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:a}=bn(),s=En();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[_,v]of h)g=g.split(`${_}*`).join(`${_}{0,${v}}`).split(`${_}+`).join(`${_}{1,${v}}`);return g},m=(g,_,v)=>{const y=p(_),S=d++;s(g,S,_),l[g]=S,c[S]=_,u[S]=y,i[S]=new RegExp(_,v?"g":void 0),o[S]=new RegExp(y,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 Gn,Zi;function Ls(){if(Zi)return Gn;Zi=1;const t=Object.freeze({loose:!0}),e=Object.freeze({});return Gn=n=>n?typeof n!="object"?t:n:e,Gn}var Hn,Vi;function lu(){if(Vi)return Hn;Vi=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 Hn={compareIdentifiers:e,rcompareIdentifiers:(n,a)=>e(a,n)},Hn}var Zn,Wi;function xe(){if(Wi)return Zn;Wi=1;const t=En(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:r}=bn(),{safeRe:n,t:a}=Rr(),s=Ls(),{compareIdentifiers:i}=lu();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 Zn=o,Zn}var Vn,Ji;function Qt(){if(Ji)return Vn;Ji=1;const t=xe();return Vn=(r,n,a=!1)=>{if(r instanceof t)return r;try{return new t(r,n)}catch(s){if(!a)return null;throw s}},Vn}var Wn,Ki;function gh(){if(Ki)return Wn;Ki=1;const t=Qt();return Wn=(r,n)=>{const a=t(r,n);return a?a.version:null},Wn}var Jn,Yi;function _h(){if(Yi)return Jn;Yi=1;const t=Qt();return Jn=(r,n)=>{const a=t(r.trim().replace(/^[=v]+/,""),n);return a?a.version:null},Jn}var Kn,Qi;function yh(){if(Qi)return Kn;Qi=1;const t=xe();return Kn=(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}},Kn}var Yn,Xi;function vh(){if(Xi)return Yn;Xi=1;const t=Qt();return Yn=(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"},Yn}var Qn,eo;function wh(){if(eo)return Qn;eo=1;const t=xe();return Qn=(r,n)=>new t(r,n).major,Qn}var Xn,to;function bh(){if(to)return Xn;to=1;const t=xe();return Xn=(r,n)=>new t(r,n).minor,Xn}var ea,ro;function Eh(){if(ro)return ea;ro=1;const t=xe();return ea=(r,n)=>new t(r,n).patch,ea}var ta,no;function Sh(){if(no)return ta;no=1;const t=Qt();return ta=(r,n)=>{const a=t(r,n);return a&&a.prerelease.length?a.prerelease:null},ta}var ra,ao;function He(){if(ao)return ra;ao=1;const t=xe();return ra=(r,n,a)=>new t(r,a).compare(new t(n,a)),ra}var na,so;function Th(){if(so)return na;so=1;const t=He();return na=(r,n,a)=>t(n,r,a),na}var aa,io;function xh(){if(io)return aa;io=1;const t=He();return aa=(r,n)=>t(r,n,!0),aa}var sa,oo;function js(){if(oo)return sa;oo=1;const t=xe();return sa=(r,n,a)=>{const s=new t(r,a),i=new t(n,a);return s.compare(i)||s.compareBuild(i)},sa}var ia,co;function Ih(){if(co)return ia;co=1;const t=js();return ia=(r,n)=>r.sort((a,s)=>t(a,s,n)),ia}var oa,uo;function Ah(){if(uo)return oa;uo=1;const t=js();return oa=(r,n)=>r.sort((a,s)=>t(s,a,n)),oa}var ca,lo;function Sn(){if(lo)return ca;lo=1;const t=He();return ca=(r,n,a)=>t(r,n,a)>0,ca}var ua,fo;function Ds(){if(fo)return ua;fo=1;const t=He();return ua=(r,n,a)=>t(r,n,a)<0,ua}var la,ho;function du(){if(ho)return la;ho=1;const t=He();return la=(r,n,a)=>t(r,n,a)===0,la}var da,po;function fu(){if(po)return da;po=1;const t=He();return da=(r,n,a)=>t(r,n,a)!==0,da}var fa,mo;function Us(){if(mo)return fa;mo=1;const t=He();return fa=(r,n,a)=>t(r,n,a)>=0,fa}var ha,go;function Fs(){if(go)return ha;go=1;const t=He();return ha=(r,n,a)=>t(r,n,a)<=0,ha}var pa,_o;function hu(){if(_o)return pa;_o=1;const t=du(),e=fu(),r=Sn(),n=Us(),a=Ds(),s=Fs();return pa=(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}`)}},pa}var ma,yo;function $h(){if(yo)return ma;yo=1;const t=xe(),e=Qt(),{safeRe:r,t:n}=Rr();return ma=(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)},ma}var ga,vo;function Oh(){if(vo)return ga;vo=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 ga=t,ga}var _a,wo;function Ze(){if(wo)return _a;wo=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(z=>!m(z[0])),this.set.length===0)this.set=[P];else if(this.set.length>1){for(const z of this.set)if(z.length===1&&g(z[0])){this.set=[z];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,z=n.get(P);if(z)return z;const M=this.options.loose,H=M?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));M&&(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=>_(P,F)&&E.set.some(z=>_(z,F)&&P.every(M=>z.every(H=>M.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}}_a=e;const r=Oh(),n=new r,a=Ls(),s=Tn(),i=En(),o=xe(),{safeRe:c,t:u,comparatorTrimReplace:l,tildeTrimReplace:d,caretTrimReplace:f}=Rr(),{FLAG_INCLUDE_PRERELEASE:h,FLAG_LOOSE:p}=bn(),m=A=>A.value==="<0.0.0-0",g=A=>A.value==="",_=(A,E)=>{let F=!0;const P=A.slice();let z=P.pop();for(;F&&P.length;)F=P.every(M=>z.intersects(M,E)),z=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),y=A=>!A||A.toLowerCase()==="x"||A==="*",S=(A,E)=>A.trim().split(/\s+/).map(F=>O(F,E)).join(" "),O=(A,E)=>{const F=E.loose?c[u.TILDELOOSE]:c[u.TILDE];return A.replace(F,(P,z,M,H,X)=>{i("tilde",A,P,z,M,H,X);let Y;return y(z)?Y="":y(M)?Y=`>=${z}.0.0 <${+z+1}.0.0-0`:y(H)?Y=`>=${z}.${M}.0 <${z}.${+M+1}.0-0`:X?(i("replaceTilde pr",X),Y=`>=${z}.${M}.${H}-${X} <${z}.${+M+1}.0-0`):Y=`>=${z}.${M}.${H} <${z}.${+M+1}.0-0`,i("tilde return",Y),Y})},U=(A,E)=>A.trim().split(/\s+/).map(F=>B(F,E)).join(" "),B=(A,E)=>{i("caret",A,E);const F=E.loose?c[u.CARETLOOSE]:c[u.CARET],P=E.includePrerelease?"-0":"";return A.replace(F,(z,M,H,X,Y)=>{i("caret",A,z,M,H,X,Y);let se;return y(M)?se="":y(H)?se=`>=${M}.0.0${P} <${+M+1}.0.0-0`:y(X)?M==="0"?se=`>=${M}.${H}.0${P} <${M}.${+H+1}.0-0`:se=`>=${M}.${H}.0${P} <${+M+1}.0.0-0`:Y?(i("replaceCaret pr",Y),M==="0"?H==="0"?se=`>=${M}.${H}.${X}-${Y} <${M}.${H}.${+X+1}-0`:se=`>=${M}.${H}.${X}-${Y} <${M}.${+H+1}.0-0`:se=`>=${M}.${H}.${X}-${Y} <${+M+1}.0.0-0`):(i("no pr"),M==="0"?H==="0"?se=`>=${M}.${H}.${X}${P} <${M}.${H}.${+X+1}-0`:se=`>=${M}.${H}.${X}${P} <${M}.${+H+1}.0-0`:se=`>=${M}.${H}.${X} <${+M+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,z,M,H,X,Y)=>{i("xRange",A,P,z,M,H,X,Y);const se=y(M),pe=se||y(H),ne=pe||y(X),Ve=ne;return z==="="&&Ve&&(z=""),Y=E.includePrerelease?"-0":"",se?z===">"||z==="<"?P="<0.0.0-0":P="*":z&&Ve?(pe&&(H=0),X=0,z===">"?(z=">=",pe?(M=+M+1,H=0,X=0):(H=+H+1,X=0)):z==="<="&&(z="<",pe?M=+M+1:H=+H+1),z==="<"&&(Y="-0"),P=`${z+M}.${H}.${X}${Y}`):pe?P=`>=${M}.0.0${Y} <${+M+1}.0.0-0`:ne&&(P=`>=${M}.${H}.0${Y} <${M}.${+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,z,M,H,X,Y,se,pe,ne,Ve)=>(y(P)?F="":y(z)?F=`>=${P}.0.0${A?"-0":""}`:y(M)?F=`>=${P}.${z}.0${A?"-0":""}`:H?F=`>=${F}`:F=`>=${F}${A?"-0":""}`,y(se)?Y="":y(pe)?Y=`<${+se+1}.0.0-0`:y(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 z=A[P].semver;if(z.major===E.major&&z.minor===E.minor&&z.patch===E.patch)return!0}return!1}return!0};return _a}var ya,bo;function Tn(){if(bo)return ya;bo=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(">")))}}ya=e;const r=Ls(),{safeRe:n,t:a}=Rr(),s=hu(),i=En(),o=xe(),c=Ze();return ya}var va,Eo;function xn(){if(Eo)return va;Eo=1;const t=Ze();return va=(r,n,a)=>{try{n=new t(n,a)}catch{return!1}return n.test(r)},va}var wa,So;function Rh(){if(So)return wa;So=1;const t=Ze();return wa=(r,n)=>new t(r,n).set.map(a=>a.map(s=>s.value).join(" ").trim().split(" ")),wa}var ba,To;function kh(){if(To)return ba;To=1;const t=xe(),e=Ze();return ba=(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},ba}var Ea,xo;function Ch(){if(xo)return Ea;xo=1;const t=xe(),e=Ze();return Ea=(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},Ea}var Sa,Io;function Nh(){if(Io)return Sa;Io=1;const t=xe(),e=Ze(),r=Sn();return Sa=(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},Sa}var Ta,Ao;function Ph(){if(Ao)return Ta;Ao=1;const t=Ze();return Ta=(r,n)=>{try{return new t(r,n).range||"*"}catch{return null}},Ta}var xa,$o;function zs(){if($o)return xa;$o=1;const t=xe(),e=Tn(),{ANY:r}=e,n=Ze(),a=xn(),s=Sn(),i=Ds(),o=Fs(),c=Us();return xa=(l,d,f,h)=>{l=new t(l,h),d=new n(d,h);let p,m,g,_,v;switch(f){case">":p=s,m=o,g=i,_=">",v=">=";break;case"<":p=i,m=c,g=s,_="<",v="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(a(l,d,h))return!1;for(let y=0;y<d.set.length;++y){const S=d.set[y];let O=null,U=null;if(S.forEach(B=>{B.semver===r&&(B=new e(">=0.0.0")),O=O||B,U=U||B,p(B.semver,O.semver,h)?O=B:g(B.semver,U.semver,h)&&(U=B)}),O.operator===_||O.operator===v||(!U.operator||U.operator===_)&&m(l,U.semver))return!1;if(U.operator===v&&g(l,U.semver))return!1}return!0},xa}var Ia,Oo;function Mh(){if(Oo)return Ia;Oo=1;const t=zs();return Ia=(r,n,a)=>t(r,n,">",a),Ia}var Aa,Ro;function Lh(){if(Ro)return Aa;Ro=1;const t=zs();return Aa=(r,n,a)=>t(r,n,"<",a),Aa}var $a,ko;function jh(){if(ko)return $a;ko=1;const t=Ze();return $a=(r,n,a)=>(r=new t(r,a),n=new t(n,a),r.intersects(n,a)),$a}var Oa,Co;function Dh(){if(Co)return Oa;Co=1;const t=xn(),e=He();return Oa=(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},Oa}var Ra,No;function Uh(){if(No)return Ra;No=1;const t=Ze(),e=Tn(),{ANY:r}=e,n=xn(),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 _=c(m,g,h);if(p=p||_!==null,_)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 _;if(m&&g){if(_=a(m.semver,g.semver,h),_>0)return null;if(_===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,y,S,O,U=g&&!h.includePrerelease&&g.semver.prerelease.length?g.semver:!1,B=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(O=O||I.operator===">"||I.operator===">=",S=S||I.operator==="<"||I.operator==="<=",m){if(B&&I.semver.prerelease&&I.semver.prerelease.length&&I.semver.major===B.major&&I.semver.minor===B.minor&&I.semver.patch===B.patch&&(B=!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(y=l(g,I,h),y===I&&y!==g)return!1}else if(g.operator==="<="&&!n(g.semver,String(I),h))return!1}if(!I.operator&&(g||m)&&_!==0)return!1}return!(m&&S&&!g&&_!==0||g&&O&&!m&&_!==0||B||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 Ra=s,Ra}var ka,Po;function Fh(){if(Po)return ka;Po=1;const t=Rr(),e=bn(),r=xe(),n=lu(),a=Qt(),s=gh(),i=_h(),o=yh(),c=vh(),u=wh(),l=bh(),d=Eh(),f=Sh(),h=He(),p=Th(),m=xh(),g=js(),_=Ih(),v=Ah(),y=Sn(),S=Ds(),O=du(),U=fu(),B=Us(),I=Fs(),oe=hu(),he=$h(),we=Tn(),je=Ze(),jt=xn(),A=Rh(),E=kh(),F=Ch(),P=Nh(),z=Ph(),M=zs(),H=Mh(),X=Lh(),Y=jh(),se=Dh(),pe=Uh();return ka={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:_,rsort:v,gt:y,lt:S,eq:O,neq:U,gte:B,lte:I,cmp:oe,coerce:he,Comparator:we,Range:je,satisfies:jt,toComparators:A,maxSatisfying:E,minSatisfying:F,minVersion:P,validRange:z,outside:M,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},ka}Fh();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 zh 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}}class Bh extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}}function Mo(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithNotFoundError"}async function L(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===404)throw new Bh(a);if(t.status===409)throw new zh(a);const s=new Error(a);throw s.status=t.status,s}const pu="ERR_CONFLICTING_ENDPOINTS";class qh 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:pu}),this.name="ConflictingEndpointsError"}}function Gh(t){return typeof t=="object"&&t!==null&&t.code===pu}var Lo="[...]",Hh={result:"[Circular]"},on=[],Ft=[];const Zh=new TextEncoder;function Vh(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Hr(t){return Zh.encode(t)}function mu(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 Wh(t){return function(e,r){return mu(r)}}function Ne(t,e,r,n,a){try{const s=JSON.stringify(t,Wh(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]");Oe("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=Vh()),Xa(t,"",0,[],void 0,0,a);let i;try{Ft.length===0?i=JSON.stringify(t,r,n):i=JSON.stringify(t,Jh(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 Ca(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 Xa(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){Ca(Hh,t,e,a);return}if(typeof i.depthLimit<"u"&&s>i.depthLimit){Ca(Lo,t,e,a);return}if(typeof i.edgesLimit<"u"&&r+1>i.edgesLimit){Ca(Lo,t,e,a);return}if(n.push(t),Array.isArray(t))for(o=0;o<t.length;o++)Xa(t[o],o,o,n,t,s,i);else{t=mu(t);var c=Object.keys(t);for(o=0;o<c.length;o++){var u=c[o];Xa(t[u],u,o,n,t,s,i)}}n.pop()}}function Jh(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 jo(t,e,r){if(r)return t;const n=iu(),a=e??ou(),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 Kh=t=>{const e=t?.toString()??Oe("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},Yh=t=>{const r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};async function Qh(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 Xh=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 Do(t){return typeof t=="number"?Number(t.toFixed(4)):t}const ep=24*1024*1024,gu=1024*1024*1024,tp=1e4,rp=100,Uo="https://api.smith.langchain.com";class np{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??gu}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||Of(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,"_cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_multipartDisabled",{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=Kh(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??Oe("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new Fi({...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??gu;this.batchIngestCaller=new Fi({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:n,...e.callerOptions??{},onFailedResponseHook:Xh,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 np(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,cu()&&(this.langSmithToOTELTranslator=new Qf),this.cachedLSEnvVarsForMetadata=ou(),e.cache===!0?this._cache=new Mf:e.cache&&typeof e.cache=="object"?this._cache=e.cache:this._cache=void 0}static getDefaultClientConfig(){const e=Oe("API_KEY"),r=Oe("ENDPOINT")??Uo,n=Oe("HIDE_INPUTS")==="true",a=Oe("HIDE_OUTPUTS")==="true";return{apiUrl:r,apiKey:e,webUrl:void 0,hideInputs:n,hideOutputs:a}}getHostUrl(){return this.webUrl?this.webUrl:Yh(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/${nu}`};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 L(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 L(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 L(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??ep}async _getBatchSizeLimit(){const e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??rp}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(o=>o.action==="create").map(o=>o.item),runUpdates:e.filter(o=>o.action==="update").map(o=>o.item)},s=await this._ensureServerInfo();if(!this._multipartDisabled&&(s?.batch_ingest_config?.use_multipart_endpoint??!0)){const o=s?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(a,{...r,useGzip:o,sizeBytes:n})}catch(c){if(Mo(c))this._multipartDisabled=!0,await this.batchIngestRuns(a,{...r,sizeBytes:n});else throw c}}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=jo(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(tp),...this.fetchOptions});return await L(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=uu(),r=Wf();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=jo(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 L(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 L(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:_,error:v,serialized:y,attachments:S,...O}=h,U={inputs:p,outputs:m,events:g,extra:_,error:v,serialized:y},B=Ne(O,`Serializing for multipart ingestion of run with id: ${O.id}`);l.push({name:`${d}.${O.id}`,payload:new Blob([B],{type:`application/json; length=${B.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: ${O.id}`);l.push({name:`${d}.${O.id}.${I}`,payload:new Blob([he],{type:`application/json; length=${he.length}`})})}if(O.id!==void 0){const I=a[O.id];if(I){delete a[O.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 ${O.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${O.id}.${oe}`,payload:new Blob([je],{type:`${we}; length=${je.byteLength}`})})}}}u.push(`trace=${O.trace_id},id=${O.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=$f(),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 L(h,"Failed to send multipart request",!0),h});try{let u,l=!1;!s&&!this.multipartStreamingDisabled&&su()!=="bun"?(l=!0,u=await c(o)):u=await c(i),(!this.multipartStreamingDisabled||l)&&u.status===422&&(n?.apiUrl??this.apiUrl)!==Uo&&(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){if(Mo(u))throw 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 L(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:Oe("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 Qh(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:_,select:v,order:y}=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 O=["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:_,trace:s,select:v||O,is_root:u,order:y};U.select.includes("child_run_ids")&&ru("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let B=0;for await(const I of this._getCursorPaginatedList("/runs/query",U))if(_){if(B>=_)break;if(I.length+B>_){yield*I.slice(0,_-B);break}B+=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,B])=>B!==void 0)),_=JSON.stringify(g),y=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:_});return await L(U,`Failed to fetch ${h}`),U})).json(),{groups:S,total:O}=y;if(S.length===0)break;for(const U of S)yield U;if(f+=S.length,f>=O)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 _=i||[];s&&(_=[...i||[],...await Promise.all(s.map(B=>this.readProject({projectName:B}).then(I=>I.id)))]);const y=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:a,session:_,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(([B,I])=>I!==void 0)),S=JSON.stringify(y);return await(await this.caller.call(async()=>{const B=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 L(B,"get run stats"),B})).json()}async shareRun(e,{shareId:r}={}){const n={run_id:e,share_token:r||xt()};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 L(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 L(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 L(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 L(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 L(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 L(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 L(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 L(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 L(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 L(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 L(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 L(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 L(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 L(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 L(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 L(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 L(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 L(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 L(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 L(u,"fetch similar examples"),u})).json()).examples}async createExample(e,r,n){if(Fo(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;Fo(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]??xt())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];const v=e;let y=v[0].dataset_id;const S=v[0].dataset_name;if(y===void 0&&S===void 0)throw new Error("Must provide either datasetName or datasetId");if(y!==void 0&&S!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");y===void 0&&(y=(await this.readDataset({datasetName:S})).id);const O=await this._uploadExamplesMultipart(y,v);return await Promise.all(O.example_ids.map(B=>this.readExample(B)))}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,y)=>({dataset_id:h,inputs:v,outputs:n?.[y],metadata:a?.[y],split:s?.[y],id:l?.[y],attachments:u?.[y],source_run_id:i?.[y],use_source_run_io:o?.[y],use_source_run_attachments:c?.[y]})),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=>zi(i)?Bi(i):i),s=zi(r)?Bi(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 _ of n)h.append("id",_);if(s!==void 0)for(const _ of s)h.append("splits",_);if(o!==void 0){const _=JSON.stringify(o);h.append("metadata",_)}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(_=>h.append("select",_));let g=0;for await(const _ of this._getPaginated("/examples",h)){for(const v of _){const{attachment_urls:y,...S}=v,O=S;y&&(O.attachments=Object.entries(y).reduce((U,[B,I])=>(U[B.slice(11)]={presigned_url:I.presigned_url,mime_type:I.mime_type||void 0},U),{})),yield O,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 L(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 L(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 L(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 L(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 L(u,"update dataset splits",!0),u})}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??xt(),run_id:e,key:r,score:Do(n),value:a,correction:s,comment:i,feedback_source:p,comparative_experiment_id:h,feedbackConfig:d,session_id:f},g=JSON.stringify(m),_=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const v=await this._fetch(_,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:g});return await L(v,"create feedback",!0),v}),m}async updateFeedback(e,{score:r,value:n,correction:a,comment:s}){const i={};r!=null&&(i.score=Do(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 L(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 L(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 L(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 L(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||xt(),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 L(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 L(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 L(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 L(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 L(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 L(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 L(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 L(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 L(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 L(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 L(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 L(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 L(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 L(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??xt()).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 L(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 L(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 L(i,"delete prompt"),i})).json()}_getPromptCacheKey(e,r){return`${e}${r?":with_model":""}`}async _fetchPromptFromApi(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 L(c,"pull prompt commit"),c})).json();return{owner:n,repo:a,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async pullPromptCommit(e,r){if(!r?.skipCache&&this._cache){const n=this._getPromptCacheKey(e,r?.includeModel),a=this._cache.get(n);if(a)return a;const s=await this._fetchPromptFromApi(e,r);return this._cache.set(n,s),s}return this._fetchPromptFromApi(e,r)}async _pullPrompt(e,r){const n=await this.pullPromptCommit(e,{includeModel:r?.includeModel,skipCache:r?.skipCache});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}`)}}get cache(){return this._cache}cleanup(){this._cache&&this._cache.stop()}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 new Promise(e=>setTimeout(e,1)),await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await Jf()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function Fo(t){return"dataset_id"in t||"dataset_name"in t}const ap=t=>!!["TRACING_V2","TRACING"].find(r=>Oe(r)==="true"),yt=Symbol.for("lc:context_variables"),Na=Symbol.for("langsmith:replica_trace_roots");function zo(t,e){if(yt in t)return t[yt][e]}function sp(t,e,r){const n=yt in t?t[yt]:{};n[e]=r,t[yt]=n}const sr="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function Bo(t){const r=Object.keys(t).sort().map(n=>`${n}:${t[n]??""}`).join("|");return ar(r,sr)}function ip(t){return t.replace(/[-:.]/g,"")}function _u(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 yu(t,e,r=1){const n=_u(t,r);return{dottedOrder:ip(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}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),op(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=_u(this.start_time,this.execution_order)),this.id||(this.id=kf(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=dp(this.replicas),!this.dotted_order){const{dottedOrder:o}=yu(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:tu(),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});yt in this&&(s[yt]=this[yt]);const i=Symbol.for("lc:child_config"),o=e.extra?.[i]??this.extra[i];if(up(o)){const l={...o},d=cp(l.callbacks)?l.callbacks.copy?.():void 0;d&&(Object.assign(d,{_parentRunId:s.id}),d.handlers?.find(vu)?.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=zo(this,Na)??{};n[e]=r,sp(this,Na,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 _=Bo({projectName:r,apiUrl:o,apiKey:c,workspaceId:u});this._setReplicaTraceRoot(_,l.id)}let d;if(!s){const _=zo(this,Na)??{},v=Bo({projectName:r,apiUrl:o,apiKey:c,workspaceId:u});if(d=_[v],d&&(l.trace_id=d,l.dotted_order)){const y=l.dotted_order.split(".");let S=null;for(let O=0;O<y.length;O++)if(y[O].slice(-36)===d){S=O;break}if(S!==null){const O=y.slice(S);l.dotted_order=O.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(y=>{const S=y.slice(-36),O=ar(`${S}:${r}`,sr);return y.slice(0,-36)+O}).join(".")),{...l,id:h,trace_id:p,parent_run_id:m,dotted_order:g,session_name:r}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{const r=iu();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){ru("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)}this.child_runs=[]}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)}this.child_runs=[]}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=ap();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 op(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}function vu(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}function qo(t){return Array.isArray(t)&&t.some(e=>vu(e))}function cp(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}function up(t){const e=t?.callbacks;return t!=null&&typeof e=="object"&&(qo(e?.handlers)||qo(e))}function lp(){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){fp(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(Gh(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 dp(t){return t?t.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):lp()}function fp(t){if(Object.keys(t).length>0&&Oe("ENDPOINT"))throw new qh}var hp={};ge(hp,{BaseTracer:()=>Xt,isBaseTracer:()=>Ut});const pp=t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t};function es(t,e){if(t)return new $e({...t,start_time:t._serialized_start_time??t.start_time,parent_run:es(e),child_runs:t.child_runs.map(r=>es(r)).filter(r=>r!==void 0),extra:{...t.extra,runtime:Yc()},tracingEnabled:!1})}function Pa(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 Or{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(t){super(...arguments)}copy(){return this}getRunById(t){if(t!==void 0)return this.usesRunTreeMap?pp(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}=yu(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=es(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,c){const u=this._getExecutionOrder(n),l=Date.now(),d={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:e,execution_order:u,child_execution_order:u,run_type:i??"chain",child_runs:[],extra:s?{...c,metadata:s}:{...c},tags:a||[]};return this._addRunToRunMap(d)}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=Pa(t,"output"),s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),a?.inputs!==void 0&&(s.inputs=Pa(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=Pa(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 Go;function mp(){return Go||(Go=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 gp=mp();const wu=gn(gp);var _p={};ge(_p,{ConsoleCallbackHandler:()=>ts});function Ee(t,e){return`${t.open}${e}${t.close}`}function Me(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}function Ho(t){return typeof t=="string"?t.trim():t==null?t:Me(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}=wu;var ts=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(wu.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: ${Me(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: ${Me(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: ${Me(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: ${Me(r,"[inputs]")}`)}onLLMEnd(t){const e=this.getBreadcrumbs(t);console.log(`${Ee(Ae.cyan,"[llm/end]")} [${e}] [${ht(t)}] Exiting LLM run with output: ${Me(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: ${Me(t.error,"[error]")}`)}onToolStart(t){const e=this.getBreadcrumbs(t);console.log(`${Ee(Ae.green,"[tool/start]")} [${e}] Entering Tool run with input: "${Ho(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: "${Ho(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: ${Me(t.error,"[error]")}`)}onRetrieverStart(t){const e=this.getBreadcrumbs(t);console.log(`${Ee(Ae.green,"[retriever/start]")} [${e}] Entering Retriever run with input: ${Me(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: ${Me(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: ${Me(t.error,"[error]")}`)}onAgentAction(t){const e=t,r=this.getBreadcrumbs(t);console.log(`${Ee(Ae.blue,"[agent/action]")} [${r}] Agent selected action: ${Me(e.actions[e.actions.length-1],"[action]")}`)}};let Ma;const bu=()=>{if(Ma===void 0){const t=At("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};Ma=new wr(t)}return Ma};let yp=class{getStore(){}run(e,r){return r()}};const La=Symbol.for("ls:tracing_async_local_storage"),vp=new yp;let wp=class{getInstance(){return globalThis[La]??vp}initializeGlobalInstance(e){globalThis[La]===void 0&&(globalThis[La]=e)}};const bp=new wp;function Ep(t=!1){const e=bp.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 Sp={};ge(Sp,{LangChainTracer:()=>Yr});function Tp(t){let e;for(const r of t)for(const n of r)wt.isInstance(n.message)&&n.message.usage_metadata!==void 0&&(e=yn(e,n.message.usage_metadata));return e}var Yr=class Eu 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??tu(),this.replicas=s,this.exampleId=r,this.client=a??bu();const i=Eu.getTraceableRunTree();i&&this.updateFromRunTree(i)}async persistRun(e){}async onRunCreate(e){e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){const r=this.getRunTreeWithTracingConfig(e.id);e.extra?.lc_defers_inputs?await r?.postRun():await r?.patchRun()}onLLMEnd(e){const r=e.outputs;if(r?.generations){const n=Tp(r.generations);if(n!==void 0){e.extra=e.extra??{};const a=e.extra.metadata??{};a.usage_metadata=n,e.extra.metadata=a}}}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 Ep(!0)}catch{return}}};let $t;function xp(){const t="default"in st?st.default:st;return new t({autoStart:!0,concurrency:1})}function Ip(){return typeof $t>"u"&&($t=xp()),$t}async function fe(t,e){if(e===!0){const r=vr();r!==void 0?await r.run(void 0,async()=>t()):await t()}else $t=Ip(),$t.add(async()=>{const r=vr();r!==void 0?await r.run(void 0,async()=>t()):await t()})}async function Ap(){const t=bu();await Promise.allSettled([typeof $t<"u"?$t.onIdle():Promise.resolve(),t.awaitPendingTraceBatches()])}var $p={};ge($p,{awaitAllCallbacks:()=>Ap,consumeCallback:()=>fe});const Op=t=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(r=>At(r)==="true");function Su(t){const e=vr();return e===void 0?void 0:e.getStore()?.[ur]?.[t]}const Rp=Symbol("lc:configure_hooks"),kp=()=>Su(Rp)||[];var Cp={};ge(Cp,{BaseCallbackManager:()=>Tu,BaseRunManager:()=>kr,CallbackManager:()=>Mt,CallbackManagerForChainRun:()=>Iu,CallbackManagerForLLMRun:()=>rs,CallbackManagerForRetrieverRun:()=>xu,CallbackManagerForToolRun:()=>Au,ensureHandler:()=>br,parseCallbackConfigArg:()=>Np});function Np(t){return t?Array.isArray(t)||"name"in t?{callbacks:t}:t:{}}var Tu=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)))}},xu=class extends kr{getChild(t){const e=new Mt(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)))}},rs=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)))}},Iu=class extends kr{getChild(t){const e=new Mt(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)))}},Au=class extends kr{getChild(t){const e=new Mt(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)))}},Mt=class ir extends Tu{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 rs(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=ks(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 rs(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,c=void 0,u=void 0){return await Promise.all(this.handlers.map(l=>{if(!l.ignoreChain)return Ut(l)&&l._createRunForChainStart(e,r,n,this._parentRunId,this.tags,this.metadata,a,o,u),fe(async()=>{try{await l.handleChainStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,a,o,u)}catch(d){if((l.raiseError?console.error:console.warn)(`Error in handler ${l.constructor.name}, handleChainStart: ${d}`),l.raiseError)throw d}},l.awaitHandlers)})),new Iu(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 Au(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 xu(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 Or{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=At("LANGCHAIN_VERBOSE")==="true"||o?.verbose,l=Yr.getTraceableRunTree()?.tracingEnabled||Op(),d=l||(At("LANGCHAIN_TRACING")??!1);if(u||d){if(c||(c=new ir),u&&!c.handlers.some(f=>f.name===ts.prototype.name)){const f=new ts;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 kp()){const g=m&&At(m)==="true"&&p;let _;const v=f!==void 0?Su(f):void 0;v&&Xc(v)?_=v:g&&(_=new p({})),_!==void 0&&(c||(c=new ir),c.handlers.some(y=>y.name===_.name)||c.addHandler(_,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:Or.fromMethods(t)}var $u=class{getStore(){}run(t,e){return e()}enterWith(t){}};const Pp=new $u,Zo=Symbol.for("lc:child_config");var Mp=class{getInstance(){return vr()??Pp}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[Zo]}runWithConfig(t,e,r){const n=Mt._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,[Zo]: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&&Ld(t)}};const lt=new Mp;var Lp={};ge(Lp,{AsyncLocalStorageProviderSingleton:()=>lt,MockAsyncLocalStorage:()=>$u,_CONTEXT_VARIABLES_KEY:()=>ur});const ja=25;async function qe(t){return Mt._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata)}function Vo(...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 Mt(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 jp=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))jp.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 bt(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 Dp={};ge(Dp,{AsyncGeneratorWithSetup:()=>Lt,IterableReadableStream:()=>Ge,atee:()=>qs,concat:()=>Gs,pipeGeneratorWithSetup:()=>Ou});var Ge=class ns 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 ns({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 ns({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 qs(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 Gs(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]=Gs(r[n],a):r[n]=a;return r}else throw new Error(`Cannot concat ${typeof t} and ${typeof e}`)}var Lt=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()=>bt(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 Ou(t,e,r,n,...a){const s=new Lt({generator:e,startSetup:r,signal:n}),i=await s.setup;return{output:t(s,i,...a),setup:i}}const Up=Object.prototype.hasOwnProperty;function Fp(t,e){return Up.call(t,e)}function zp(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)Fp(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 as(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 S_(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function Bp(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function ss(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(ss(t[r]))return!0}else if(typeof t=="object"){const r=zp(t),n=r.length;for(var e=0;e<n;e++)if(ss(t[r[e]]))return!0}}return!1}function Wo(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 qp=class extends Error{constructor(t,e,r,n,a){super(Wo(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=Wo(t,{name:e,index:r,operation:n,tree:a})}},Ru={};ge(Ru,{JsonPatchError:()=>ue,_areEquals:()=>Sr,applyOperation:()=>Ot,applyPatch:()=>Er,applyReducer:()=>Zp,deepClone:()=>Gp,getValueByPointer:()=>ln,validate:()=>ku,validator:()=>dn});const ue=qp,Gp=kt;function Da(t){return Object.getOwnPropertyNames(Object.prototype).includes(t)}const zt={add:function(t,e,r){if(Da(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(Da(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(Da(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=Ot(r,{op:"remove",path:this.from}).removed;return Ot(r,{op:"add",path:this.path,value:a}),{newDocument:r,removed:n}},copy:function(t,e,r){const n=ln(r,this.from);return Ot(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 Hp={add:function(t,e,r){return as(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:zt.move,copy:zt.copy,test:zt.test,_get:zt._get};function ln(t,e){if(e=="")return t;var r={op:"_get",path:e};return Ot(t,r),r.value}function Ot(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=Bp(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&&!as(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);as(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=Hp[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=zt[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]=Ot(t,e[i],r,!0,a,i),t=s[i].newDocument;return s.newDocument=t,s}function Zp(t,e,r){const n=Ot(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(zt[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")&&ss(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=ku([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 ku(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}({...Ru});var Vp={};ge(Vp,{LogStreamCallbackHandler:()=>os,RunLog:()=>Hs,RunLogPatch:()=>rt,isLogStreamHandler:()=>Cu});var rt=class{ops;constructor(t){this.ops=t.ops??[]}concat(t){const e=this.ops.concat(t.ops),r=Er({},e);return new Hs({ops:e,state:r[r.length-1].newDocument})}},Hs=class is 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 is({ops:r,state:n[n.length-1].newDocument})}static fromRunLogPatch(e){const r=Er({},e.ops);return new is({ops:e.ops,state:r[r.length-1].newDocument})}};const Cu=t=>t.name==="log_stream_tracer";async function Jo(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 Ko(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 Wp(t){return t!==void 0&&t.message!==void 0}var os=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 Jo(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 Jo(t,this._schemaFormat)}),r.push({op:"add",path:`/logs/${e}/final_output`,value:await Ko(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 Ko(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?Wp(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)}},Jp={};ge(Jp,{ChatGenerationChunk:()=>Yp,GenerationChunk:()=>fn,RUN_KEY:()=>Kp});const Kp="__run";var fn=class Nu{text;generationInfo;constructor(e){this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new Nu({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}},Yp=class Pu extends fn{message;constructor(e){super(e),this.message=e.message}concat(e){return new Pu({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 Qp=t=>t.name==="event_stream_tracer";var Xp=class extends Xt{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;readableStreamClosed=!1;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({flush:()=>{this.readableStreamClosed=!0}}),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.readableStreamClosed||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 em=Object.prototype.toString,tm=t=>em.call(t)==="[object Error]",rm=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 nm(t){if(!(t&&tm(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:rm.has(r)}function am(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 sm=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 im(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 Yo(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}async function om({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 sm)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),Yo(n,o)<=0)throw s;const u=await a.shouldConsumeRetry(c),l=Yo(n,o);if(l<=0||i<=0)throw s;if(s instanceof TypeError&&!nm(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=im(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 cs(t,e={}){if(e={...e},am(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 om({error:s,attemptNumber:r,retriesConsumed:n,startTime:a,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var cm={};ge(cm,{AsyncCaller:()=>Mu});const um=[400,401,402,403,404,405,406,407,409],lm=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&&um.includes(+e))throw t;if(t?.error?.code==="insufficient_quota"){const r=new Error(t?.message);throw r.name="InsufficientQuotaError",r}};var Mu=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(t){this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,this.onFailedAttempt=t.onFailedAttempt??lm;const e="default"in st?st.default:st;this.queue=new e({concurrency:this.maxConcurrency})}async call(t,...e){return this.queue.add(()=>cs(()=>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)))}},Lu=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 Zs(t){return t?t.lc_runnable:!1}var dm=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 fm=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 _e(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 T_(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."),_e(t)}function ju(t){return!t||typeof t!="object"||Array.isArray(t)?!1:!!(le(t)||_e(t))}function hm(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 pm(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 x_(t){return!!(hm(t)||pm(t))}async function I_(t,e){if(le(t))try{return{success:!0,data:await fc(t,e)}}catch(r){return{success:!1,error:r}}if(_e(t))return await t.safeParseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function mm(t,e){if(le(t))return await fc(t,e);if(_e(t))return await t.parseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function A_(t,e){if(le(t))try{return{success:!0,data:fs(t,e)}}catch(r){return{success:!1,error:r}}if(_e(t))return t.safeParse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function $_(t,e){if(le(t))return fs(t,e);if(_e(t))return t.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function gm(t){if(le(t))return Pe.get(t)?.description;if(_e(t)||"description"in t&&typeof t.description=="string")return t.description}function O_(t){if(!ju(t))return!1;if(_e(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 _m(t){return ju(t)?_e(t)?t._def.typeName==="ZodString":le(t)?t._zod.def.type==="string":!1:!1}function Du(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 Vs(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 ym(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 vm(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 R_(t){return!!(Du(t)||it(t))}function Qo(t){if(_e(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 k_(t,e){if(_e(t))return t.extend(e);if(le(t))return fl(t,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function C_(t){if(_e(t))return t.partial();if(le(t))return hl(hc,t,void 0);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function us(t,e=!1){if(_e(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=us(i,e);r[s]=c}else if(Vs(i)){let c=i._zod.def.element;it(c)&&(c=us(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 Xo(t,e=!1){if(Du(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=Xo(i,e);r[s]=c}else if(Vs(i)){let c=i._zod.def.element;it(c)&&(c=Xo(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:pl(ml)}),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 N_(t){if(_e(t))try{const e=t.parse(void 0);return()=>e}catch{return}if(le(t))try{const e=fs(t,void 0);return()=>e}catch{return}}function wm(t){return _e(t)&&"typeName"in t._def&&t._def.typeName==="ZodEffects"}function bm(t){return le(t)&&t._zod.def.type==="pipe"}function Tt(t,e,r){const n=r.get(t);if(n!==void 0)return n;if(_e(t))return wm(t)?Tt(t._def.schema,e,r):t;if(le(t)){let a=t;if(bm(t)&&(a=Tt(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]=Tt(c,e,r);a=nt(a,{...a._zod.def,shape:i})}else if(Vs(a)){const i=Tt(a._zod.def.element,e,r);a=nt(a,{...a._zod.def,element:i})}else if(ym(a)){const i=Tt(a._zod.def.innerType,e,r);a=nt(a,{...a._zod.def,innerType:i})}else if(vm(a)){const i=Tt(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 Em(t,e=!1){return Tt(t,e,new WeakMap)}function P_(t,e){if(_e(t)){const r=Qo(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=Qo(t),n={...t._zod.def.shape};for(const[i,o]of Object.entries(r))e(i,o)&&(n[i]=new hc({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 M_(t){return t instanceof Error&&(t.constructor.name==="ZodError"||t.constructor.name==="$ZodError")}function Ua(t){return t.replace(/[^a-zA-Z-_0-9]/g,"_")}const Sm=["*","_","`"];function Tm(t){let e="";for(const[r,n]of Object.entries(t))e+=` classDef ${r} ${n};
|
|
55
|
+
`;return e}function xm(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,_]of Object.entries(t)){const v=_.name.split(":").pop()??"";let S=Sm.some(U=>v.startsWith(U)&&v.endsWith(U))?`<p>${v}</p>`:v;Object.keys(_.metadata??{}).length&&(S+=`<hr/><small><em>${Object.entries(_.metadata??{}).map(([U,B])=>`${U} = ${B}`).join(`
|
|
59
|
+
`)}</em></small>`);const O=(m[g]??m[p]).replace("{0}",Ua(g)).replace("{1}",S);u+=` ${O}
|
|
60
|
+
`}}const l={};for(const p of e){const m=p.source.split(":"),g=p.target.split(":"),_=m.filter((v,y)=>v===g[y]).join(":");l[_]||(l[_]=[]),l[_].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 _=f(Object.keys(l).filter(v=>v.startsWith(`${m}:`)&&v!==m&&v.split(":").length===m.split(":").length+1));for(const v of _)h(l[v],v);for(const v of p){const{source:y,target:S,data:O,conditional:U}=v;let B="";if(O!==void 0){let I=O;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> ")),B=U?` -. ${I} .-> `:` -- ${I} --> `}else B=U?" -.-> ":" --> ";u+=` ${Ua(y)}${B}${Ua(S)};
|
|
62
|
+
`}m&&!g&&(u+=` end
|
|
63
|
+
`)}h(l[""]??[],"");for(const p in l)!p.includes(":")&&p!==""&&h(l[p],p);return i&&(u+=Tm(s??{})),u}async function Im(t,e){let r=e?.backgroundColor??"white";const n=e?.imageType??"png",a=fm(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 Am=Symbol("Let zodToJsonSchema decide on which parser to use"),$m={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"},Om=t=>({...$m,...t}),Rm=t=>{const e=Om(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}]))}},Uu=(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"?Uu(e,t.currentPath):e.join("/")}}function Fu(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ae(t,e,r,n,a){t[e]=r,Fu(t,e,n,a)}function km(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 Cm(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 Nm(){return{type:"boolean"}}function zu(t,e){return re(t.type._def,e)}const Pm=(t,e)=>re(t.innerType._def,e);function Bu(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(a=>Bu(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 Mm(t,e)}}const Mm=(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 Lm(t,e){return{...re(t.innerType._def,e),default:t.defaultValue()}}function jm(t,e){return e.effectStrategy==="input"?re(t.schema._def,e):Ce(e)}function Dm(t){return{type:"string",enum:Array.from(t.values)}}const Um=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Fm(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(Um(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 zm(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 Fa;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:()=>(Fa===void 0&&(Fa=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Fa),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 qu(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(`^${za(n.value,e)}`),n.message,e);break;case"endsWith":Se(r,RegExp(`${za(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(za(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 za(t,e){return e.patternStrategy==="escape"?qm(t):t}const Bm=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function qm(t){let e="";for(let r=0;r<t.length;r++)Bm.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:ec(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ae(t,"pattern",ec(e,n),r,n)}function ec(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 Gu(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}=qu(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}=zu(t.keyType._def,e);return{...r,propertyNames:a}}}return r}function Gm(t,e){if(e.mapStrategy==="record")return Gu(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 Hm(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 Zm(t){return t.target==="openAi"?void 0:{not:Ce({...t,currentPath:[...t.currentPath,"not"]})}}function Vm(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const hn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Wm(t,e){if(e.target==="openApi3")return tc(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 tc(t,e)}const tc=(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 Jm(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 Km(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",Fu(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 Ym(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=Xm(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=Qm(t,e);return i!==void 0&&(n.additionalProperties=i),n}function Qm(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 Xm(t){try{return t.isOptional()}catch{return!0}}const eg=(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)},tg=(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 rg(t,e){return re(t.type._def,e)}function ng(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 ag(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 sg(t){return{not:Ce(t)}}function ig(t){return Ce(t)}const og=(t,e)=>re(t.innerType._def,e),cg=(t,e,r)=>{switch(e){case b.ZodString:return qu(t,r);case b.ZodNumber:return Km(t,r);case b.ZodObject:return Ym(t,r);case b.ZodBigInt:return Cm(t,r);case b.ZodBoolean:return Nm();case b.ZodDate:return Bu(t,r);case b.ZodUndefined:return sg(r);case b.ZodNull:return Vm(r);case b.ZodArray:return km(t,r);case b.ZodUnion:case b.ZodDiscriminatedUnion:return Wm(t,r);case b.ZodIntersection:return Fm(t,r);case b.ZodTuple:return ag(t,r);case b.ZodRecord:return Gu(t,r);case b.ZodLiteral:return zm(t,r);case b.ZodEnum:return Dm(t);case b.ZodNativeEnum:return Hm(t);case b.ZodNullable:return Jm(t,r);case b.ZodOptional:return eg(t,r);case b.ZodMap:return Gm(t,r);case b.ZodSet:return ng(t,r);case b.ZodLazy:return()=>t.getter()._def;case b.ZodPromise:return rg(t,r);case b.ZodNaN:case b.ZodNever:return Zm(r);case b.ZodEffects:return jm(t,r);case b.ZodAny:return Ce(r);case b.ZodUnknown:return ig(r);case b.ZodDefault:return Lm(t,r);case b.ZodBranded:return zu(t,r);case b.ZodReadonly:return og(t,r);case b.ZodCatch:return Pm(t,r);case b.ZodPipeline:return tg(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!==Am)return o}if(n&&!r){const o=ug(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=cg(t,t.typeName,e),i=typeof s=="function"?re(s(),e):s;if(i&&lg(t,e,i),e.postProcess){const o=e.postProcess(i,t,e);return a.jsonSchema=i,o}return a.jsonSchema=i,i}const ug=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Uu(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}},lg=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),dg=(t,e)=>{const r=Rm(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 ze(t){return encodeURI(fg(t))}function fg(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}const hg={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},pg={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},mg={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 gg=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=gg,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(mg[s])continue;const i=`${n}/${ze(s)}`,o=t[s];if(Array.isArray(o)){if(hg[s]){const c=o.length;for(let u=0;u<c;u++)gt(o[u],e,r,`${i}/${u}`)}}else if(pg[s])for(let c in o)gt(o[c],e,r,`${i}/${ze(c)}`);else gt(o,e,r,i)}return e}const _g=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,yg=[0,31,28,31,30,31,30,31,31,30,31,30,31],vg=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,wg=/^(?=.{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,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,Eg=/^(?:(?:[^\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,Sg=/^(?:(?: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,Tg=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,xg=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Ig=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Ag=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,$g=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))},Og=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Rg=/^((([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,kg=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 rc={date:Hu,time:Zu.bind(void 0,!1),"date-time":Pg,duration:kg,uri:jg,"uri-reference":Je(bg),"uri-template":Je(Eg),url:Je(Sg),email:$g,hostname:Je(wg),ipv4:Je(Og),ipv6:Je(Rg),regex:Ug,uuid:Je(Tg),"json-pointer":Je(xg),"json-pointer-uri-fragment":Je(Ig),"relative-json-pointer":Je(Ag)};function Cg(t){return t%4===0&&(t%100!==0||t%400===0)}function Hu(t){const e=t.match(_g);if(!e)return!1;const r=+e[1],n=+e[2],a=+e[3];return n>=1&&n<=12&&a>=1&&a<=(n==2&&Cg(r)?29:yg[n])}function Zu(t,e){const r=e.match(vg);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 Ng=/t|\s/i;function Pg(t){const e=t.split(Ng);return e.length==2&&Hu(e[0])&&Zu(!0,e[1])}const Mg=/\/|:/,Lg=/^(?:[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 jg(t){return Mg.test(t)&&Lg.test(t)}const Dg=/[^\\]\\Z/;function Ug(t){if(Dg.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}function Fg(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:_,not:v,anyOf:y,allOf:S,oneOf:O,if:U,then:B,else:I,format:oe,properties:he,patternProperties:we,additionalProperties:je,unevaluatedProperties:jt,minProperties:A,maxProperties:E,propertyNames:F,dependentRequired:P,dependentSchemas:z,dependencies:M,prefixItems:H,items:X,additionalItems:Y,unevaluatedItems:se,contains:pe,minContains:ne,maxContains:Ve,minItems:An,maxItems:$n,uniqueItems:cl,minimum:Et,maximum:St,exclusiveMinimum:er,exclusiveMaximum:tr,multipleOf:Nr,minLength:Pr,maxLength:Mr,pattern:Ys,__absolute_ref__:Lr,__absolute_recursive_ref__:ul}=e,$=[];if(h===!0&&s===null&&(s=e),f==="#"){const q=s===null?n[ul]: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[Lr||d];if(j===void 0){let T=`Unresolved $ref "${d}".`;throw Lr&&Lr!==d&&(T+=` Absolute URI "${Lr}".`),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(y!==void 0){const q=`${o}/anyOf`,j=$.length;let W=!1;for(let C=0;C<y.length;C++){const T=y[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(O!==void 0){const q=`${o}/oneOf`,j=$.length,W=O.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(B!==void 0){const W=ce(t,B,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(_!==void 0)for(const C of _)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}/${ze(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(z!==void 0)for(const C in z){const T=`${o}/dependentSchemas`;if(C in t){const Z=ce(t,z[C],r,n,a,s,i,`${T}/${ze(C)}`,c);Z.valid||$.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:T,error:`Instance has "${C}" but does not match dependant schema.`},...Z.errors)}}if(M!==void 0){const C=`${o}/dependencies`;for(const T in M)if(T in t){const Z=M[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}/${ze(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}/${ze(T)}`,G=ce(t[T],he[T],r,n,a,s,Z,`${C}/${ze(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 Qs=`${i}/${ze(Ie)}`,Xs=ce(t[Ie],G,r,n,a,s,Qs,`${C}/${ze(T)}`);Xs.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.`},...Xs.errors))}}}if(!W&&je!==void 0){const C=`${o}/additionalProperties`;for(const T in t){if(j[T])continue;const Z=`${i}/${ze(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}/${ze(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"){$n!==void 0&&t.length>$n&&$.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${t.length} > ${$n}).`}),An!==void 0&&t.length<An&&$.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${t.length} < ${An}).`});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(cl)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"?(Et!==void 0&&(er===!0&&t<=Et||t<Et)&&$.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${t} is less than ${er?"or equal to ":""} ${Et}.`}),St!==void 0&&(tr===!0&&t>=St||t>St)&&$.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${t} is greater than ${tr?"or equal to ":""} ${St}.`})):(Et!==void 0&&t<Et&&$.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${t} is less than ${Et}.`}),St!==void 0&&t>St&&$.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${t} is greater than ${St}.`}),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&&Mr===void 0?0:Fg(t);Pr!==void 0&&q<Pr&&$.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${q} < ${Pr}).`}),Mr!==void 0&&q>Mr&&$.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${q} > ${Mr}).`}),Ys!==void 0&&!new RegExp(Ys,"u").test(t)&&$.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),oe!==void 0&&rc[oe]&&!rc[oe](t)&&$.push({instanceLocation:i,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${oe}".`})}return{valid:$.length===0,errors:$}}class zg{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 Bg={};ge(Bg,{Validator:()=>zg,deepCompareStrict:()=>qt,toJsonSchema:()=>Vu,validatesOnlyStrings:()=>Qr});function Vu(t,e){if(le(t)){const r=Em(t,!0);if(it(r)){const n=us(r,!0);return ei(n,e)}else return ei(t,e)}return _e(t)?dg(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 qg={};ge(qg,{Graph:()=>Ws});function Gg(t,e){if(t!==void 0&&!lr(t))return t;if(Zs(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 Hg(t){return Zs(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...Vu(t.data.schema),title:t.data.name}}}var Ws=class Wu{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],...Hg(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??xt(),s={id:a,data:e,name:Gg(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 nc(this)}lastNode(){return ac(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&&nc(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&ac(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 Wu({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 xm(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 Im(r,{backgroundColor:e?.backgroundColor})}};function nc(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 ac(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 Zg(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 sc(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}const Vg=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function";function ls(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*ic(t,e){for(;;){const{value:r,done:n}=lt.runWithConfig(Jt(t),e.next.bind(e),!0);if(n)break;yield r}}async function*ds(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 Re=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 Yu({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 Kg({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 Mu({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 Lt({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 bt(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 bt(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 Gs(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 Ou(e.bind(this),l(),async()=>c?.handleChainStart(this.toJSON(),{input:""},o.runId,o.runType,void 0,void 0,o.runName??this.getName(),void 0,{lc_defers_inputs:!0}),r?.signal,o);delete o.runId,d=f.setup;const h=d?.handlers.find(Qp);let p=f.output;h!==void 0&&d!==void 0&&(p=h.tapOutputIterable(d.runId,p));const m=d?.handlers.find(Cu);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 Ws,r=e.addNode({name:`${this.getName()}Input`,schema:hi()}),n=e.addNode(this),a=e.addNode({name:`${this.getName()}Output`,schema:hi()});return e.addEdge(r,n),e.addEdge(n,a),e}pipe(t){return new Qu({first:this,last:It(t)})}pick(t){return this.pipe(new Qg(t))}assign(t){return this.pipe(new Yg(new In({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 os({...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"?Zg(n):Ge.fromAsyncGenerator(n)}async*_streamEventsV2(t,e,r){const n=new Xp({...r,autoClose:!1}),a=ie(e),s=a.runId??xt();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 _ 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 os({...r,autoClose:!1,_schemaFormat:"streaming_events"}),l=new dm({...r}),d=this._streamLog(t,u,s);for await(const h of d){if(n?n=n.concat(h):n=Hs.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 _={...n.state},v={run_id:_.id,event:`on_${_.type}_start`,name:c,tags:i,metadata:o,data:{input:t}};l.includeEvent(v,_.type)&&(yield v)}const p=h.ops.filter(_=>_.path.startsWith("/logs/")).map(_=>_.path.split("/")[2]),m=[...new Set(p)];for(const _ of m){let v,y={};const S=n.state.logs[_];if(S.end_time===void 0?S.streamed_output.length>0?v="stream":v="start":v="end",v==="start")S.inputs!==void 0&&(y.input=S.inputs);else if(v==="end")S.inputs!==void 0&&(y.input=S.inputs),y.output=S.final_output;else if(v==="stream"){const O=S.streamed_output.length;if(O!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${O} instead. Encountered in: "${S.name}"`);y={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:y}}const{state:g}=n;if(g.streamed_output.length>0){const _=g.streamed_output.length;if(_!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${_} instead. Encountered in: "${g.name}"`);const v={chunk:g.streamed_output[0]};g.streamed_output=[];const y={event:`on_${g.type}_stream`,run_id:g.id,tags:i,metadata:o,name:c,data:v};l.includeEvent(y,g.type)&&(yield y)}}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 Zs(t)}withListeners({onStart:t,onEnd:e,onError:r}){return new pn({bound:this,config:{},configFactories:[n=>({callbacks:[new Lu({config:n,onStart:t,onEnd:e,onError:r})]})]})}asTool(t){return Xg(this,t)}},pn=class Ju extends Re{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=Vo(this.config,...e);return Vo(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 Yu({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&&Re.isRunnable(e.bound)}withListeners({onStart:e,onEnd:r,onError:n}){return new Ju({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[a=>({callbacks:[new Lu({config:a,onStart:e,onEnd:r,onError:n})]})]})}},L_=class Ku extends Re{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 Ku({bound:this.bound.withListeners({onStart:e,onEnd:r,onError:n})})}},Yu=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 cs(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 cs(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)}},Qu=class or extends Re{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 bt(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 bt(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 Ws;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:It(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&Re.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:It(e),middle:r.slice(0,-1).map(It),last:It(r[r.length-1])})}},In=class Xu extends Re{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]=It(n)}static from(e){return new Xu({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 bt(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=qs(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 bt(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 Lt({generator:this.transform(n(),a),config:a});return await s.setup,Ge.fromAsyncGenerator(s)}},Wg=class el extends Re{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 bt(s,n?.signal)}async*_streamIterator(e,r){const[n]=this._getOptionsList(r??{},1),a=await this.invoke(e,r);if(ls(a)){for await(const s of a)n?.signal?.throwIfAborted(),yield s;return}if(Vg(a)){for(;;){n?.signal?.throwIfAborted();const s=a.next();if(s.done)break;yield s.value}return}yield a}static from(e){return new el({func:e})}};function Jg(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 tl extends Re{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(e){if(Bs(e.func))return Wg.from(e.func);super(e),Jg(e.func),this.func=e.func}static from(e){return new tl({func:e})}async _invoke(e,r,n){return new Promise((a,s)=>{const i=be(r,{callbacks:n?.getChild(),recursionLimit:(r?.recursionLimit??ja)-1});lt.runWithConfig(Jt(i),async()=>{try{let o=await this.func(e,{...i});if(o&&Re.isRunnable(o)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(e,{...i,recursionLimit:(i.recursionLimit??ja)-1})}else if(ls(o)){let c;for await(const u of ds(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(sc(o)){let c;for(const u of ic(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??ja)-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&&Re.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(ls(i))for await(const o of ds(s,i))n?.signal?.throwIfAborted(),yield o;else if(sc(i))for(const o of ic(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 Lt({generator:this.transform(n(),a),config:a});return await s.setup,Ge.fromAsyncGenerator(s)}},j_=class extends In{},Kg=class extends Re{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=ds(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 It(t){if(typeof t=="function")return new Cr({func:t});if(Re.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){const e={};for(const[r,n]of Object.entries(t))e[r]=It(n);return new In({steps:e})}else throw new Error(`Expected a Runnable, function or object.
|
|
77
|
+
Instead got an unsupported type.`)}var Yg=class extends Re{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(t){t instanceof In&&(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]=qs(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 Lt({generator:this.transform(r(),n),config:n});return await a.setup,Ge.fromAsyncGenerator(a)}},Qg=class extends Re{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 Lt({generator:this.transform(r(),n),config:n});return await a.setup,Ge.fromAsyncGenerator(a)}},oc=class extends pn{name;description;schema;constructor(t){const e=Qu.from([Cr.from(async r=>{let n;if(Lc(r))try{n=await mm(this.schema,r.args)}catch{throw new xd("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 Xg(t,e){const r=e.name??t.getName(),n=e.description??gm(e.schema);return _m(e.schema)?new oc({name:r,description:n,schema:Bl({input:zl()}).transform(a=>a.input),bound:t}):new oc({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 rl(t,e){return Array.isArray(t)?cc(t,e):Cr.from(r=>cc(r,t))}function cc(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 nl(t){return Array.isArray(t)?uc(t):Cr.from(uc)}function uc(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(t_(o))}}return e}function al(t,e){if(Array.isArray(t)){const r=t;if(!e)throw new Error("Options parameter is required when providing messages.");return lc(r,e)}else{const r=t;return Cr.from(n=>lc(n,r)).withConfig({runName:"trim_messages"})}}async function lc(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=Ks;if(u&&("splitText"in u?d=u.splitText:d=async f=>u(f)),a==="first")return sl(t,{maxTokens:r,tokenCounter:l,textSplitter:d,partialStrategy:s?"first":void 0,endOn:i});if(a==="last")return e_(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 sl(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=Js(l.getType(),{...m,content:p}),_=[...o.slice(0,c),g];if(await n(_)<=r)o=_,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 e_(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 Js(l.getType(),d,xs(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 sl(u,{...i,partialStrategy:r?"last":void 0,endOn:s}),c?[u[0],...u.slice(1).reverse()]:u.reverse()}const dc={human:{message:Nt,messageChunk:$r},ai:{message:wt,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:yr,messageChunk:yr}};function Js(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 wt(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 t_(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 dc&&(r=Js(e,n)),!r)throw new Error(`Unrecognized message chunk class ${e}. Supported classes are ${Object.keys(dc)}`);return r}function Ks(t){const e=t.split(`
|
|
79
|
+
`);return Promise.resolve([...e.slice(0,-1).map(r=>`${r}
|
|
80
|
+
`),e[e.length-1]])}const r_=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"],n_=["image","video","audio","text-plain","file"],il=["text","reasoning",...r_,...n_];var ol={};ge(ol,{AIMessage:()=>wt,AIMessageChunk:()=>Pt,BaseMessage:()=>tt,BaseMessageChunk:()=>dt,ChatMessage:()=>Yt,ChatMessageChunk:()=>xr,FunctionMessage:()=>Ir,FunctionMessageChunk:()=>Ar,HumanMessage:()=>Nt,HumanMessageChunk:()=>$r,KNOWN_BLOCK_TYPES:()=>il,RemoveMessage:()=>yr,SystemMessage:()=>ut,SystemMessageChunk:()=>Rt,ToolMessage:()=>Ct,ToolMessageChunk:()=>Tr,_isMessageFieldWithRole:()=>Ss,_mergeDicts:()=>ve,_mergeLists:()=>Kt,_mergeObj:()=>Es,_mergeStatus:()=>bs,coerceMessageLikeToMessage:()=>Bc,collapseToolCallChunks:()=>Ns,convertToChunk:()=>sn,convertToOpenAIImageBlock:()=>yc,convertToProviderContentBlock:()=>wc,defaultTextSplitter:()=>Ks,defaultToolCallParser:()=>vn,filterMessages:()=>rl,getBufferString:()=>ks,iife:()=>zc,isAIMessage:()=>Uc,isAIMessageChunk:()=>Fc,isBase64ContentBlock:()=>ms,isBaseMessage:()=>Ts,isBaseMessageChunk:()=>xs,isChatMessage:()=>$c,isChatMessageChunk:()=>Oc,isDataContentBlock:()=>ct,isDirectToolOutput:()=>As,isFunctionMessage:()=>Rc,isFunctionMessageChunk:()=>kc,isHumanMessage:()=>Cc,isHumanMessageChunk:()=>Nc,isIDContentBlock:()=>gs,isMessage:()=>_s,isOpenAIToolCallArray:()=>Tc,isPlainTextContentBlock:()=>_c,isSystemMessage:()=>Pc,isSystemMessageChunk:()=>Mc,isToolMessage:()=>$s,isToolMessageChunk:()=>Os,isURLContentBlock:()=>ps,mapChatMessagesToStoredMessages:()=>Gc,mapStoredMessageToChatMessage:()=>Cs,mapStoredMessagesToChatMessages:()=>qc,mergeContent:()=>Xe,mergeMessageRuns:()=>nl,mergeResponseMetadata:()=>Is,mergeUsageMetadata:()=>yn,parseBase64DataUrl:()=>an,parseMimeType:()=>vc,trimMessages:()=>al});const D_=Object.freeze(Object.defineProperty({__proto__:null,AIMessage:wt,AIMessageChunk:Pt,BaseMessage:tt,BaseMessageChunk:dt,ChatMessage:Yt,ChatMessageChunk:xr,FunctionMessage:Ir,FunctionMessageChunk:Ar,HumanMessage:Nt,HumanMessageChunk:$r,KNOWN_BLOCK_TYPES:il,RemoveMessage:yr,SystemMessage:ut,SystemMessageChunk:Rt,ToolMessage:Ct,ToolMessageChunk:Tr,_isMessageFieldWithRole:Ss,_mergeDicts:ve,_mergeLists:Kt,_mergeObj:Es,_mergeStatus:bs,coerceMessageLikeToMessage:Bc,collapseToolCallChunks:Ns,convertToChunk:sn,convertToOpenAIImageBlock:yc,convertToProviderContentBlock:wc,defaultTextSplitter:Ks,defaultToolCallParser:vn,filterMessages:rl,getBufferString:ks,iife:zc,isAIMessage:Uc,isAIMessageChunk:Fc,isBase64ContentBlock:ms,isBaseMessage:Ts,isBaseMessageChunk:xs,isChatMessage:$c,isChatMessageChunk:Oc,isDataContentBlock:ct,isDirectToolOutput:As,isFunctionMessage:Rc,isFunctionMessageChunk:kc,isHumanMessage:Cc,isHumanMessageChunk:Nc,isIDContentBlock:gs,isMessage:_s,isOpenAIToolCallArray:Tc,isPlainTextContentBlock:_c,isSystemMessage:Pc,isSystemMessageChunk:Mc,isToolMessage:$s,isToolMessageChunk:Os,isURLContentBlock:ps,mapChatMessagesToStoredMessages:Gc,mapStoredMessageToChatMessage:Cs,mapStoredMessagesToChatMessages:qc,mergeContent:Xe,mergeMessageRuns:nl,mergeResponseMetadata:Is,mergeUsageMetadata:yn,messages_exports:ol,parseBase64DataUrl:an,parseMimeType:vc,trimMessages:al},Symbol.toStringTag,{value:"Module"}));export{vm as $,lt as A,wt as B,Mt as C,Yp as D,Pt as E,Yt as F,fn as G,$s as H,ct as I,wc as J,an as K,At as L,Qu as M,zp as N,Fp as O,S_ as P,kt as Q,Kp as R,Re as S,xd as T,le as U,_e as V,T_ as W,ym as X,it as Y,Du as Z,Lc as _,mm as a,ut as a$,pm as a0,hm as a1,Vs as a2,O_ as a3,R_ as a4,x_ as a5,Em as a6,us as a7,Xo as a8,C_ as a9,Yu as aA,Qg as aB,j_ as aC,L_ as aD,Td as aE,xs as aF,sn as aG,qt as aH,Er as aI,y_ as aJ,Kc as aK,b as aL,$r as aM,Rt as aN,Ar as aO,Tr as aP,xr as aQ,vc as aR,zc as aS,Qc as aT,Ps as aU,Fd as aV,Lt as aW,Ge as aX,zg as aY,ar as aZ,wr as a_,P_ as aa,A_ as ab,$_ as ac,gm as ad,Qo as ae,N_ as af,k_ as ag,Nt as ah,ks as ai,gr as aj,Cs as ak,Bc as al,Yg as am,In as an,Fc as ao,Cr as ap,ps as aq,ms as ar,yc as as,It as at,qe as au,me as av,pn as aw,bt as ax,Kg as ay,oc as az,M_ as b,tt as b0,Xt as b1,Dp as b2,Bg as b3,Dd as b4,cm as b5,Sp as b6,Vp as b7,_p as b8,hp as b9,p_ as bA,d_ as bB,u_ as bC,o_ as bD,i_ as bE,yr as bF,al as bG,s_ as bH,rl as bI,dt as bJ,D_ as bK,Lp as ba,qg as bb,Jp as bc,Sd as bd,ol as be,nd as bf,$p as bg,Cp as bh,Jd as bi,ed as bj,gi as bk,ys as bl,Yl as bm,g_ as bn,Or as bo,Ws as bp,lr as bq,xt as br,Fl as bs,ee as bt,l_ as bu,h_ as bv,c_ as bw,hi as bx,f_ as by,m_ as bz,__ as c,As as d,ie as e,Ct as f,ge as g,_m as h,ju as i,Qr as j,be as k,Jt as l,Vo as m,un as n,Bl as o,Np as p,Mu as q,I_ as r,zl as s,Uc as t,jc as u,ce as v,Yd as w,Gs as x,Vu as y,Ts as z};
|