UNPKG

@kaibanjs/tools

Version:

A set of tools to work with LLMs and KaibanJS

9 lines 335 kB
"use strict";var e,t;!function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter((e=>"number"!=typeof t[t[e]])),a={};for(const e of r)a[e]=t[e];return e.objectValues(a)},e.objectValues=t=>e.objectKeys(t).map((function(e){return t[e]})),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(e||(e={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(t||(t={}));const r=e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),a=e=>{switch(typeof e){case"undefined":return r.undefined;case"string":return r.string;case"number":return isNaN(e)?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(e)?r.array:null===e?r.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?r.promise:"undefined"!=typeof Map&&e instanceof Map?r.map:"undefined"!=typeof Set&&e instanceof Set?r.set:"undefined"!=typeof Date&&e instanceof Date?r.date:r.object;default:return r.unknown}},n=e.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 i extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},a=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(a);else if("invalid_return_type"===n.code)a(n.returnTypeError);else if("invalid_arguments"===n.code)a(n.argumentsError);else if(0===n.path.length)r._errors.push(t(n));else{let e=r,a=0;for(;a<n.path.length;){const r=n.path[a];a===n.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(n))):e[r]=e[r]||{_errors:[]},e=e[r],a++}}};return a(this),r}static assert(e){if(!(e instanceof i))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,e.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const a of this.issues)a.path.length>0?(t[a.path[0]]=t[a.path[0]]||[],t[a.path[0]].push(e(a))):r.push(e(a));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}i.create=e=>new i(e);const s=(t,a)=>{let i;switch(t.code){case n.invalid_type:i=t.received===r.undefined?"Required":`Expected ${t.expected}, received ${t.received}`;break;case n.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(t.expected,e.jsonStringifyReplacer)}`;break;case n.unrecognized_keys:i=`Unrecognized key(s) in object: ${e.joinValues(t.keys,", ")}`;break;case n.invalid_union:i="Invalid input";break;case n.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${e.joinValues(t.options)}`;break;case n.invalid_enum_value:i=`Invalid enum value. Expected ${e.joinValues(t.options)}, received '${t.received}'`;break;case n.invalid_arguments:i="Invalid function arguments";break;case n.invalid_return_type:i="Invalid function return type";break;case n.invalid_date:i="Invalid date";break;case n.invalid_string:"object"==typeof t.validation?"includes"in t.validation?(i=`Invalid input: must include "${t.validation.includes}"`,"number"==typeof t.validation.position&&(i=`${i} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?i=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?i=`Invalid input: must end with "${t.validation.endsWith}"`:e.assertNever(t.validation):i="regex"!==t.validation?`Invalid ${t.validation}`:"Invalid";break;case n.too_small:i="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:"number"===t.type?`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:"date"===t.type?`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:"Invalid input";break;case n.too_big:i="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:"number"===t.type?`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"bigint"===t.type?`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"date"===t.type?`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:"Invalid input";break;case n.custom:i="Invalid input";break;case n.invalid_intersection_types:i="Intersection results could not be merged";break;case n.not_multiple_of:i=`Number must be a multiple of ${t.multipleOf}`;break;case n.not_finite:i="Number must be finite";break;default:i=a.defaultError,e.assertNever(t)}return{message:i}};let o=s;function c(){return o}const d=e=>{const{data:t,path:r,errorMaps:a,issueData:n}=e,i=[...r,...n.path||[]],s={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let o="";const c=a.filter((e=>!!e)).slice().reverse();for(const e of c)o=e(s,{data:t,defaultError:o}).message;return{...n,path:i,message:o}};function l(e,t){const r=c(),a=d({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===s?void 0:s].filter((e=>!!e))});e.common.issues.push(a)}class u{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const a of t){if("aborted"===a.status)return h;"dirty"===a.status&&e.dirty(),r.push(a.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,a=await e.value;r.push({key:t,value:a})}return u.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const a of t){const{key:t,value:n}=a;if("aborted"===t.status)return h;if("aborted"===n.status)return h;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!a.alwaysSet||(r[t.value]=n.value)}return{status:e.value,value:r}}}const h=Object.freeze({status:"aborted"}),p=e=>({status:"dirty",value:e}),m=e=>({status:"valid",value:e}),f=e=>"aborted"===e.status,g=e=>"dirty"===e.status,y=e=>"valid"===e.status,_=e=>"undefined"!=typeof Promise&&e instanceof Promise;function b(e,t,r,a){if("function"==typeof t?e!==t||!a:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function v(e,t,r,a,n){if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,r),r}var w,E,O;"function"==typeof SuppressedError&&SuppressedError,function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(w||(w={}));class ${constructor(e,t,r,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=a}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const k=(e,t)=>{if(y(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new i(e.common.issues);return this._error=t,this._error}}};function I(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:a,description:n}=e;if(t&&(r||a))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(t,n)=>{var i,s;const{message:o}=e;return"invalid_enum_value"===t.code?{message:null!=o?o:n.defaultError}:void 0===n.data?{message:null!==(i=null!=o?o:a)&&void 0!==i?i:n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:null!==(s=null!=o?o:r)&&void 0!==s?s:n.defaultError}},description:n}}class T{get description(){return this._def.description}_getType(e){return a(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:a(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new u,ctx:{common:e.parent.common,data:e.data,parsedType:a(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(_(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;const n={common:{issues:[],async:null!==(r=null==t?void 0:t.async)&&void 0!==r&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:a(e)},i=this._parseSync({data:e,path:n.path,parent:n});return k(n,i)}"~validate"(e){var t,r;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:a(e)};if(!this["~standard"].async)try{const t=this._parseSync({data:e,path:[],parent:n});return y(t)?{value:t.value}:{issues:n.common.issues}}catch(e){(null===(r=null===(t=null==e?void 0:e.message)||void 0===t?void 0:t.toLowerCase())||void 0===r?void 0:r.includes("encountered"))&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then((e=>y(e)?{value:e.value}:{issues:n.common.issues}))}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:a(e)},n=this._parse({data:e,path:r.path,parent:r}),i=await(_(n)?n:Promise.resolve(n));return k(r,i)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,a)=>{const i=e(t),s=()=>a.addIssue({code:n.custom,...r(t)});return"undefined"!=typeof Promise&&i instanceof Promise?i.then((e=>!!e||(s(),!1))):!!i||(s(),!1)}))}refinement(e,t){return this._refinement(((r,a)=>!!e(r)||(a.addIssue("function"==typeof t?t(r,a):t),!1)))}_refinement(e){return new xe({schema:this,typeName:Ze.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:e=>this["~validate"](e)}}optional(){return Se.create(this,this._def)}nullable(){return Ae.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return de.create(this)}promise(){return Te.create(this,this._def)}or(e){return he.create([this,e],this._def)}and(e){return ge.create(this,e,this._def)}transform(e){return new xe({...I(this._def),schema:this,typeName:Ze.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new je({...I(this._def),innerType:this,defaultValue:t,typeName:Ze.ZodDefault})}brand(){return new Ce({typeName:Ze.ZodBranded,type:this,...I(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Pe({...I(this._def),innerType:this,catchValue:t,typeName:Ze.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Le.create(this,e)}readonly(){return Me.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const x=/^c[^\s-]{8,}$/i,S=/^[0-9a-z]+$/,A=/^[0-9A-HJKMNP-TV-Z]{26}$/i,j=/^[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,P=/^[a-z0-9_-]{21}$/i,R=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,N=/^[-+]?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)?)??$/,C=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let L;const M=/^(?:(?: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])$/,U=/^(?:(?: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])$/,D=/^(([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]))$/,F=/^(([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])$/,Z=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,z=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,B="((\\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])))",H=new RegExp(`^${B}$`);function q(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),t}function G(e){let t=`${B}T${q(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function J(e,t){return!("v4"!==t&&t||!M.test(e))||!("v6"!==t&&t||!D.test(e))}function V(e,t){if(!R.test(e))return!1;try{const[r]=e.split("."),a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(a));return"object"==typeof n&&null!==n&&(!(!n.typ||!n.alg)&&(!t||n.alg===t))}catch(e){return!1}}function W(e,t){return!("v4"!==t&&t||!U.test(e))||!("v6"!==t&&t||!F.test(e))}class K extends T{_parse(t){this._def.coerce&&(t.data=String(t.data));if(this._getType(t)!==r.string){const e=this._getOrReturnCtx(t);return l(e,{code:n.invalid_type,expected:r.string,received:e.parsedType}),h}const a=new u;let i;for(const r of this._def.checks)if("min"===r.kind)t.data.length<r.value&&(i=this._getOrReturnCtx(t,i),l(i,{code:n.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),a.dirty());else if("max"===r.kind)t.data.length>r.value&&(i=this._getOrReturnCtx(t,i),l(i,{code:n.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),a.dirty());else if("length"===r.kind){const e=t.data.length>r.value,s=t.data.length<r.value;(e||s)&&(i=this._getOrReturnCtx(t,i),e?l(i,{code:n.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):s&&l(i,{code:n.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),a.dirty())}else if("email"===r.kind)C.test(t.data)||(i=this._getOrReturnCtx(t,i),l(i,{validation:"email",code:n.invalid_string,message:r.message}),a.dirty());else if("emoji"===r.kind)L||(L=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),L.test(t.data)||(i=this._getOrReturnCtx(t,i),l(i,{validation:"emoji",code:n.invalid_string,message:r.message}),a.dirty());else if("uuid"===r.kind)j.test(t.data)||(i=this._getOrReturnCtx(t,i),l(i,{validation:"uuid",code:n.invalid_string,message:r.message}),a.dirty());else if("nanoid"===r.kind)P.test(t.data)||(i=this._getOrReturnCtx(t,i),l(i,{validation:"nanoid",code:n.invalid_string,message:r.message}),a.dirty());else if("cuid"===r.kind)x.test(t.data)||(i=this._getOrReturnCtx(t,i),l(i,{validation:"cuid",code:n.invalid_string,message:r.message}),a.dirty());else if("cuid2"===r.kind)S.test(t.data)||(i=this._getOrReturnCtx(t,i),l(i,{validation:"cuid2",code:n.invalid_string,message:r.message}),a.dirty());else if("ulid"===r.kind)A.test(t.data)||(i=this._getOrReturnCtx(t,i),l(i,{validation:"ulid",code:n.invalid_string,message:r.message}),a.dirty());else if("url"===r.kind)try{new URL(t.data)}catch(e){i=this._getOrReturnCtx(t,i),l(i,{validation:"url",code:n.invalid_string,message:r.message}),a.dirty()}else if("regex"===r.kind){r.regex.lastIndex=0;r.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),l(i,{validation:"regex",code:n.invalid_string,message:r.message}),a.dirty())}else if("trim"===r.kind)t.data=t.data.trim();else if("includes"===r.kind)t.data.includes(r.value,r.position)||(i=this._getOrReturnCtx(t,i),l(i,{code:n.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),a.dirty());else if("toLowerCase"===r.kind)t.data=t.data.toLowerCase();else if("toUpperCase"===r.kind)t.data=t.data.toUpperCase();else if("startsWith"===r.kind)t.data.startsWith(r.value)||(i=this._getOrReturnCtx(t,i),l(i,{code:n.invalid_string,validation:{startsWith:r.value},message:r.message}),a.dirty());else if("endsWith"===r.kind)t.data.endsWith(r.value)||(i=this._getOrReturnCtx(t,i),l(i,{code:n.invalid_string,validation:{endsWith:r.value},message:r.message}),a.dirty());else if("datetime"===r.kind){G(r).test(t.data)||(i=this._getOrReturnCtx(t,i),l(i,{code:n.invalid_string,validation:"datetime",message:r.message}),a.dirty())}else if("date"===r.kind){H.test(t.data)||(i=this._getOrReturnCtx(t,i),l(i,{code:n.invalid_string,validation:"date",message:r.message}),a.dirty())}else if("time"===r.kind){new RegExp(`^${q(r)}$`).test(t.data)||(i=this._getOrReturnCtx(t,i),l(i,{code:n.invalid_string,validation:"time",message:r.message}),a.dirty())}else"duration"===r.kind?N.test(t.data)||(i=this._getOrReturnCtx(t,i),l(i,{validation:"duration",code:n.invalid_string,message:r.message}),a.dirty()):"ip"===r.kind?J(t.data,r.version)||(i=this._getOrReturnCtx(t,i),l(i,{validation:"ip",code:n.invalid_string,message:r.message}),a.dirty()):"jwt"===r.kind?V(t.data,r.alg)||(i=this._getOrReturnCtx(t,i),l(i,{validation:"jwt",code:n.invalid_string,message:r.message}),a.dirty()):"cidr"===r.kind?W(t.data,r.version)||(i=this._getOrReturnCtx(t,i),l(i,{validation:"cidr",code:n.invalid_string,message:r.message}),a.dirty()):"base64"===r.kind?Z.test(t.data)||(i=this._getOrReturnCtx(t,i),l(i,{validation:"base64",code:n.invalid_string,message:r.message}),a.dirty()):"base64url"===r.kind?z.test(t.data)||(i=this._getOrReturnCtx(t,i),l(i,{validation:"base64url",code:n.invalid_string,message:r.message}),a.dirty()):e.assertNever(r);return{status:a.value,value:t.data}}_regex(e,t,r){return this.refinement((t=>e.test(t)),{validation:t,code:n.invalid_string,...w.errToObj(r)})}_addCheck(e){return new K({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...w.errToObj(e)})}url(e){return this._addCheck({kind:"url",...w.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...w.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...w.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...w.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...w.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...w.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...w.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...w.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...w.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...w.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...w.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...w.errToObj(e)})}datetime(e){var t,r;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,local:null!==(r=null==e?void 0:e.local)&&void 0!==r&&r,...w.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...w.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...w.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...w.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...w.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...w.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...w.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...w.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...w.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...w.errToObj(t)})}nonempty(e){return this.min(1,w.errToObj(e))}trim(){return new K({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new K({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new K({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function X(e,t){const r=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,n=r>a?r:a;return parseInt(e.toFixed(n).replace(".",""))%parseInt(t.toFixed(n).replace(".",""))/Math.pow(10,n)}K.create=e=>{var t;return new K({checks:[],typeName:Ze.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...I(e)})};class Y extends T{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){this._def.coerce&&(t.data=Number(t.data));if(this._getType(t)!==r.number){const e=this._getOrReturnCtx(t);return l(e,{code:n.invalid_type,expected:r.number,received:e.parsedType}),h}let a;const i=new u;for(const r of this._def.checks)if("int"===r.kind)e.isInteger(t.data)||(a=this._getOrReturnCtx(t,a),l(a,{code:n.invalid_type,expected:"integer",received:"float",message:r.message}),i.dirty());else if("min"===r.kind){(r.inclusive?t.data<r.value:t.data<=r.value)&&(a=this._getOrReturnCtx(t,a),l(a,{code:n.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),i.dirty())}else if("max"===r.kind){(r.inclusive?t.data>r.value:t.data>=r.value)&&(a=this._getOrReturnCtx(t,a),l(a,{code:n.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),i.dirty())}else"multipleOf"===r.kind?0!==X(t.data,r.value)&&(a=this._getOrReturnCtx(t,a),l(a,{code:n.not_multiple_of,multipleOf:r.value,message:r.message}),i.dirty()):"finite"===r.kind?Number.isFinite(t.data)||(a=this._getOrReturnCtx(t,a),l(a,{code:n.not_finite,message:r.message}),i.dirty()):e.assertNever(r);return{status:i.value,value:t.data}}gte(e,t){return this.setLimit("min",e,!0,w.toString(t))}gt(e,t){return this.setLimit("min",e,!1,w.toString(t))}lte(e,t){return this.setLimit("max",e,!0,w.toString(t))}lt(e,t){return this.setLimit("max",e,!1,w.toString(t))}setLimit(e,t,r,a){return new Y({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:w.toString(a)}]})}_addCheck(e){return new Y({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:w.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:w.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:w.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:w.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:w.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:w.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:w.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:w.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:w.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((t=>"int"===t.kind||"multipleOf"===t.kind&&e.isInteger(t.value)))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Y.create=e=>new Y({checks:[],typeName:Ze.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...I(e)});class Q extends T{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch(e){return this._getInvalidInput(t)}if(this._getType(t)!==r.bigint)return this._getInvalidInput(t);let a;const i=new u;for(const r of this._def.checks)if("min"===r.kind){(r.inclusive?t.data<r.value:t.data<=r.value)&&(a=this._getOrReturnCtx(t,a),l(a,{code:n.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),i.dirty())}else if("max"===r.kind){(r.inclusive?t.data>r.value:t.data>=r.value)&&(a=this._getOrReturnCtx(t,a),l(a,{code:n.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),i.dirty())}else"multipleOf"===r.kind?t.data%r.value!==BigInt(0)&&(a=this._getOrReturnCtx(t,a),l(a,{code:n.not_multiple_of,multipleOf:r.value,message:r.message}),i.dirty()):e.assertNever(r);return{status:i.value,value:t.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:r.bigint,received:t.parsedType}),h}gte(e,t){return this.setLimit("min",e,!0,w.toString(t))}gt(e,t){return this.setLimit("min",e,!1,w.toString(t))}lte(e,t){return this.setLimit("max",e,!0,w.toString(t))}lt(e,t){return this.setLimit("max",e,!1,w.toString(t))}setLimit(e,t,r,a){return new Q({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:w.toString(a)}]})}_addCheck(e){return new Q({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:w.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:w.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:w.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:w.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:w.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}Q.create=e=>{var t;return new Q({checks:[],typeName:Ze.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...I(e)})};class ee extends T{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==r.boolean){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:r.boolean,received:t.parsedType}),h}return m(e.data)}}ee.create=e=>new ee({typeName:Ze.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...I(e)});class te extends T{_parse(t){this._def.coerce&&(t.data=new Date(t.data));if(this._getType(t)!==r.date){const e=this._getOrReturnCtx(t);return l(e,{code:n.invalid_type,expected:r.date,received:e.parsedType}),h}if(isNaN(t.data.getTime())){return l(this._getOrReturnCtx(t),{code:n.invalid_date}),h}const a=new u;let i;for(const r of this._def.checks)"min"===r.kind?t.data.getTime()<r.value&&(i=this._getOrReturnCtx(t,i),l(i,{code:n.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),a.dirty()):"max"===r.kind?t.data.getTime()>r.value&&(i=this._getOrReturnCtx(t,i),l(i,{code:n.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),a.dirty()):e.assertNever(r);return{status:a.value,value:new Date(t.data.getTime())}}_addCheck(e){return new te({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:w.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:w.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}te.create=e=>new te({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:Ze.ZodDate,...I(e)});class re extends T{_parse(e){if(this._getType(e)!==r.symbol){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:r.symbol,received:t.parsedType}),h}return m(e.data)}}re.create=e=>new re({typeName:Ze.ZodSymbol,...I(e)});class ae extends T{_parse(e){if(this._getType(e)!==r.undefined){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:r.undefined,received:t.parsedType}),h}return m(e.data)}}ae.create=e=>new ae({typeName:Ze.ZodUndefined,...I(e)});class ne extends T{_parse(e){if(this._getType(e)!==r.null){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:r.null,received:t.parsedType}),h}return m(e.data)}}ne.create=e=>new ne({typeName:Ze.ZodNull,...I(e)});class ie extends T{constructor(){super(...arguments),this._any=!0}_parse(e){return m(e.data)}}ie.create=e=>new ie({typeName:Ze.ZodAny,...I(e)});class se extends T{constructor(){super(...arguments),this._unknown=!0}_parse(e){return m(e.data)}}se.create=e=>new se({typeName:Ze.ZodUnknown,...I(e)});class oe extends T{_parse(e){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:r.never,received:t.parsedType}),h}}oe.create=e=>new oe({typeName:Ze.ZodNever,...I(e)});class ce extends T{_parse(e){if(this._getType(e)!==r.undefined){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:r.void,received:t.parsedType}),h}return m(e.data)}}ce.create=e=>new ce({typeName:Ze.ZodVoid,...I(e)});class de extends T{_parse(e){const{ctx:t,status:a}=this._processInputParams(e),i=this._def;if(t.parsedType!==r.array)return l(t,{code:n.invalid_type,expected:r.array,received:t.parsedType}),h;if(null!==i.exactLength){const e=t.data.length>i.exactLength.value,r=t.data.length<i.exactLength.value;(e||r)&&(l(t,{code:e?n.too_big:n.too_small,minimum:r?i.exactLength.value:void 0,maximum:e?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),a.dirty())}if(null!==i.minLength&&t.data.length<i.minLength.value&&(l(t,{code:n.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),a.dirty()),null!==i.maxLength&&t.data.length>i.maxLength.value&&(l(t,{code:n.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),a.dirty()),t.common.async)return Promise.all([...t.data].map(((e,r)=>i.type._parseAsync(new $(t,e,t.path,r))))).then((e=>u.mergeArray(a,e)));const s=[...t.data].map(((e,r)=>i.type._parseSync(new $(t,e,t.path,r))));return u.mergeArray(a,s)}get element(){return this._def.type}min(e,t){return new de({...this._def,minLength:{value:e,message:w.toString(t)}})}max(e,t){return new de({...this._def,maxLength:{value:e,message:w.toString(t)}})}length(e,t){return new de({...this._def,exactLength:{value:e,message:w.toString(t)}})}nonempty(e){return this.min(1,e)}}function le(e){if(e instanceof ue){const t={};for(const r in e.shape){const a=e.shape[r];t[r]=Se.create(le(a))}return new ue({...e._def,shape:()=>t})}return e instanceof de?new de({...e._def,type:le(e.element)}):e instanceof Se?Se.create(le(e.unwrap())):e instanceof Ae?Ae.create(le(e.unwrap())):e instanceof ye?ye.create(e.items.map((e=>le(e)))):e}de.create=(e,t)=>new de({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ze.ZodArray,...I(t)});class ue extends T{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const t=this._def.shape(),r=e.objectKeys(t);return this._cached={shape:t,keys:r}}_parse(e){if(this._getType(e)!==r.object){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:r.object,received:t.parsedType}),h}const{status:t,ctx:a}=this._processInputParams(e),{shape:i,keys:s}=this._getCached(),o=[];if(!(this._def.catchall instanceof oe&&"strip"===this._def.unknownKeys))for(const e in a.data)s.includes(e)||o.push(e);const c=[];for(const e of s){const t=i[e],r=a.data[e];c.push({key:{status:"valid",value:e},value:t._parse(new $(a,r,a.path,e)),alwaysSet:e in a.data})}if(this._def.catchall instanceof oe){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of o)c.push({key:{status:"valid",value:e},value:{status:"valid",value:a.data[e]}});else if("strict"===e)o.length>0&&(l(a,{code:n.unrecognized_keys,keys:o}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of o){const r=a.data[t];c.push({key:{status:"valid",value:t},value:e._parse(new $(a,r,a.path,t)),alwaysSet:t in a.data})}}return a.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of c){const r=await t.key,a=await t.value;e.push({key:r,value:a,alwaysSet:t.alwaysSet})}return e})).then((e=>u.mergeObjectSync(t,e))):u.mergeObjectSync(t,c)}get shape(){return this._def.shape()}strict(e){return w.errToObj,new ue({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var a,n,i,s;const o=null!==(i=null===(n=(a=this._def).errorMap)||void 0===n?void 0:n.call(a,t,r).message)&&void 0!==i?i:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(s=w.errToObj(e).message)&&void 0!==s?s:o}:{message:o}}}:{}})}strip(){return new ue({...this._def,unknownKeys:"strip"})}passthrough(){return new ue({...this._def,unknownKeys:"passthrough"})}extend(e){return new ue({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ue({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Ze.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ue({...this._def,catchall:e})}pick(t){const r={};return e.objectKeys(t).forEach((e=>{t[e]&&this.shape[e]&&(r[e]=this.shape[e])})),new ue({...this._def,shape:()=>r})}omit(t){const r={};return e.objectKeys(this.shape).forEach((e=>{t[e]||(r[e]=this.shape[e])})),new ue({...this._def,shape:()=>r})}deepPartial(){return le(this)}partial(t){const r={};return e.objectKeys(this.shape).forEach((e=>{const a=this.shape[e];t&&!t[e]?r[e]=a:r[e]=a.optional()})),new ue({...this._def,shape:()=>r})}required(t){const r={};return e.objectKeys(this.shape).forEach((e=>{if(t&&!t[e])r[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof Se;)t=t._def.innerType;r[e]=t}})),new ue({...this._def,shape:()=>r})}keyof(){return $e(e.objectKeys(this.shape))}}ue.create=(e,t)=>new ue({shape:()=>e,unknownKeys:"strip",catchall:oe.create(),typeName:Ze.ZodObject,...I(t)}),ue.strictCreate=(e,t)=>new ue({shape:()=>e,unknownKeys:"strict",catchall:oe.create(),typeName:Ze.ZodObject,...I(t)}),ue.lazycreate=(e,t)=>new ue({shape:e,unknownKeys:"strip",catchall:oe.create(),typeName:Ze.ZodObject,...I(t)});class he extends T{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map((async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map((e=>new i(e.ctx.common.issues)));return l(t,{code:n.invalid_union,unionErrors:r}),h}));{let e;const a=[];for(const n of r){const r={...t,common:{...t.common,issues:[]},parent:null},i=n._parseSync({data:t.data,path:t.path,parent:r});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:r}),r.common.issues.length&&a.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=a.map((e=>new i(e)));return l(t,{code:n.invalid_union,unionErrors:s}),h}}get options(){return this._def.options}}he.create=(e,t)=>new he({options:e,typeName:Ze.ZodUnion,...I(t)});const pe=t=>t instanceof Ee?pe(t.schema):t instanceof xe?pe(t.innerType()):t instanceof Oe?[t.value]:t instanceof ke?t.options:t instanceof Ie?e.objectValues(t.enum):t instanceof je?pe(t._def.innerType):t instanceof ae?[void 0]:t instanceof ne?[null]:t instanceof Se?[void 0,...pe(t.unwrap())]:t instanceof Ae?[null,...pe(t.unwrap())]:t instanceof Ce||t instanceof Me?pe(t.unwrap()):t instanceof Pe?pe(t._def.innerType):[];class me extends T{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==r.object)return l(t,{code:n.invalid_type,expected:r.object,received:t.parsedType}),h;const a=this.discriminator,i=t.data[a],s=this.optionsMap.get(i);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(l(t,{code:n.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[a]}),h)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const a=new Map;for(const r of t){const t=pe(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const n of t){if(a.has(n))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(n)}`);a.set(n,r)}}return new me({typeName:Ze.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...I(r)})}}function fe(t,n){const i=a(t),s=a(n);if(t===n)return{valid:!0,data:t};if(i===r.object&&s===r.object){const r=e.objectKeys(n),a=e.objectKeys(t).filter((e=>-1!==r.indexOf(e))),i={...t,...n};for(const e of a){const r=fe(t[e],n[e]);if(!r.valid)return{valid:!1};i[e]=r.data}return{valid:!0,data:i}}if(i===r.array&&s===r.array){if(t.length!==n.length)return{valid:!1};const e=[];for(let r=0;r<t.length;r++){const a=fe(t[r],n[r]);if(!a.valid)return{valid:!1};e.push(a.data)}return{valid:!0,data:e}}return i===r.date&&s===r.date&&+t==+n?{valid:!0,data:t}:{valid:!1}}class ge extends T{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),a=(e,a)=>{if(f(e)||f(a))return h;const i=fe(e.value,a.value);return i.valid?((g(e)||g(a))&&t.dirty(),{status:t.value,value:i.data}):(l(r,{code:n.invalid_intersection_types}),h)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then((([e,t])=>a(e,t))):a(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}ge.create=(e,t,r)=>new ge({left:e,right:t,typeName:Ze.ZodIntersection,...I(r)});class ye extends T{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==r.array)return l(a,{code:n.invalid_type,expected:r.array,received:a.parsedType}),h;if(a.data.length<this._def.items.length)return l(a,{code:n.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),h;!this._def.rest&&a.data.length>this._def.items.length&&(l(a,{code:n.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...a.data].map(((e,t)=>{const r=this._def.items[t]||this._def.rest;return r?r._parse(new $(a,e,a.path,t)):null})).filter((e=>!!e));return a.common.async?Promise.all(i).then((e=>u.mergeArray(t,e))):u.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new ye({...this._def,rest:e})}}ye.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ye({items:e,typeName:Ze.ZodTuple,rest:null,...I(t)})};class _e extends T{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==r.object)return l(a,{code:n.invalid_type,expected:r.object,received:a.parsedType}),h;const i=[],s=this._def.keyType,o=this._def.valueType;for(const e in a.data)i.push({key:s._parse(new $(a,e,a.path,e)),value:o._parse(new $(a,a.data[e],a.path,e)),alwaysSet:e in a.data});return a.common.async?u.mergeObjectAsync(t,i):u.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,r){return new _e(t instanceof T?{keyType:e,valueType:t,typeName:Ze.ZodRecord,...I(r)}:{keyType:K.create(),valueType:e,typeName:Ze.ZodRecord,...I(t)})}}class be extends T{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==r.map)return l(a,{code:n.invalid_type,expected:r.map,received:a.parsedType}),h;const i=this._def.keyType,s=this._def.valueType,o=[...a.data.entries()].map((([e,t],r)=>({key:i._parse(new $(a,e,a.path,[r,"key"])),value:s._parse(new $(a,t,a.path,[r,"value"]))})));if(a.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const r of o){const a=await r.key,n=await r.value;if("aborted"===a.status||"aborted"===n.status)return h;"dirty"!==a.status&&"dirty"!==n.status||t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const r of o){const a=r.key,n=r.value;if("aborted"===a.status||"aborted"===n.status)return h;"dirty"!==a.status&&"dirty"!==n.status||t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}}}}be.create=(e,t,r)=>new be({valueType:t,keyType:e,typeName:Ze.ZodMap,...I(r)});class ve extends T{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==r.set)return l(a,{code:n.invalid_type,expected:r.set,received:a.parsedType}),h;const i=this._def;null!==i.minSize&&a.data.size<i.minSize.value&&(l(a,{code:n.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),t.dirty()),null!==i.maxSize&&a.data.size>i.maxSize.value&&(l(a,{code:n.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());const s=this._def.valueType;function o(e){const r=new Set;for(const a of e){if("aborted"===a.status)return h;"dirty"===a.status&&t.dirty(),r.add(a.value)}return{status:t.value,value:r}}const c=[...a.data.values()].map(((e,t)=>s._parse(new $(a,e,a.path,t))));return a.common.async?Promise.all(c).then((e=>o(e))):o(c)}min(e,t){return new ve({...this._def,minSize:{value:e,message:w.toString(t)}})}max(e,t){return new ve({...this._def,maxSize:{value:e,message:w.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ve.create=(e,t)=>new ve({valueType:e,minSize:null,maxSize:null,typeName:Ze.ZodSet,...I(t)});class we extends T{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==r.function)return l(t,{code:n.invalid_type,expected:r.function,received:t.parsedType}),h;function a(e,r){return d({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,c(),s].filter((e=>!!e)),issueData:{code:n.invalid_arguments,argumentsError:r}})}function o(e,r){return d({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,c(),s].filter((e=>!!e)),issueData:{code:n.invalid_return_type,returnTypeError:r}})}const u={errorMap:t.common.contextualErrorMap},p=t.data;if(this._def.returns instanceof Te){const e=this;return m((async function(...t){const r=new i([]),n=await e._def.args.parseAsync(t,u).catch((e=>{throw r.addIssue(a(t,e)),r})),s=await Reflect.apply(p,this,n);return await e._def.returns._def.type.parseAsync(s,u).catch((e=>{throw r.addIssue(o(s,e)),r}))}))}{const e=this;return m((function(...t){const r=e._def.args.safeParse(t,u);if(!r.success)throw new i([a(t,r.error)]);const n=Reflect.apply(p,this,r.data),s=e._def.returns.safeParse(n,u);if(!s.success)throw new i([o(n,s.error)]);return s.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new we({...this._def,args:ye.create(e).rest(se.create())})}returns(e){return new we({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new we({args:e||ye.create([]).rest(se.create()),returns:t||se.create(),typeName:Ze.ZodFunction,...I(r)})}}class Ee extends T{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Ee.create=(e,t)=>new Ee({getter:e,typeName:Ze.ZodLazy,...I(t)});class Oe extends T{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return l(t,{received:t.data,code:n.invalid_literal,expected:this._def.value}),h}return{status:"valid",value:e.data}}get value(){return this._def.value}}function $e(e,t){return new ke({values:e,typeName:Ze.ZodEnum,...I(t)})}Oe.create=(e,t)=>new Oe({value:e,typeName:Ze.ZodLiteral,...I(t)});class ke extends T{constructor(){super(...arguments),E.set(this,void 0)}_parse(t){if("string"!=typeof t.data){const r=this._getOrReturnCtx(t),a=this._def.values;return l(r,{expected:e.joinValues(a),received:r.parsedType,code:n.invalid_type}),h}if(b(this,E)||v(this,E,new Set(this._def.values)),!b(this,E).has(t.data)){const e=this._getOrReturnCtx(t),r=this._def.values;return l(e,{received:e.data,code:n.invalid_enum_value,options:r}),h}return m(t.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ke.create(e,{...this._def,...t})}exclude(e,t=this._def){return ke.create(this.options.filter((t=>!e.includes(t))),{...this._def,...t})}}E=new WeakMap,ke.create=$e;class Ie extends T{constructor(){super(...arguments),O.set(this,void 0)}_parse(t){const a=e.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==r.string&&i.parsedType!==r.number){const t=e.objectValues(a);return l(i,{expected:e.joinValues(t),received:i.parsedType,code:n.invalid_type}),h}if(b(this,O)||v(this,O,new Set(e.getValidEnumValues(this._def.values))),!b(this,O).has(t.data)){const t=e.objectValues(a);return l(i,{received:i.data,code:n.invalid_enum_value,options:t}),h}return m(t.data)}get enum(){return this._def.values}}O=new WeakMap,Ie.create=(e,t)=>new Ie({values:e,typeName:Ze.ZodNativeEnum,...I(t)});class Te extends T{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==r.promise&&!1===t.common.async)return l(t,{code:n.invalid_type,expected:r.promise,received:t.parsedType}),h;const a=t.parsedType===r.promise?t.data:Promise.resolve(t.data);return m(a.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}Te.create=(e,t)=>new Te({type:e,typeName:Ze.ZodPromise,...I(t)});class xe extends T{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:r,ctx:a}=this._processInputParams(t),n=this._def.effect||null,i={addIssue:e=>{l(a,e),e.fatal?r.abort():r.dirty()},get path(){return a.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===n.type){const e=n.transform(a.data,i);if(a.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===r.value)return h;const t=await this._def.schema._parseAsync({data:e,path:a.path,parent:a});return"aborted"===t.status?h:"dirty"===t.status||"dirty"===r.value?p(t.value):t}));{if("aborted"===r.value)return h;const t=this._def.schema._parseSync({data:e,path:a.path,parent:a});return"aborted"===t.status?h:"dirty"===t.status||"dirty"===r.value?p(t.value):t}}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,i);if(a.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===a.common.async){const t=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return"aborted"===t.status?h:("dirty"===t.status&&r.dirty(),e(t.value),{status:r.value,value:t.value})}return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then((t=>"aborted"===t.status?h:("dirty"===t.status&&r.dirty(),e(t.value).then((()=>({status:r.value,value:t.value}))))))}if("transform"===n.type){if(!1===a.common.async){const e=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!y(e))return e;const t=n.transform(e.value,i);if(t instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:t}}return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then((e=>y(e)?Promise.resolve(n.transform(e.value,i)).then((e=>({status:r.value,value:e}))):e))}e.assertNever(n)}}xe.create=(e,t,r)=>new xe({schema:e,typeName:Ze.ZodEffects,effect:t,...I(r)}),xe.createWithPreprocess=(e,t,r)=>new xe({schema:t,effect:{type:"preprocess",transform:e},typeName:Ze.ZodEffects,...I(r)});class Se extends T{_parse(e){return this._getType(e)===r.undefined?m(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Se.create=(e,t)=>new Se({innerType:e,typeName:Ze.ZodOptional,...I(t)});class Ae extends T{_parse(e){return this._getType(e)===r.null?m(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:Ze.ZodNullable,...I(t)});class je extends T{_parse(e){const{ctx:t}=this._processInputParams(e);let a=t.data;return t.parsedType===r.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}je.create=(e,t)=>new je({innerType:e,typeName:Ze.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...I(t)});class Pe extends T{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return _(a)?a.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new i(r.common.issues)},input:r.data})}))):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new i(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Pe.create=(e,t)=>new Pe({innerType:e,typeName:Ze.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...I(t)});class Re extends T{_parse(e){if(this._getType(e)!==r.nan){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:r.nan,received:t.parsedType}),h}return{status:"valid",value:e.data}}}Re.create=e=>new Re({typeName:Ze.ZodNaN,...I(e)});const Ne=Symbol("zod_brand");class Ce extends T{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Le extends T{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?h:"dirty"===e.status?(t.dirty(),p(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?h:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new Le({in:e,out:t,typeName:Ze.ZodPipeline})}}class Me extends T{_parse(e){const t=this._def.innerType._parse(e),r=e=>(y(e)&&(e.value=Object.freeze(e.value)),e);return _(t)?t.then((e=>r(e))):r(t)}unwrap(){return this._def.innerType}}function Ue(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function De(e,t={},r){return e?ie.create().superRefine(((a,n)=>{var i,s;const o=e(a);if(o instanceof Promise)return o.then((e=>{var i,s;if(!e){const e=Ue(t,a),o=null===(s=null!==(i=e.fatal)&&void 0!==i?i:r)||void 0===s||s;n.addIssue({code:"custom",...e,fatal:o})}}));if(!o){const e=Ue(t,a),o=null===(s=null!==(i=e.fatal)&&void 0!==i?i:r)||void 0===s||s;n.addIssue({code:"custom",...e,fatal:o})}})):ie.create()}Me.create=(e,t)=>new Me({innerType:e,typeName:Ze.ZodReadonly,...I(t)});const Fe={object:ue.lazycreate};var Ze;!function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(Ze||(Ze={}));const ze=K.create,Be=Y.create,He=Re.create,qe=Q.create,Ge=ee.create,Je=te.create,Ve=re.create,We=ae.create,Ke=ne.create,Xe=ie.create,Ye=se.create,Qe=oe.create,et=ce.create,tt=de.create,rt=ue.create,at=ue.strictCreate,nt=he.create,it=me.create,st=ge.create,ot=ye.create,ct=_e.create,dt=be.create,lt=ve.create,ut=we.create,ht=Ee.create,pt=Oe.create,mt=ke.create,ft=Ie.create,gt=Te.create,yt=xe.create,_t=Se.create,bt=Ae.create,vt=xe.createWithPreprocess,wt=Le.create,Et={string:e=>K.create({...e,coerce:!0}),number:e=>Y.create({...e,coerce:!0}),boolean:e=>ee.create({...e,coerce:!0}),bigint:e=>Q.create({...e,coerce:!0}),date:e=>te.create({...e,coerce:!0})},Ot=h;var $t=Object.freeze({__proto__:null,defaultErrorMap:s,setErrorMap:function(e){o=e},getErrorMap:c,makeIssue:d,EMPTY_PATH:[],addIssueToContext:l,ParseStatus:u,INVALID:h,DIRTY:p,OK:m,isAborted:f,isDirty:g,isValid:y,isAsync:_,get util(){return e},get objectUtil(){return t},ZodParsedType:r,getParsedType:a,ZodType:T,datetimeRegex:G,ZodString:K,ZodNumber:Y,ZodBigInt:Q,ZodBoolean:ee,ZodDate:te,ZodSymbol:re,ZodUndefined:ae,ZodNull:ne,ZodAny:ie,ZodUnknown:se,ZodNever:oe,ZodVoid:ce,ZodArray:de,ZodObject:ue,ZodUnion:he,ZodDiscriminatedUnion:me,ZodIntersection:ge,ZodTuple:ye,ZodRecord:_e,ZodMap:be,ZodSet:ve,ZodFunction:we,ZodLazy:Ee,ZodLiteral:Oe,ZodEnum:ke,ZodNativeEnum:Ie,ZodPromise:Te,ZodEffects:xe,ZodTransformer:xe,ZodOptional:Se,ZodNullable:Ae,ZodDefault:je,ZodCatch:Pe,ZodNaN:Re,BRAND:Ne,ZodBranded:Ce,ZodPipeline:Le,ZodReadonly:Me,custom:De,Schema:T,ZodSchema:T,late:Fe,get ZodFirstPartyTypeKind(){return Ze},coerce:Et,any:Xe,array:tt,bigint:qe,boolean:Ge,date:Je,discriminatedUnion:it,effect:yt,enum:mt,function:ut,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>De((t=>t instanceof e),t),intersection:st,lazy:ht,literal:pt,map:dt,nan:He,nativeEnum:ft,never:Qe,null:Ke,nullable:bt,number:Be,object:rt,oboolean:()=>Ge().optional(),onumber:()=>Be().optional(),optional:_t,ostring:()=>ze().optional(),pipeline:wt,preprocess:vt,promise:gt,record:ct,set:lt,strictObject:at,string:ze,symbol:Ve,transformer:yt,tuple:ot,undefined:We,union:nt,unknown:Ye,void:et,NEVER:Ot,ZodIssueCode:n,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:i});function kt(e,t){const r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;const r=e.length;if(r!==t.length)return!1;for(let a=0;a<r;a++)if(!kt(e[a],t[a]))return!1;return!0}if("object"===r){if(!e||!t)return e===t;const r=Object.keys(e),a=Object.keys(t);if(r.length!==a.length)return!1;for(const a of r)if(!kt(e[a],t[a]))return!1;return!0}return e===t}function It(e){return encodeURI(function(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}(e))}const Tt={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},xt={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},St={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 At="undefined"!=typeof self&&self.location&&"null"!==self.location.origin?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function jt(e,t=Object.create(null),r=At,a=""){if(e&&"object"==typeof e&&!Array.isArray(e)){const n=e.$id||e.id;if(n){const i=new URL(n,r.href);i.hash.length>1?t[i.href]=e:(i.hash="",""===a?r=i:jt(e,t,r))}}else if(!0!==e&&!1!==e)return t;const n=r.href+(a?"#"+a:"");if(void 0!==t[n])throw new Error(`Duplicate schema URI "${n}".`);if(t[n]=e,!0===e||!1===e)return t;if(void 0===e.__absolute_uri__&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:n}),e.$ref&&void 0===e.__absolute_ref__){const t=new URL(e.$ref,r.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&void 0===e.__absolute_recursive_ref__){const t=new URL(e.$recursiveRef,r.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}if(e.$anchor){t[new URL("#"+e.$anchor,r.href).href]=e}for(let n in e){if(St[n])continue;const i=`${a}/${It(n)}`,s=e[n];if(Array.isArray(s)){if(Tt[n]){const e=s.length;for(let a=0;a<e;a++)jt(s[a],t,r,`${i}/${a}`)}}else if(xt[n])for(let e in s)jt(s[e],t,r,`${i}/${It(e)}`);else jt(s,t,r,i)}return t}const Pt=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Rt=[0,31,28,31,30,31,30,31,31,30,31,30,31],Nt=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;function Ct(e){return e.test.bind(e)}const Lt={date:Mt,time:Ut.bind(void 0,!1),"date-time":function(e){const t=e.split(Dt);return 2==t.length&&Mt(t[0])&&Ut(!0,t[1])},duration:e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),uri:function(e){return Ft.test(e)&&Zt.test(e)},"uri-reference":Ct(/^(?:[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),"uri-template":Ct(/^(?:(?:[^\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),url:Ct(/^(?:(?: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),email:e=>{if('"'===e[0])return!1;const[t,r,...a]=e.split("@");return!(!t||!r||0!==a.length||t.length>64||r.length>253)&&("."!==t[0]&&!t.endsWith(".")&&!t.includes("..")&&(!(!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t))&&r.split(".").every((e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e)))))},hostname:Ct(/^(?=.{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),ipv4:Ct(/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/),ipv6:Ct(/^((([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),regex:function(e){if(zt.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(e){return!1}},uuid:Ct(/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i),"json-pointer":Ct(/^(?:\/(?:[^~/]|~0|~1)*)*$/),"json-pointer-uri-fragment":Ct(/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i),"relative-json-pointer":Ct(/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/)};function Mt(e){const t=e.match(Pt);if(!t)return!1;const r=+t[1],a=+t[2],n=+t[3];return a>=1&&a<=12&&n>=1&&n<=(2==a&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(r)?29:Rt[a])}function Ut(e,t){const r=t.match(Nt);if(!r)return!1;const a=+r[1],n=+r[2],i=+r[3],s=!!r[5];return(a<=23&&n<=59&&i<=59||23==a&&59==n&&60==i)&&(!e||s)}const Dt=/t|\s/i;const Ft=/\/|:/,Zt=/^(?:[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;const zt=/[^\\]\\Z/;function Bt(e,t,r="2019-09",a=jt(t),n=!0,i=null,s="#",o="#",c=Object.create(null)){if(!0===t)return{valid:!0,errors:[]};if(!1===t)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};const d=typeof e;let l;switch(d){case"boolean":case"number":case"string":l=d;break;case"object":l=null===e?"null":Array.isArray(e)?"array":"object";break;default:throw new Error(`Instances of "${d}" type are not supported.`)}const{$ref:u,$recursiveRef:h,$recursiveAnchor:p,type:m,const:f,enum:g,required:y,not:_,anyOf:b,allOf:v,oneOf:w,if:E,then:O,else:$,format:k,properties:I,patternProperties:T,additionalProperties:x,unevaluatedProperties:S,minProperties:A,maxProperties:j,propertyNames:P,dependentRequired:R,dependentSchemas:N,dependencies:C,prefixItems:L,items:M,additionalItems:U,unevaluatedItems:D,contains:F,minContains:Z,maxContains:z,minItems:B,maxItems:H,uniqueItems:q,minimum:G,maximum:J,exclusiveMinimum:V,exclusiveMaximum:W,multipleOf:K,minLength:X,maxLength:Y,pattern:Q,__absolute_ref__:ee,__absolute_recursive_ref__:te}=t,re=[];if(!0===p&&null===i&&(i=t),"#"===h){const d=null===i?a[te]:i,l=`${o}/$recursiveRef`,u=Bt(e,null===i?t:i,r,a,n,d,s,l,c);u.valid||re.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:l,error:"A subschema had errors."},...u.errors)}if(void 0!==u){const t=a[ee||u];if(void 0===t){let e=`Unresolved $ref "${u}".`;throw ee&&ee!==u&&(e+=`  Absolute URI "${ee}".`),e+=`\nKnown schemas:\n- ${Object.keys(a).join("\n- ")}`,new Error(e)}const d=`${o}/$ref`,l=Bt(e,t,r,a,n,i,s,d,c);if(l.valid||re.push({instanceLocation:s,keyword:"$ref",keywordLocation:d,error:"A subschema had errors."},...l.errors),"4"===r||"7"===r)return{valid:0===re.length,errors:re}}if(Array.isArray(m)){let t=m.length,r=!1;for(let a=0;a<t;a++)if(l===m[a]||"integer"===m[a]&&"number"===l&&e%1==0&&e==e){r=!0;break}r||re.push({instanceLocation:s,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${m.join('", "')}".`})}else"integer"===m?("number"!==l||e%1||e!=e)&&re.push({instanceLocation:s,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${m}".`}):void 0!==m&&l!==m&&re.push({instanceLocation:s,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${m}".`});if(void 0!==f&&("object"===l||"array"===l?kt(e,f)||re.push({instanceLocation:s,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(f)}.`}):e!==f&&re.push({instanceLocation:s,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(f)}.`})),void 0!==g&&("object"===l||"array"===l?g.some((t=>kt(e,t)))||re.push({instanceLocation:s,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some((t=>e===t))||re.push({instanceLocation:s,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),void 0!==_){const t=`${o}/not`;Bt(e,_,r,a,n,i,s,t).valid&&re.push({instanceLocation:s,keyword:"not",keywordLocation:t,error:'Instance matched "not" schema.'})}let ae=[];if(void 0!==b){const t=`${o}/anyOf`,d=re.length;let l=!1;for(let o=0;o<b.length;o++){const d=b[o],u=Object.create(c),h=Bt(e,d,r,a,n,!0===p?i:null,s,`${t}/${o}`,u);re.push(...h.errors),l=l||h.valid,h.valid&&ae.push(u)}l?re.length=d:re.splice(d,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:t,error:"Instance does not match any subschemas."})}if(void 0!==v){const t=`${o}/allOf`,d=re.length;let l=!0;for(let o=0;o<v.length;o++){const d=v[o],u=Object.create(c),h=Bt(e,d,r,a,n,!0===p?i:null,s,`${t}/${o}`,u);re.push(...h.errors),l=l&&h.valid,h.valid&&ae.push(u)}l?re.length=d:re.splice(d,0,{instanceLocation:s,keyword:"allOf",keywordLocation:t,error:"Instance does not match every subschema."})}if(void 0!==w){const t=`${o}/oneOf`,d=re.length,l=w.filter(((o,d)=>{const l=Object.create(c),u=Bt(e,o,r,a,n,!0===p?i:null,s,`${t}/${d}`,l);return re.push(...u.errors),u.valid&&ae.push(l),u.valid})).length;1===l?re.length=d:re.splice(d,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:t,error:`Instance does not match exactly one subschema (${l} matches).`})}if("object"!==l&&"array"!==l||Object.assign(c,...ae),void 0!==E){const t=`${o}/if`;if(Bt(e,E,r,a,n,i,s,t,c).valid){if(void 0!==O){const d=Bt(e,O,r,a,n,i,s,`${o}/then`,c);d.valid||re.push({instanceLocation:s,keyword:"if",keywordLocation:t,error:'Instance does not match "then" schema.'},...d.errors)}}else if(void 0!==$){const d=Bt(e,$,r,a,n,i,s,`${o}/else`,c);d.valid||re.push({instanceLocation:s,keyword:"if",keywordLocation:t,error:'Instance does not match "else" schema.'},...d.errors)}}if("object"===l){if(void 0!==y)for(const t of y)t in e||re.push({instanceLocation:s,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${t}".`});const t=Object.keys(e);if(void 0!==A&&t.length<A&&re.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${A} properties.`}),void 0!==j&&t.length>j&&re.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${j} properties.`}),void 0!==P){const t=`${o}/propertyNames`;for(const o in e){const e=`${s}/${It(o)}`,c=Bt(o,P,r,a,n,i,e,t);c.valid||re.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:t,error:`Property name "${o}" does not match schema.`},...c.errors)}}if(void 0!==R){const t=`${o}/dependantRequired`;for(const r in R)if(r in e){const a=R[r];for(const n of a)n in e||re.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:t,error:`Instance has "${r}" but does not have "${n}".`})}}if(void 0!==N)for(const t in N){const d=`${o}/dependentSchemas`;if(t in e){const o=Bt(e,N[t],r,a,n,i,s,`${d}/${It(t)}`,c);o.valid||re.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:d,error:`Instance has "${t}" but does not match dependant schema.`},...o.errors)}}if(void 0!==C){const t=`${o}/dependencies`;for(const o in C)if(o in e){const c=C[o];if(Array.isArray(c))for(const r of c)r in e||re.push({instanceLocation:s,keyword:"dependencies",keywordLocation:t,error:`Instance has "${o}" but does not have "${r}".`});else{const d=Bt(e,c,r,a,n,i,s,`${t}/${It(o)}`);d.valid||re.push({instanceLocation:s,keyword:"dependencies",keywordLocation:t,error:`Instance has "${o}" but does not match dependant schema.`},...d.errors)}}}const d=Object.create(null);let l=!1;if(void 0!==I){const t=`${o}/properties`;for(const o in I){if(!(o in e))continue;const u=`${s}/${It(o)}`,h=Bt(e[o],I[o],r,a,n,i,u,`${t}/${It(o)}`);if(h.valid)c[o]=d[o]=!0;else if(l=n,re.push({instanceLocation:s,keyword:"properties",keywordLocation:t,error:`Property "${o}" does not match schema.`},...h.errors),l)break}}if(!l&&void 0!==T){const t=`${o}/patternProperties`;for(const o in T){const u=new RegExp(o,"u"),h=T[o];for(const p in e){if(!u.test(p))continue;const m=`${s}/${It(p)}`,f=Bt(e[p],h,r,a,n,i,m,`${t}/${It(o)}`);f.valid?c[p]=d[p]=!0:(l=n,re.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:t,error:`Property "${p}" matches pattern "${o}" but does not match associated schema.`},...f.errors))}}}if(l||void 0===x){if(!l&&void 0!==S){const t=`${o}/unevaluatedProperties`;for(const o in e)if(!c[o]){const d=`${s}/${It(o)}`,l=Bt(e[o],S,r,a,n,i,d,t);l.valid?c[o]=!0:re.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:t,error:`Property "${o}" does not match unevaluated properties schema.`},...l.errors)}}}else{const t=`${o}/additionalProperties`;for(const o in e){if(d[o])continue;const u=`${s}/${It(o)}`,h=Bt(e[o],x,r,a,n,i,u,t);h.valid?c[o]=!0:(l=n,re.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:t,error:`Property "${o}" does not match additional properties schema.`},...h.errors))}}}else if("array"===l){void 0!==H&&e.length>H&&re.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${e.length} > ${H}).`}),void 0!==B&&e.length<B&&re.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${e.length} < ${B}).`});const t=e.length;let d=0,l=!1;if(void 0!==L){const u=`${o}/prefixItems`,h=Math.min(L.length,t);for(;d<h;d++){const t=Bt(e[d],L[d],r,a,n,i,`${s}/${d}`,`${u}/${d}`);if(c[d]=!0,!t.valid&&(l=n,re.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:u,error:"Items did not match schema."},...t.errors),l))break}}if(void 0!==M){const u=`${o}/items`;if(Array.isArray(M)){const o=Math.min(M.length,t);for(;d<o;d++){const t=Bt(e[d],M[d],r,a,n,i,`${s}/${d}`,`${u}/${d}`);if(c[d]=!0,!t.valid&&(l=n,re.push({instanceLocation:s,keyword:"items",keywordLocation:u,error:"Items did not match schema."},...t.errors),l))break}}else for(;d<t;d++){const t=Bt(e[d],M,r,a,n,i,`${s}/${d}`,u);if(c[d]=!0,!t.valid&&(l=n,re.push({instanceLocation:s,keyword:"items",keywordLocation:u,error:"Items did not match schema."},...t.errors),l))break}if(!l&&void 0!==U){const u=`${o}/additionalItems`;for(;d<t;d++){const t=Bt(e[d],U,r,a,n,i,`${s}/${d}`,u);c[d]=!0,t.valid||(l=n,re.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:u,error:"Items did not match additional items schema."},...t.errors))}}}if(void 0!==F)if(0===t&&void 0===Z)re.push({instanceLocation:s,keyword:"contains",keywordLocation:`${o}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(void 0!==Z&&t<Z)re.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array has less items (${t}) than minContains (${Z}).`});else{const d=`${o}/contains`,l=re.length;let u=0;for(let o=0;o<t;o++){const t=Bt(e[o],F,r,a,n,i,`${s}/${o}`,d);t.valid?(c[o]=!0,u++):re.push(...t.errors)}u>=(Z||0)&&(re.length=l),void 0===Z&&void 0===z&&0===u?re.splice(l,0,{instanceLocation:s,keyword:"contains",keywordLocation:d,error:"Array does not contain item matching schema."}):void 0!==Z&&u<Z?re.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array must contain at least ${Z} items matching schema. Only ${u} items were found.`}):void 0!==z&&u>z&&re.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${z} items matching schema. ${u} items were found.`})}if(!l&&void 0!==D){const l=`${o}/unevaluatedItems`;for(;d<t;d++){if(c[d])continue;const t=Bt(e[d],D,r,a,n,i,`${s}/${d}`,l);c[d]=!0,t.valid||re.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:l,error:"Items did not match unevaluated items schema."},...t.errors)}}if(q)for(let r=0;r<t;r++){const a=e[r],n="object"==typeof a&&null!==a;for(let i=0;i<t;i++){if(r===i)continue;const t=e[i];(a===t||n&&("object"==typeof t&&null!==t)&&kt(a,t))&&(re.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${o}/uniqueItems`,error:`Duplicate items at indexes ${r} and ${i}.`}),r=Number.MAX_SAFE_INTEGER,i=Number.MAX_SAFE_INTEGER)}}}else if("number"===l){if("4"===r?(void 0!==G&&(!0===V&&e<=G||e<G)&&re.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${e} is less than ${V?"or equal to ":""} ${G}.`}),void 0!==J&&(!0===W&&e>=J||e>J)&&re.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${W?"or equal to ":""} ${J}.`})):(void 0!==G&&e<G&&re.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${e} is less than ${G}.`}),void 0!==J&&e>J&&re.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${J}.`}),void 0!==V&&e<=V&&re.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${e} is less than ${V}.`}),void 0!==W&&e>=W&&re.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${e} is greater than or equal to ${W}.`})),void 0!==K){const t=e%K;Math.abs(0-t)>=1.1920929e-7&&Math.abs(K-t)>=1.1920929e-7&&re.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${e} is not a multiple of ${K}.`})}}else if("string"===l){const t=void 0===X&&void 0===Y?0:function(e){let t,r=0,a=e.length,n=0;for(;n<a;)r++,t=e.charCodeAt(n++),t>=55296&&t<=56319&&n<a&&(t=e.charCodeAt(n),56320==(64512&t)&&n++);return r}(e);void 0!==X&&t<X&&re.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${t} < ${X}).`}),void 0!==Y&&t>Y&&re.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${t} > ${Y}).`}),void 0===Q||new RegExp(Q,"u").test(e)||re.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),void 0!==k&&Lt[k]&&!Lt[k](e)&&re.push({instanceLocation:s,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${k}".`})}return{valid:0===re.length,errors:re}}var Ht=/^(?:[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 qt(e){return"string"==typeof e&&Ht.test(e)}for(var Gt,Jt=[],Vt=0;Vt<256;++Vt)Jt.push((Vt+256).toString(16).slice(1));var Wt=new Uint8Array(16);function Kt(){if(!Gt&&!(Gt="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Gt(Wt)}var Xt={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Yt(e,t,r){if(Xt.randomUUID&&!t&&!e)return Xt.randomUUID();var a=(e=e||{}).random||(e.rng||Kt)();return a[6]=15&a[6]|64,a[8]=63&a[8]|128,function(e,t=0){return(Jt[e[t+0]]+Jt[e[t+1]]+Jt[e[t+2]]+Jt[e[t+3]]+"-"+Jt[e[t+4]]+Jt[e[t+5]]+"-"+Jt[e[t+6]]+Jt[e[t+7]]+"-"+Jt[e[t+8]]+Jt[e[t+9]]+"-"+Jt[e[t+10]]+Jt[e[t+11]]+Jt[e[t+12]]+Jt[e[t+13]]+Jt[e[t+14]]+Jt[e[t+15]]).toLowerCase()}(a)}function Qt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var er=Qt((function(e,t){if("string"!=typeof e)throw new TypeError("Expected a string");return t=void 0===t?"_":t,e.replace(/([a-z\d])([A-Z])/g,"$1"+t+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+t+"$2").toLowerCase()})),tr={exports:{}};const rr=/[\p{Lu}]/u,ar=/[\p{Ll}]/u,nr=/^[\p{Lu}](?![\p{Lu}])/gu,ir=/([\p{Alpha}\p{N}_]|$)/u,sr=/[_.\- ]+/,or=new RegExp("^"+sr.source),cr=new RegExp(sr.source+ir.source,"gu"),dr=new RegExp("\\d+"+ir.source,"gu"),lr=(e,t)=>{if("string"!=typeof e&&!Array.isArray(e))throw new TypeError("Expected the input to be `string | string[]`");if(t={pascalCase:!1,preserveConsecutiveUppercase:!1,...t},0===(e=Array.isArray(e)?e.map((e=>e.trim())).filter((e=>e.length)).join("-"):e.trim()).length)return"";const r=!1===t.locale?e=>e.toLowerCase():e=>e.toLocaleLowerCase(t.locale),a=!1===t.locale?e=>e.toUpperCase():e=>e.toLocaleUpperCase(t.locale);if(1===e.length)return t.pascalCase?a(e):r(e);return e!==r(e)&&(e=((e,t,r)=>{let a=!1,n=!1,i=!1;for(let s=0;s<e.length;s++){const o=e[s];a&&rr.test(o)?(e=e.slice(0,s)+"-"+e.slice(s),a=!1,i=n,n=!0,s++):n&&i&&ar.test(o)?(e=e.slice(0,s-1)+"-"+e.slice(s-1),i=n,n=!1,a=!0):(a=t(o)===o&&r(o)!==o,i=n,n=r(o)===o&&t(o)!==o)}return e})(e,r,a)),e=e.replace(or,""),e=t.preserveConsecutiveUppercase?((e,t)=>(nr.lastIndex=0,e.replace(nr,(e=>t(e)))))(e,r):r(e),t.pascalCase&&(e=a(e.charAt(0))+e.slice(1)),((e,t)=>(cr.lastIndex=0,dr.lastIndex=0,e.replace(cr,((e,r)=>t(r))).replace(dr,(e=>t(e)))))(e,a)};function ur(e,t){return t?.[e]||er(e)}function hr(e,t,r){const a={};for(const n in e)Object.hasOwn(e,n)&&(a[t(n,r)]=e[n]);return a}function pr(e){return Array.isArray(e)?[...e]:{...e}}function mr(e,t){const r=pr(e);for(const[e,a]of Object.entries(t)){const[t,...n]=e.split(".").reverse();let i=r;for(const e of n.reverse()){if(void 0===i[e])break;i[e]=pr(i[e]),i=i[e]}void 0!==i[t]&&(i[t]={lc:1,type:"secret",id:[a]})}return r}function fr(e){const t=Object.getPrototypeOf(e);return"function"==typeof e.lc_name&&("function"!=typeof t.lc_name||e.lc_name()!==t.lc_name())?e.lc_name():e.name}tr.exports=lr,tr.exports.default=lr;class gr{static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,fr(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...t){Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),void 0!==this.lc_serializable_keys?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter((([e])=>this.lc_serializable_keys?.includes(e)))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof gr||"object"!=typeof this.lc_kwargs||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},t={},r=Object.keys(this.lc_kwargs).reduce(((e,t)=>(e[t]=t in this?this[t]:this.lc_kwargs[t],e)),{});for(let a=Object.getPrototypeOf(this);a;a=Object.getPrototypeOf(a))Object.assign(e,Reflect.get(a,"lc_aliases",this)),Object.assign(t,Reflect.get(a,"lc_secrets",this)),Object.assign(r,Reflect.get(a,"lc_attributes",this));return Object.keys(t).forEach((e=>{let t=this,a=r;const[n,...i]=e.split(".").reverse();for(const e of i.reverse()){if(!(e in t)||void 0===t[e])return;e in a&&void 0!==a[e]||("object"==typeof t[e]&&null!=t[e]?a[e]={}:Array.isArray(t[e])&&(a[e]=[])),t=t[e],a=a[e]}n in t&&void 0!==t[n]&&(a[n]=a[n]||t[n])})),{lc:1,type:"constructor",id:this.lc_id,kwargs:hr(Object.keys(t).length?mr(r,t):r,ur,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}var yr="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function _r(){throw new Error("setTimeout has not been defined")}function br(){throw new Error("clearTimeout has not been defined")}var vr=_r,wr=br;function Er(e){if(vr===setTimeout)return setTimeout(e,0);if((vr===_r||!vr)&&setTimeout)return vr=setTimeout,setTimeout(e,0);try{return vr(e,0)}catch(t){try{return vr.call(null,e,0)}catch(t){return vr.call(this,e,0)}}}"function"==typeof yr.setTimeout&&(vr=setTimeout),"function"==typeof yr.clearTimeout&&(wr=clearTimeout);var Or,$r=[],kr=!1,Ir=-1;function Tr(){kr&&Or&&(kr=!1,Or.length?$r=Or.concat($r):Ir=-1,$r.length&&xr())}function xr(){if(!kr){var e=Er(Tr);kr=!0;for(var t=$r.length;t;){for(Or=$r,$r=[];++Ir<t;)Or&&Or[Ir].run();Ir=-1,t=$r.length}Or=null,kr=!1,function(e){if(wr===clearTimeout)return clearTimeout(e);if((wr===br||!wr)&&clearTimeout)return wr=clearTimeout,clearTimeout(e);try{return wr(e)}catch(t){try{return wr.call(null,e)}catch(t){return wr.call(this,e)}}}(e)}}function Sr(e,t){this.fun=e,this.array=t}Sr.prototype.run=function(){this.fun.apply(null,this.array)};function Ar(){}var jr=Ar,Pr=Ar,Rr=Ar,Nr=Ar,Cr=Ar,Lr=Ar,Mr=Ar;var Ur=yr.performance||{},Dr=Ur.now||Ur.mozNow||Ur.msNow||Ur.oNow||Ur.webkitNow||function(){return(new Date).getTime()};var Fr=new Date;var Zr={nextTick:function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];$r.push(new Sr(e,t)),1!==$r.length||kr||Er(xr)},title:"browser",browser:!0,env:{},argv:[],version:"",versions:{},on:jr,addListener:Pr,once:Rr,off:Nr,removeListener:Cr,removeAllListeners:Lr,emit:Mr,binding:function(e){throw new Error("process.binding is not supported")},cwd:function(){return"/"},chdir:function(e){throw new Error("process.chdir is not supported")},umask:function(){return 0},hrtime:function(e){var t=.001*Dr.call(Ur),r=Math.floor(t),a=Math.floor(t%1*1e9);return e&&(r-=e[0],(a-=e[1])<0&&(r--,a+=1e9)),[r,a]},platform:"browser",release:{},config:{},uptime:function(){return(new Date-Fr)/1e3}};const zr=()=>"undefined"!=typeof Deno,Br=()=>{let e;return e="undefined"!=typeof window&&void 0!==window.document?"browser":void 0===Zr.versions||void 0===Zr.versions.node||zr()?"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name?"webworker":"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"))?"jsdom":zr()?"deno":"other":"node",e};let Hr;async function qr(){if(void 0===Hr){const e=Br();Hr={library:"langchain-js",runtime:e}}return Hr}function Gr(e){try{return Zr.env?.[e]}catch(e){return}}class Jr{}class Vr extends Jr{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,fr(this.constructor)]}constructor(e){super(),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ignoreLLM",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreChain",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreAgent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreRetriever",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreCustomEvent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"raiseError",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"awaitHandlers",{enumerable:!0,configurable:!0,writable:!0,value:"false"===Gr("LANGCHAIN_CALLBACKS_BACKGROUND")}),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._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(e){return new class extends Vr{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:Yt()}),Object.assign(this,e)}}}}const Wr=e=>{const t=e;return void 0!==t&&"function"==typeof t.copy&&"string"==typeof t.name&&"boolean"==typeof t.awaitHandlers};var Kr={exports:{}};!function(e){const t=(e=0)=>t=>`[${38+e};5;${t}m`,r=(e=0)=>(t,r,a)=>`[${38+e};2;${t};${r};${a}m`;Object.defineProperty(e,"exports",{enumerable:!0,get:function(){const e=new Map,a={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]}};a.color.gray=a.color.blackBright,a.bgColor.bgGray=a.bgColor.bgBlackBright,a.color.grey=a.color.blackBright,a.bgColor.bgGrey=a.bgColor.bgBlackBright;for(const[t,r]of Object.entries(a)){for(const[t,n]of Object.entries(r))a[t]={open:`[${n[0]}m`,close:`[${n[1]}m`},r[t]=a[t],e.set(n[0],n[1]);Object.defineProperty(a,t,{value:r,enumerable:!1})}return Object.defineProperty(a,"codes",{value:e,enumerable:!1}),a.color.close="",a.bgColor.close="",a.color.ansi256=t(),a.color.ansi16m=r(),a.bgColor.ansi256=t(10),a.bgColor.ansi16m=r(10),Object.defineProperties(a,{rgbToAnsi256:{value:(e,t,r)=>e===t&&t===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(r/255*5),enumerable:!1},hexToRgb:{value:e=>{const t=/(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(e.toString(16));if(!t)return[0,0,0];let{colorString:r}=t.groups;3===r.length&&(r=r.split("").map((e=>e+e)).join(""));const a=Number.parseInt(r,16);return[a>>16&255,a>>8&255,255&a]},enumerable:!1},hexToAnsi256:{value:e=>a.rgbToAnsi256(...a.hexToRgb(e)),enumerable:!1}}),a}})}(Kr);var Xr=Qt(Kr.exports);function Yr(e,t){return e&&!Array.isArray(e)&&"object"==typeof e?e:{[t]:e}}function Qr(e){return"function"==typeof e._addRunToRunMap}class ea extends Vr{constructor(e){super(...arguments),Object.defineProperty(this,"runMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}copy(){return this}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`\n\n${e.stack}`:""):"string"==typeof e?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){const t=function(e,t,r){const a=r.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(e).toISOString().slice(0,-1)}${a}Z`.replace(/[-:.]/g,"")+t}(e.start_time,e.id,e.execution_order),r={...e};if(void 0!==r.parent_run_id){const e=this.runMap.get(r.parent_run_id);e&&(this._addChildRun(e,r),e.child_execution_order=Math.max(e.child_execution_order,r.child_execution_order),r.trace_id=e.trace_id,void 0!==e.dotted_order&&(r.dotted_order=[e.dotted_order,t].join(".")))}else r.trace_id=r.id,r.dotted_order=t;return this.runMap.set(r.id,r),r}async _endTrace(e){const t=void 0!==e.parent_run_id&&this.runMap.get(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),this.runMap.delete(e.id),await(this.onRunUpdate?.(e))}_getExecutionOrder(e){const t=void 0!==e&&this.runMap.get(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,r,a,n,i,s,o){const c=this._getExecutionOrder(a),d=Date.now(),l=s?{...n,metadata:s}:n,u={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:d,serialized:e,events:[{name:"start",time:new Date(d).toISOString()}],inputs:{prompts:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:l??{},tags:i||[]};return this._addRunToRunMap(u)}async handleLLMStart(e,t,r,a,n,i,s,o){const c=this.runMap.get(r)??this._createRunForLLMStart(e,t,r,a,n,i,s,o);return await(this.onRunCreate?.(c)),await(this.onLLMStart?.(c)),c}_createRunForChatModelStart(e,t,r,a,n,i,s,o){const c=this._getExecutionOrder(a),d=Date.now(),l=s?{...n,metadata:s}:n,u={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:d,serialized:e,events:[{name:"start",time:new Date(d).toISOString()}],inputs:{messages:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:l??{},tags:i||[]};return this._addRunToRunMap(u)}async handleChatModelStart(e,t,r,a,n,i,s,o){const c=this.runMap.get(r)??this._createRunForChatModelStart(e,t,r,a,n,i,s,o);return await(this.onRunCreate?.(c)),await(this.onLLMStart?.(c)),c}async handleLLMEnd(e,t,r,a,n){const i=this.runMap.get(t);if(!i||"llm"!==i?.run_type)throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.outputs=e,i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...n},await(this.onLLMEnd?.(i)),await this._endTrace(i),i}async handleLLMError(e,t,r,a,n){const i=this.runMap.get(t);if(!i||"llm"!==i?.run_type)throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...n},await(this.onLLMError?.(i)),await this._endTrace(i),i}_createRunForChainStart(e,t,r,a,n,i,s,o){const c=this._getExecutionOrder(a),d=Date.now(),l={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:d,serialized:e,events:[{name:"start",time:new Date(d).toISOString()}],inputs:t,execution_order:c,child_execution_order:c,run_type:s??"chain",child_runs:[],extra:i?{metadata:i}:{},tags:n||[]};return this._addRunToRunMap(l)}async handleChainStart(e,t,r,a,n,i,s,o){const c=this.runMap.get(r)??this._createRunForChainStart(e,t,r,a,n,i,s,o);return await(this.onRunCreate?.(c)),await(this.onChainStart?.(c)),c}async handleChainEnd(e,t,r,a,n){const i=this.runMap.get(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=Yr(e,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),void 0!==n?.inputs&&(i.inputs=Yr(n.inputs,"input")),await(this.onChainEnd?.(i)),await this._endTrace(i),i}async handleChainError(e,t,r,a,n){const i=this.runMap.get(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),void 0!==n?.inputs&&(i.inputs=Yr(n.inputs,"input")),await(this.onChainError?.(i)),await this._endTrace(i),i}_createRunForToolStart(e,t,r,a,n,i,s){const o=this._getExecutionOrder(a),c=Date.now(),d={id:r,name:s??e.id[e.id.length-1],parent_run_id:a,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:t},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:i?{metadata:i}:{},tags:n||[]};return this._addRunToRunMap(d)}async handleToolStart(e,t,r,a,n,i,s){const o=this.runMap.get(r)??this._createRunForToolStart(e,t,r,a,n,i,s);return await(this.onRunCreate?.(o)),await(this.onToolStart?.(o)),o}async handleToolEnd(e,t){const r=this.runMap.get(t);if(!r||"tool"!==r?.run_type)throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await(this.onToolEnd?.(r)),await this._endTrace(r),r}async handleToolError(e,t){const r=this.runMap.get(t);if(!r||"tool"!==r?.run_type)throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await(this.onToolError?.(r)),await this._endTrace(r),r}async handleAgentAction(e,t){const r=this.runMap.get(t);if(!r||"chain"!==r?.run_type)return;const a=r;a.actions=a.actions||[],a.actions.push(e),a.events.push({name:"agent_action",time:(new Date).toISOString(),kwargs:{action:e}}),await(this.onAgentAction?.(r))}async handleAgentEnd(e,t){const r=this.runMap.get(t);r&&"chain"===r?.run_type&&(r.events.push({name:"agent_end",time:(new Date).toISOString(),kwargs:{action:e}}),await(this.onAgentEnd?.(r)))}_createRunForRetrieverStart(e,t,r,a,n,i,s){const o=this._getExecutionOrder(a),c=Date.now(),d={id:r,name:s??e.id[e.id.length-1],parent_run_id:a,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:t},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:i?{metadata:i}:{},tags:n||[]};return this._addRunToRunMap(d)}async handleRetrieverStart(e,t,r,a,n,i,s){const o=this.runMap.get(r)??this._createRunForRetrieverStart(e,t,r,a,n,i,s);return await(this.onRunCreate?.(o)),await(this.onRetrieverStart?.(o)),o}async handleRetrieverEnd(e,t){const r=this.runMap.get(t);if(!r||"retriever"!==r?.run_type)throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await(this.onRetrieverEnd?.(r)),await this._endTrace(r),r}async handleRetrieverError(e,t){const r=this.runMap.get(t);if(!r||"retriever"!==r?.run_type)throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await(this.onRetrieverError?.(r)),await this._endTrace(r),r}async handleText(e,t){const r=this.runMap.get(t);r&&"chain"===r?.run_type&&(r.events.push({name:"text",time:(new Date).toISOString(),kwargs:{text:e}}),await(this.onText?.(r)))}async handleLLMNewToken(e,t,r,a,n,i){const s=this.runMap.get(r);if(!s||"llm"!==s?.run_type)throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return s.events.push({name:"new_token",time:(new Date).toISOString(),kwargs:{token:e,idx:t,chunk:i?.chunk}}),await(this.onLLMNewToken?.(s,e,{chunk:i?.chunk})),s}}function ta(e,t){return`${e.open}${t}${e.close}`}function ra(e,t){try{return JSON.stringify(e,null,2)}catch(e){return t}}function aa(e){return"string"==typeof e?e.trim():null==e?e:ra(e,e.toString())}function na(e){if(!e.end_time)return"";const t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}const{color:ia}=Xr;class sa extends ea{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"console_callback_handler"})}persistRun(e){return Promise.resolve()}getParents(e){const t=[];let r=e;for(;r.parent_run_id;){const e=this.runMap.get(r.parent_run_id);if(!e)break;t.push(e),r=e}return t}getBreadcrumbs(e){const t=[...this.getParents(e).reverse(),e].map(((e,t,r)=>{const a=`${e.execution_order}:${e.run_type}:${e.name}`;return t===r.length-1?ta(Xr.bold,a):a})).join(" > ");return ta(ia.grey,t)}onChainStart(e){const t=this.getBreadcrumbs(e);console.log(`${ta(ia.green,"[chain/start]")} [${t}] Entering Chain run with input: ${ra(e.inputs,"[inputs]")}`)}onChainEnd(e){const t=this.getBreadcrumbs(e);console.log(`${ta(ia.cyan,"[chain/end]")} [${t}] [${na(e)}] Exiting Chain run with output: ${ra(e.outputs,"[outputs]")}`)}onChainError(e){const t=this.getBreadcrumbs(e);console.log(`${ta(ia.red,"[chain/error]")} [${t}] [${na(e)}] Chain run errored with error: ${ra(e.error,"[error]")}`)}onLLMStart(e){const t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map((e=>e.trim()))}:e.inputs;console.log(`${ta(ia.green,"[llm/start]")} [${t}] Entering LLM run with input: ${ra(r,"[inputs]")}`)}onLLMEnd(e){const t=this.getBreadcrumbs(e);console.log(`${ta(ia.cyan,"[llm/end]")} [${t}] [${na(e)}] Exiting LLM run with output: ${ra(e.outputs,"[response]")}`)}onLLMError(e){const t=this.getBreadcrumbs(e);console.log(`${ta(ia.red,"[llm/error]")} [${t}] [${na(e)}] LLM run errored with error: ${ra(e.error,"[error]")}`)}onToolStart(e){const t=this.getBreadcrumbs(e);console.log(`${ta(ia.green,"[tool/start]")} [${t}] Entering Tool run with input: "${aa(e.inputs.input)}"`)}onToolEnd(e){const t=this.getBreadcrumbs(e);console.log(`${ta(ia.cyan,"[tool/end]")} [${t}] [${na(e)}] Exiting Tool run with output: "${aa(e.outputs?.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${ta(ia.red,"[tool/error]")} [${t}] [${na(e)}] Tool run errored with error: ${ra(e.error,"[error]")}`)}onRetrieverStart(e){const t=this.getBreadcrumbs(e);console.log(`${ta(ia.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${ra(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const t=this.getBreadcrumbs(e);console.log(`${ta(ia.cyan,"[retriever/end]")} [${t}] [${na(e)}] Exiting Retriever run with output: ${ra(e.outputs,"[outputs]")}`)}onRetrieverError(e){const t=this.getBreadcrumbs(e);console.log(`${ta(ia.red,"[retriever/error]")} [${t}] [${na(e)}] Retriever run errored with error: ${ra(e.error,"[error]")}`)}onAgentAction(e){const t=e,r=this.getBreadcrumbs(e);console.log(`${ta(ia.blue,"[agent/action]")} [${r}] Agent selected action: ${ra(t.actions[t.actions.length-1],"[action]")}`)}}function oa(e){return!(!e||"object"!=typeof e||!("type"in e)||"tool_call"!==e.type)}class ca extends Error{constructor(e,t){super(e),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=t}}function da(e){if(void 0===e)return null;try{return JSON.parse(e)}catch(e){}let t="";const r=[];let a=!1,n=!1;for(let i of e){if(a)'"'!==i||n?"\n"!==i||n?n="\\"===i&&!n:i="\\n":a=!1;else if('"'===i)a=!0,n=!1;else if("{"===i)r.push("}");else if("["===i)r.push("]");else if("}"===i||"]"===i){if(!r||r[r.length-1]!==i)return null;r.pop()}t+=i}a&&(t+='"');for(let e=r.length-1;e>=0;e-=1)t+=r[e];try{return JSON.parse(t)}catch(e){return null}}function la(e){return"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type&&"source_type"in e&&("url"===e.source_type||"base64"===e.source_type||"text"===e.source_type||"id"===e.source_type)}class ua extends gr{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}get text(){return"string"==typeof this.content?this.content:Array.isArray(this.content)?this.content.map((e=>"string"==typeof e?e:"text"===e.type?e.text:"")).join(""):""}getType(){return this._getType()}constructor(e,t){"string"==typeof e&&(e={content:e,additional_kwargs:t,response_metadata:{}}),e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","messages"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"content",{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,"additional_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.content=e.content,this.additional_kwargs=e.additional_kwargs,this.response_metadata=e.response_metadata,this.id=e.id}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}}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(null===e)return this;const t=(r=this._printableFields,a=Math.max(4,e),JSON.stringify(function e(t,r){if("object"!=typeof t||null==t)return t;if(r>=a)return Array.isArray(t)?"[Array]":"[Object]";if(Array.isArray(t))return t.map((t=>e(t,r+1)));const n={};for(const a of Object.keys(t))n[a]=e(t[a],r+1);return n}(r,0),null,2));var r,a;return`${this.constructor.lc_name()} ${t}`}}function ha(e,t){const r={...e};for(const[e,a]of Object.entries(t))if(null==r[e])r[e]=a;else{if(null==a)continue;if(typeof r[e]!=typeof a||Array.isArray(r[e])!==Array.isArray(a))throw new Error(`field[${e}] already exists in the message chunk, but with a different type.`);if("string"==typeof r[e]){if("type"===e)continue;r[e]+=a}else if("object"!=typeof r[e]||Array.isArray(r[e]))if(Array.isArray(r[e]))r[e]=pa(r[e],a);else{if(r[e]===a)continue;console.warn(`field[${e}] already exists in this message chunk and value has unsupported type.`)}else r[e]=ha(r[e],a)}return r}function pa(e,t){if(void 0!==e||void 0!==t){if(void 0===e||void 0===t)return e||t;{const r=[...e];for(const e of t)if("object"==typeof e&&"index"in e&&"number"==typeof e.index){const t=r.findIndex((t=>t.index===e.index));-1!==t?r[t]=ha(r[t],e):r.push(e)}else{if("object"==typeof e&&"text"in e&&""===e.text)continue;r.push(e)}return r}}}class ma extends ua{}class fa extends ua{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}constructor(e,t,r){"string"==typeof e&&(e={content:e,name:r,tool_call_id:t}),super(e),Object.defineProperty(this,"lc_direct_tool_output",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}_getType(){return"tool"}static isInstance(e){return"tool"===e._getType()}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}class ga extends ma{constructor(e){let t;if("string"==typeof e)t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(void 0===e.tool_call_chunks)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:void 0!==e.usage_metadata?e.usage_metadata:void 0};else{const r=[],a=[];for(const t of e.tool_call_chunks){let e={};try{if(e=da(t.args||"{}"),null===e||"object"!=typeof e||Array.isArray(e))throw new Error("Malformed tool call chunk args.");r.push({name:t.name??"",args:e,id:t.id,type:"tool_call"})}catch(e){a.push({name:t.name,args:t.args,id:t.id,error:"Malformed args.",type:"invalid_tool_call"})}}t={...e,tool_calls:r,invalid_tool_calls:a,usage_metadata:void 0!==e.usage_metadata?e.usage_metadata:void 0}}super(t),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tool_call_chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.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"}_getType(){return"ai"}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(e){const t={content:(r=this.content,a=e.content,"string"==typeof r?""===r?a:"string"==typeof a?r+a:Array.isArray(a)&&a.some((e=>la(e)))?[{type:"text",source_type:"text",text:r},...a]:[{type:"text",text:r},...a]:Array.isArray(a)?pa(r,a)??[...r,...a]:""===a?r:Array.isArray(r)&&r.some((e=>la(e)))?[...r,{type:"file",source_type:"text",text:a}]:[...r,{type:"text",text:a}]),additional_kwargs:ha(this.additional_kwargs,e.additional_kwargs),response_metadata:ha(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};var r,a;if(void 0!==this.tool_call_chunks||void 0!==e.tool_call_chunks){const r=pa(this.tool_call_chunks,e.tool_call_chunks);void 0!==r&&r.length>0&&(t.tool_call_chunks=r)}if(void 0!==this.usage_metadata||void 0!==e.usage_metadata){const r={...(void 0!==this.usage_metadata?.input_token_details?.audio||void 0!==e.usage_metadata?.input_token_details?.audio)&&{audio:(this.usage_metadata?.input_token_details?.audio??0)+(e.usage_metadata?.input_token_details?.audio??0)},...(void 0!==this.usage_metadata?.input_token_details?.cache_read||void 0!==e.usage_metadata?.input_token_details?.cache_read)&&{cache_read:(this.usage_metadata?.input_token_details?.cache_read??0)+(e.usage_metadata?.input_token_details?.cache_read??0)},...(void 0!==this.usage_metadata?.input_token_details?.cache_creation||void 0!==e.usage_metadata?.input_token_details?.cache_creation)&&{cache_creation:(this.usage_metadata?.input_token_details?.cache_creation??0)+(e.usage_metadata?.input_token_details?.cache_creation??0)}},a={...(void 0!==this.usage_metadata?.output_token_details?.audio||void 0!==e.usage_metadata?.output_token_details?.audio)&&{audio:(this.usage_metadata?.output_token_details?.audio??0)+(e.usage_metadata?.output_token_details?.audio??0)},...(void 0!==this.usage_metadata?.output_token_details?.reasoning||void 0!==e.usage_metadata?.output_token_details?.reasoning)&&{reasoning:(this.usage_metadata?.output_token_details?.reasoning??0)+(e.usage_metadata?.output_token_details?.reasoning??0)}},n=this.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},i=e.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},s={input_tokens:n.input_tokens+i.input_tokens,output_tokens:n.output_tokens+i.output_tokens,total_tokens:n.total_tokens+i.total_tokens,...Object.keys(r).length>0&&{input_token_details:r},...Object.keys(a).length>0&&{output_token_details:a}};t.usage_metadata=s}return new ga(t)}}var ya={exports:{}},_a={};function ba(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}var va=ba;ba.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},ba.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},ba.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var a=this;return this._timer=setTimeout((function(){a._attempts++,a._operationTimeoutCb&&(a._timeout=setTimeout((function(){a._operationTimeoutCb(a._attempts)}),a._operationTimeout),a._options.unref&&a._timeout.unref()),a._fn(a._attempts)}),r),this._options.unref&&this._timer.unref(),!0},ba.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout((function(){r._operationTimeoutCb()}),r._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},ba.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},ba.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},ba.prototype.start=ba.prototype.try,ba.prototype.errors=function(){return this._errors},ba.prototype.attempts=function(){return this._attempts},ba.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,a=0;a<this._errors.length;a++){var n=this._errors[a],i=n.message,s=(e[i]||0)+1;e[i]=s,s>=r&&(t=n,r=s)}return t},function(e){var t=va;e.operation=function(r){var a=e.timeouts(r);return new t(a,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var a=[],n=0;n<t.retries;n++)a.push(this.createTimeout(n,t));return e&&e.forever&&!a.length&&a.push(this.createTimeout(n,t)),a.sort((function(e,t){return e-t})),a},e.createTimeout=function(e,t){var r=t.randomize?Math.random()+1:1,a=Math.round(r*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return a=Math.min(a,t.maxTimeout)},e.wrap=function(t,r,a){if(r instanceof Array&&(a=r,r=null),!a)for(var n in a=[],t)"function"==typeof t[n]&&a.push(n);for(var i=0;i<a.length;i++){var s=a[i],o=t[s];t[s]=function(a){var n=e.operation(r),i=Array.prototype.slice.call(arguments,1),s=i.pop();i.push((function(e){n.retry(e)||(e&&(arguments[0]=n.mainError()),s.apply(this,arguments))})),n.attempt((function(){a.apply(t,i)}))}.bind(t,o),t[s].options=r}}}(_a);const wa=_a,Ea=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class Oa 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}}const $a=(e,t)=>new Promise(((r,a)=>{t={onFailedAttempt:()=>{},retries:10,...t};const n=wa.operation(t);n.attempt((async i=>{try{r(await e(i))}catch(e){if(!(e instanceof Error))return void a(new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`));if(e instanceof Oa)n.stop(),a(e.originalError);else if(e instanceof TypeError&&(s=e.message,!Ea.includes(s)))n.stop(),a(e);else{((e,t,r)=>{const a=r.retries-(t-1);e.attemptNumber=t,e.retriesLeft=a})(e,i,t);try{await t.onFailedAttempt(e)}catch(e){return void a(e)}n.retry(e)||a(n.mainError())}}var s}))}));ya.exports=$a,ya.exports.default=$a,ya.exports.AbortError=Oa;var ka=Qt(ya.exports),Ia={},Ta={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,r="~";function a(){}function n(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function i(e,t,a,i,s){if("function"!=typeof a)throw new TypeError("The listener must be a function");var o=new n(a,i||e,s),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],o]:e._events[c].push(o):(e._events[c]=o,e._eventsCount++),e}function s(e,t){0==--e._eventsCount?e._events=new a:delete e._events[t]}function o(){this._events=new a,this._eventsCount=0}Object.create&&(a.prototype=Object.create(null),(new a).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,a,n=[];if(0===this._eventsCount)return n;for(a in e=this._events)t.call(e,a)&&n.push(r?a.slice(1):a);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},o.prototype.listeners=function(e){var t=r?r+e:e,a=this._events[t];if(!a)return[];if(a.fn)return[a.fn];for(var n=0,i=a.length,s=new Array(i);n<i;n++)s[n]=a[n].fn;return s},o.prototype.listenerCount=function(e){var t=r?r+e:e,a=this._events[t];return a?a.fn?1:a.length:0},o.prototype.emit=function(e,t,a,n,i,s){var o=r?r+e:e;if(!this._events[o])return!1;var c,d,l=this._events[o],u=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),u){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,a),!0;case 4:return l.fn.call(l.context,t,a,n),!0;case 5:return l.fn.call(l.context,t,a,n,i),!0;case 6:return l.fn.call(l.context,t,a,n,i,s),!0}for(d=1,c=new Array(u-1);d<u;d++)c[d-1]=arguments[d];l.fn.apply(l.context,c)}else{var h,p=l.length;for(d=0;d<p;d++)switch(l[d].once&&this.removeListener(e,l[d].fn,void 0,!0),u){case 1:l[d].fn.call(l[d].context);break;case 2:l[d].fn.call(l[d].context,t);break;case 3:l[d].fn.call(l[d].context,t,a);break;case 4:l[d].fn.call(l[d].context,t,a,n);break;default:if(!c)for(h=1,c=new Array(u-1);h<u;h++)c[h-1]=arguments[h];l[d].fn.apply(l[d].context,c)}}return!0},o.prototype.on=function(e,t,r){return i(this,e,t,r,!1)},o.prototype.once=function(e,t,r){return i(this,e,t,r,!0)},o.prototype.removeListener=function(e,t,a,n){var i=r?r+e:e;if(!this._events[i])return this;if(!t)return s(this,i),this;var o=this._events[i];if(o.fn)o.fn!==t||n&&!o.once||a&&o.context!==a||s(this,i);else{for(var c=0,d=[],l=o.length;c<l;c++)(o[c].fn!==t||n&&!o[c].once||a&&o[c].context!==a)&&d.push(o[c]);d.length?this._events[i]=1===d.length?d[0]:d:s(this,i)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new a,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,e.exports=o}(Ta);var xa=Ta.exports,Sa={exports:{}};const Aa=(e,t)=>(t=t||(()=>{}),e.then((e=>new Promise((e=>{e(t())})).then((()=>e))),(e=>new Promise((e=>{e(t())})).then((()=>{throw e})))));let ja=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};const Pa=(e,t,r)=>new Promise(((a,n)=>{if("number"!=typeof t||t<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(t===1/0)return void a(e);const i=setTimeout((()=>{if("function"==typeof r){try{a(r())}catch(e){n(e)}return}const i=r instanceof Error?r:new ja("string"==typeof r?r:`Promise timed out after ${t} milliseconds`);"function"==typeof e.cancel&&e.cancel(),n(i)}),t);Aa(e.then(a,n),(()=>{clearTimeout(i)}))}));Sa.exports=Pa,Sa.exports.default=Pa,Sa.exports.TimeoutError=ja;var Ra=Sa.exports,Na={},Ca={};Object.defineProperty(Ca,"__esModule",{value:!0}),Ca.default=function(e,t,r){let a=0,n=e.length;for(;n>0;){const i=n/2|0;let s=a+i;r(e[s],t)<=0?(a=++s,n-=i+1):n=i}return a},Object.defineProperty(Na,"__esModule",{value:!0});const La=Ca;Na.default=class{constructor(){this._queue=[]}enqueue(e,t){const r={priority:(t=Object.assign({priority:0},t)).priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority)return void this._queue.push(r);const a=La.default(this._queue,r,((e,t)=>t.priority-e.priority));this._queue.splice(a,0,r)}dequeue(){const e=this._queue.shift();return null==e?void 0:e.run}filter(e){return this._queue.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this._queue.length}},Object.defineProperty(Ia,"__esModule",{value:!0});const Ma=xa,Ua=Ra,Da=Na,Fa=()=>{},Za=new Ua.TimeoutError;var za=Ia.default=class extends Ma{constructor(e){var t,r,a,n;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=Fa,this._resolveIdle=Fa,!("number"==typeof(e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:Da.default},e)).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!==(r=null===(t=e.intervalCap)||void 0===t?void 0:t.toString())&&void 0!==r?r:""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!==(n=null===(a=e.interval)||void 0===a?void 0:a.toString())&&void 0!==n?n:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||0===e.interval,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=!0===e.throwOnTimeout,this._isPaused=!1===e.autoStart}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=Fa,0===this._pendingCount&&(this._resolveIdle(),this._resolveIdle=Fa,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const e=Date.now();if(void 0===this._intervalId){const t=this._intervalEnd-e;if(!(t<0))return void 0===this._timeoutId&&(this._timeoutId=setTimeout((()=>{this._onResumeInterval()}),t)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}_tryToStartAnother(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const t=this._queue.dequeue();return!!t&&(this.emit("active"),t(),e&&this._initializeIntervalIfNeeded(),!0)}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval((()=>{this._onInterval()}),this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){0===this._intervalCount&&0===this._pendingCount&&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(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={}){return new Promise(((r,a)=>{this._queue.enqueue((async()=>{this._pendingCount++,this._intervalCount++;try{const n=void 0===this._timeout&&void 0===t.timeout?e():Ua.default(Promise.resolve(e()),void 0===t.timeout?this._timeout:t.timeout,(()=>{(void 0===t.throwOnTimeout?this._throwOnTimeout:t.throwOnTimeout)&&a(Za)}));r(await n)}catch(e){a(e)}this._next()}),t),this._tryToStartAnother(),this.emit("add")}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(0!==this._queue.size)return new Promise((e=>{const t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}}))}async onIdle(){if(0!==this._pendingCount||0!==this._queue.size)return new Promise((e=>{const t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}}))}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};const Ba=(...e)=>fetch(...e),Ha=Symbol.for("ls:fetch_implementation"),qa=e=>async(...t)=>{if(e||"true"===xi("DEBUG")){const[e,r]=t;console.log(`→ ${r?.method||"GET"} ${e}`)}const r=await(globalThis[Ha]??Ba)(...t);return(e||"true"===xi("DEBUG"))&&console.log(`← ${r.status} ${r.statusText} ${r.url}`),r},Ga=[400,401,403,404,405,406,407,408],Ja=[409];let Va=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,"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,"debug",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.debug=e.debug,this.queue="default"in za?new za.default({concurrency:this.maxConcurrency}):new za({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){const r=this.onFailedResponseHook;return this.queue.add((()=>ka((()=>e(...t).catch((e=>{throw e instanceof Error?e:new Error(e)}))),{async onFailedAttempt(e){if(e.message.startsWith("Cancel")||e.message.startsWith("TimeoutError")||e.message.startsWith("AbortError"))throw e;if("ECONNABORTED"===e?.code)throw e;const t=e?.response,a=t?.status;if(a){if(Ga.includes(+a))throw e;if(Ja.includes(+a))return;r&&await r(t)}},retries:this.maxRetries,randomize:!0})),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise(((t,r)=>{e.signal?.addEventListener("abort",(()=>{r(new Error("AbortError"))}))}))]):this.call(t,...r)}fetch(...e){return this.call((()=>qa(this.debug)(...e).then((e=>e.ok?e:Promise.reject(e)))))}};function Wa(e){return"function"==typeof e?._getType}function Ka(e){const t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}function Xa(e,t){if(!qt(e)){throw new Error(void 0!==t?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`)}return e}const Ya={};function Qa(e){Ya[e]||(console.warn(e),Ya[e]=!0)}var en={exports:{}};var tn={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||9007199254740991,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2};var rn=Zr.env&&Zr.env.NODE_DEBUG&&/\bsemver\b/i.test(Zr.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};!function(e,t){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:a,MAX_LENGTH:n}=tn,i=rn,s=(t=e.exports={}).re=[],o=t.safeRe=[],c=t.src=[],d=t.safeSrc=[],l=t.t={};let u=0;const h="[a-zA-Z0-9-]",p=[["\\s",1],["\\d",n],[h,a]],m=(e,t,r)=>{const a=(e=>{for(const[t,r]of p)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e})(t),n=u++;i(e,n,t),l[e]=n,c[n]=t,d[n]=a,s[n]=new RegExp(t,r?"g":void 0),o[n]=new RegExp(a,r?"g":void 0)};m("NUMERICIDENTIFIER","0|[1-9]\\d*"),m("NUMERICIDENTIFIERLOOSE","\\d+"),m("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${h}*`),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.NUMERICIDENTIFIER]}|${c[l.NONNUMERICIDENTIFIER]})`),m("PRERELEASEIDENTIFIERLOOSE",`(?:${c[l.NUMERICIDENTIFIERLOOSE]}|${c[l.NONNUMERICIDENTIFIER]})`),m("PRERELEASE",`(?:-(${c[l.PRERELEASEIDENTIFIER]}(?:\\.${c[l.PRERELEASEIDENTIFIER]})*))`),m("PRERELEASELOOSE",`(?:-?(${c[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[l.PRERELEASEIDENTIFIERLOOSE]})*))`),m("BUILDIDENTIFIER",`${h}+`),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),t.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),t.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),t.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*$")}(en,en.exports);var an=en.exports;const nn=Object.freeze({loose:!0}),sn=Object.freeze({});var on=e=>e?"object"!=typeof e?nn:e:sn;const cn=/^[0-9]+$/,dn=(e,t)=>{const r=cn.test(e),a=cn.test(t);return r&&a&&(e=+e,t=+t),e===t?0:r&&!a?-1:a&&!r?1:e<t?-1:1};var ln={compareIdentifiers:dn,rcompareIdentifiers:(e,t)=>dn(t,e)};const un=rn,{MAX_LENGTH:hn,MAX_SAFE_INTEGER:pn}=tn,{safeRe:mn,safeSrc:fn,t:gn}=an,yn=on,{compareIdentifiers:_n}=ln;var bn=class e{constructor(t,r){if(r=yn(r),t instanceof e){if(t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease)return t;t=t.version}else if("string"!=typeof t)throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>hn)throw new TypeError(`version is longer than ${hn} characters`);un("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;const a=t.trim().match(r.loose?mn[gn.LOOSE]:mn[gn.FULL]);if(!a)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+a[1],this.minor=+a[2],this.patch=+a[3],this.major>pn||this.major<0)throw new TypeError("Invalid major version");if(this.minor>pn||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>pn||this.patch<0)throw new TypeError("Invalid patch version");a[4]?this.prerelease=a[4].split(".").map((e=>{if(/^[0-9]+$/.test(e)){const t=+e;if(t>=0&&t<pn)return t}return e})):this.prerelease=[],this.build=a[5]?a[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(t){if(un("SemVer.compare",this.version,this.options,t),!(t instanceof e)){if("string"==typeof t&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),_n(this.major,t.major)||_n(this.minor,t.minor)||_n(this.patch,t.patch)}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{const e=this.prerelease[r],a=t.prerelease[r];if(un("prerelease compare",r,e,a),void 0===e&&void 0===a)return 0;if(void 0===a)return 1;if(void 0===e)return-1;if(e!==a)return _n(e,a)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{const e=this.build[r],a=t.build[r];if(un("build compare",r,e,a),void 0===e&&void 0===a)return 0;if(void 0===a)return 1;if(void 0===e)return-1;if(e!==a)return _n(e,a)}while(++r)}inc(e,t,r){if(e.startsWith("pre")){if(!t&&!1===r)throw new Error("invalid increment argument: identifier is empty");if(t){const e=new RegExp(`^${this.options.loose?fn[gn.PRERELEASELOOSE]:fn[gn.PRERELEASE]}$`),r=`-${t}`.match(e);if(!r||r[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,r),this.inc("pre",t,r);break;case"prerelease":0===this.prerelease.length&&this.inc("patch",t,r),this.inc("pre",t,r);break;case"release":if(0===this.prerelease.length)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":0===this.minor&&0===this.patch&&0!==this.prerelease.length||this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":0===this.patch&&0!==this.prerelease.length||this.minor++,this.patch=0,this.prerelease=[];break;case"patch":0===this.prerelease.length&&this.patch++,this.prerelease=[];break;case"pre":{const e=Number(r)?1:0;if(0===this.prerelease.length)this.prerelease=[e];else{let a=this.prerelease.length;for(;--a>=0;)"number"==typeof this.prerelease[a]&&(this.prerelease[a]++,a=-2);if(-1===a){if(t===this.prerelease.join(".")&&!1===r)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(t){let a=[t,e];!1===r&&(a=[t]),0===_n(this.prerelease[0],t)?isNaN(this.prerelease[1])&&(this.prerelease=a):this.prerelease=a}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};const vn=bn;var wn=(e,t,r)=>new vn(e,r).compare(new vn(t,r));const En=wn;var On=(e,t,r)=>En(e,t,r)>0;const $n=wn;var kn=(e,t,r)=>$n(e,t,r)<0;const In=wn;var Tn=(e,t,r)=>0===In(e,t,r);const xn=wn;var Sn=(e,t,r)=>0!==xn(e,t,r);const An=wn;var jn=(e,t,r)=>An(e,t,r)>=0;const Pn=wn;var Rn=(e,t,r)=>Pn(e,t,r)<=0;const Nn=Tn,Cn=Sn,Ln=On,Mn=jn,Un=kn,Dn=Rn;var Fn=(e,t,r,a)=>{switch(t){case"===":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e===r;case"!==":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e!==r;case"":case"=":case"==":return Nn(e,r,a);case"!=":return Cn(e,r,a);case">":return Ln(e,r,a);case">=":return Mn(e,r,a);case"<":return Un(e,r,a);case"<=":return Dn(e,r,a);default:throw new TypeError(`Invalid operator: ${t}`)}};const{safeRe:Zn,t:zn}=an;var Bn,Hn,qn,Gn,Jn=class{constructor(){this.max=1e3,this.map=new Map}get(e){const t=this.map.get(e);return void 0===t?void 0:(this.map.delete(e),this.map.set(e,t),t)}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&void 0!==t){if(this.map.size>=this.max){const e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}};function Vn(){if(Hn)return Bn;Hn=1;const e=/\s+/g;class t{constructor(r,i){if(i=a(i),r instanceof t)return r.loose===!!i.loose&&r.includePrerelease===!!i.includePrerelease?r:new t(r.raw,i);if(r instanceof n)return this.raw=r.value,this.set=[[r]],this.formatted=void 0,this;if(this.options=i,this.loose=!!i.loose,this.includePrerelease=!!i.includePrerelease,this.raw=r.trim().replace(e," "),this.set=this.raw.split("||").map((e=>this.parseRange(e.trim()))).filter((e=>e.length)),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const e=this.set[0];if(this.set=this.set.filter((e=>!m(e[0]))),0===this.set.length)this.set=[e];else if(this.set.length>1)for(const e of this.set)if(1===e.length&&f(e[0])){this.set=[e];break}}this.formatted=void 0}get range(){if(void 0===this.formatted){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");const t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=" "),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){const t=((this.options.includePrerelease&&h)|(this.options.loose&&p))+":"+e,a=r.get(t);if(a)return a;const s=this.options.loose,f=s?o[c.HYPHENRANGELOOSE]:o[c.HYPHENRANGE];e=e.replace(f,T(this.options.includePrerelease)),i("hyphen replace",e),e=e.replace(o[c.COMPARATORTRIM],d),i("comparator trim",e),e=e.replace(o[c.TILDETRIM],l),i("tilde trim",e),e=e.replace(o[c.CARETTRIM],u),i("caret trim",e);let g=e.split(" ").map((e=>y(e,this.options))).join(" ").split(/\s+/).map((e=>I(e,this.options)));s&&(g=g.filter((e=>(i("loose invalid filter",e,this.options),!!e.match(o[c.COMPARATORLOOSE]))))),i("range list",g);const _=new Map,b=g.map((e=>new n(e,this.options)));for(const e of b){if(m(e))return[e];_.set(e.value,e)}_.size>1&&_.has("")&&_.delete("");const v=[..._.values()];return r.set(t,v),v}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some((t=>g(t,r)&&e.set.some((e=>g(e,r)&&t.every((t=>e.every((e=>t.intersects(e,r)))))))))}test(e){if(!e)return!1;if("string"==typeof e)try{e=new s(e,this.options)}catch(e){return!1}for(let t=0;t<this.set.length;t++)if(x(this.set[t],e,this.options))return!0;return!1}}Bn=t;const r=new Jn,a=on,n=Wn(),i=rn,s=bn,{safeRe:o,t:c,comparatorTrimReplace:d,tildeTrimReplace:l,caretTrimReplace:u}=an,{FLAG_INCLUDE_PRERELEASE:h,FLAG_LOOSE:p}=tn,m=e=>"<0.0.0-0"===e.value,f=e=>""===e.value,g=(e,t)=>{let r=!0;const a=e.slice();let n=a.pop();for(;r&&a.length;)r=a.every((e=>n.intersects(e,t))),n=a.pop();return r},y=(e,t)=>(i("comp",e,t),e=w(e,t),i("caret",e),e=b(e,t),i("tildes",e),e=O(e,t),i("xrange",e),e=k(e,t),i("stars",e),e),_=e=>!e||"x"===e.toLowerCase()||"*"===e,b=(e,t)=>e.trim().split(/\s+/).map((e=>v(e,t))).join(" "),v=(e,t)=>{const r=t.loose?o[c.TILDELOOSE]:o[c.TILDE];return e.replace(r,((t,r,a,n,s)=>{let o;return i("tilde",e,t,r,a,n,s),_(r)?o="":_(a)?o=`>=${r}.0.0 <${+r+1}.0.0-0`:_(n)?o=`>=${r}.${a}.0 <${r}.${+a+1}.0-0`:s?(i("replaceTilde pr",s),o=`>=${r}.${a}.${n}-${s} <${r}.${+a+1}.0-0`):o=`>=${r}.${a}.${n} <${r}.${+a+1}.0-0`,i("tilde return",o),o}))},w=(e,t)=>e.trim().split(/\s+/).map((e=>E(e,t))).join(" "),E=(e,t)=>{i("caret",e,t);const r=t.loose?o[c.CARETLOOSE]:o[c.CARET],a=t.includePrerelease?"-0":"";return e.replace(r,((t,r,n,s,o)=>{let c;return i("caret",e,t,r,n,s,o),_(r)?c="":_(n)?c=`>=${r}.0.0${a} <${+r+1}.0.0-0`:_(s)?c="0"===r?`>=${r}.${n}.0${a} <${r}.${+n+1}.0-0`:`>=${r}.${n}.0${a} <${+r+1}.0.0-0`:o?(i("replaceCaret pr",o),c="0"===r?"0"===n?`>=${r}.${n}.${s}-${o} <${r}.${n}.${+s+1}-0`:`>=${r}.${n}.${s}-${o} <${r}.${+n+1}.0-0`:`>=${r}.${n}.${s}-${o} <${+r+1}.0.0-0`):(i("no pr"),c="0"===r?"0"===n?`>=${r}.${n}.${s}${a} <${r}.${n}.${+s+1}-0`:`>=${r}.${n}.${s}${a} <${r}.${+n+1}.0-0`:`>=${r}.${n}.${s} <${+r+1}.0.0-0`),i("caret return",c),c}))},O=(e,t)=>(i("replaceXRanges",e,t),e.split(/\s+/).map((e=>$(e,t))).join(" ")),$=(e,t)=>{e=e.trim();const r=t.loose?o[c.XRANGELOOSE]:o[c.XRANGE];return e.replace(r,((r,a,n,s,o,c)=>{i("xRange",e,r,a,n,s,o,c);const d=_(n),l=d||_(s),u=l||_(o),h=u;return"="===a&&h&&(a=""),c=t.includePrerelease?"-0":"",d?r=">"===a||"<"===a?"<0.0.0-0":"*":a&&h?(l&&(s=0),o=0,">"===a?(a=">=",l?(n=+n+1,s=0,o=0):(s=+s+1,o=0)):"<="===a&&(a="<",l?n=+n+1:s=+s+1),"<"===a&&(c="-0"),r=`${a+n}.${s}.${o}${c}`):l?r=`>=${n}.0.0${c} <${+n+1}.0.0-0`:u&&(r=`>=${n}.${s}.0${c} <${n}.${+s+1}.0-0`),i("xRange return",r),r}))},k=(e,t)=>(i("replaceStars",e,t),e.trim().replace(o[c.STAR],"")),I=(e,t)=>(i("replaceGTE0",e,t),e.trim().replace(o[t.includePrerelease?c.GTE0PRE:c.GTE0],"")),T=e=>(t,r,a,n,i,s,o,c,d,l,u,h)=>`${r=_(a)?"":_(n)?`>=${a}.0.0${e?"-0":""}`:_(i)?`>=${a}.${n}.0${e?"-0":""}`:s?`>=${r}`:`>=${r}${e?"-0":""}`} ${c=_(d)?"":_(l)?`<${+d+1}.0.0-0`:_(u)?`<${d}.${+l+1}.0-0`:h?`<=${d}.${l}.${u}-${h}`:e?`<${d}.${l}.${+u+1}-0`:`<=${c}`}`.trim(),x=(e,t,r)=>{for(let r=0;r<e.length;r++)if(!e[r].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let r=0;r<e.length;r++)if(i(e[r].semver),e[r].semver!==n.ANY&&e[r].semver.prerelease.length>0){const a=e[r].semver;if(a.major===t.major&&a.minor===t.minor&&a.patch===t.patch)return!0}return!1}return!0};return Bn}function Wn(){if(Gn)return qn;Gn=1;const e=Symbol("SemVer ANY");class t{static get ANY(){return e}constructor(a,n){if(n=r(n),a instanceof t){if(a.loose===!!n.loose)return a;a=a.value}a=a.trim().split(/\s+/).join(" "),s("comparator",a,n),this.options=n,this.loose=!!n.loose,this.parse(a),this.semver===e?this.value="":this.value=this.operator+this.semver.version,s("comp",this)}parse(t){const r=this.options.loose?a[n.COMPARATORLOOSE]:a[n.COMPARATOR],i=t.match(r);if(!i)throw new TypeError(`Invalid comparator: ${t}`);this.operator=void 0!==i[1]?i[1]:"","="===this.operator&&(this.operator=""),i[2]?this.semver=new o(i[2],this.options.loose):this.semver=e}toString(){return this.value}test(t){if(s("Comparator.test",t,this.options.loose),this.semver===e||t===e)return!0;if("string"==typeof t)try{t=new o(t,this.options)}catch(e){return!1}return i(t,this.operator,this.semver,this.options)}intersects(e,a){if(!(e instanceof t))throw new TypeError("a Comparator is required");return""===this.operator?""===this.value||new c(e.value,a).test(this.value):""===e.operator?""===e.value||new c(this.value,a).test(e.semver):(!(a=r(a)).includePrerelease||"<0.0.0-0"!==this.value&&"<0.0.0-0"!==e.value)&&(!(!a.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0")))&&(!(!this.operator.startsWith(">")||!e.operator.startsWith(">"))||(!(!this.operator.startsWith("<")||!e.operator.startsWith("<"))||(!(this.semver.version!==e.semver.version||!this.operator.includes("=")||!e.operator.includes("="))||(!!(i(this.semver,"<",e.semver,a)&&this.operator.startsWith(">")&&e.operator.startsWith("<"))||!!(i(this.semver,">",e.semver,a)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))))))}}qn=t;const r=on,{safeRe:a,t:n}=an,i=Fn,s=rn,o=bn,c=Vn();return qn}Vn();Vn();Vn();Vn();Vn();Vn();const Kn=Wn(),{ANY:Xn}=Kn;Vn();Vn();Vn();const Yn=Wn(),{ANY:Qn}=Yn;new Yn(">=0.0.0-0"),new Yn(">=0.0.0");const ei=an;Wn(),Vn();function ti(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw new Error(`Invalid identifier format: ${e}`);const[t,r]=e.split(":"),a=r||"latest";if(t.includes("/")){const[r,n]=t.split("/",2);if(!r||!n)throw new Error(`Invalid identifier format: ${e}`);return[r,n,a]}if(!t)throw new Error(`Invalid identifier format: ${e}`);return["-",t,a]}ei.re,ei.src,ei.t;class ri extends Error{constructor(e){super(e),this.name="LangSmithConflictError"}}async function ai(e,t,r){let a;if(e.ok)return void(r&&(a=await e.text()));a=await e.text();const n=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Server response: ${a}`;if(409===e.status)throw new ri(n);throw new Error(n)}var ni="[...]",ii={result:"[Circular]"},si=[],oi=[];const ci=new TextEncoder;function di(e){return ci.encode(e)}function li(e,t,r,a){try{return di(JSON.stringify(e,t,r))}catch(n){if(!n.message?.includes("Converting circular structure to JSON"))return console.warn("[WARNING]: LangSmith received unserializable value."),di("[Unserializable]");let i;console.warn("[WARNING]: LangSmith received circular JSON. This will decrease tracer performance."),void 0===a&&(a={depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}),hi(e,"",0,[],void 0,0,a);try{i=0===oi.length?JSON.stringify(e,t,r):JSON.stringify(e,function(e){return e=void 0!==e?e:function(e,t){return t},function(t,r){if(oi.length>0)for(var a=0;a<oi.length;a++){var n=oi[a];if(n[1]===t&&n[0]===r){r=n[2],oi.splice(a,1);break}}return e.call(this,t,r)}}(t),r)}catch(e){return di("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==si.length;){const e=si.pop();4===e.length?Object.defineProperty(e[0],e[1],e[3]):e[0][e[1]]=e[2]}}return di(i)}}function ui(e,t,r,a){var n=Object.getOwnPropertyDescriptor(a,r);void 0!==n.get?n.configurable?(Object.defineProperty(a,r,{value:e}),si.push([a,r,t,n])):oi.push([t,r,e]):(a[r]=e,si.push([a,r,t]))}function hi(e,t,r,a,n,i,s){var o;if(i+=1,"object"==typeof e&&null!==e){for(o=0;o<a.length;o++)if(a[o]===e)return void ui(ii,e,t,n);if(void 0!==s.depthLimit&&i>s.depthLimit)return void ui(ni,e,t,n);if(void 0!==s.edgesLimit&&r+1>s.edgesLimit)return void ui(ni,e,t,n);if(a.push(e),Array.isArray(e))for(o=0;o<e.length;o++)hi(e[o],o,o,a,e,i,s);else{var c=Object.keys(e);for(o=0;o<c.length;o++){var d=c[o];hi(e[d],d,o,a,e,i,s)}}a.pop()}}function pi(e){const t=Ii(),r=function(){const e=function(){try{return Zr.env?Object.entries(Zr.env).reduce(((e,[t,r])=>(e[t]=String(r),e)),{}):void 0}catch(e){return}}()||{},t={},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[a,n]of Object.entries(e))!a.startsWith("LANGCHAIN_")&&!a.startsWith("LANGSMITH_")||"string"!=typeof n||r.includes(a)||a.toLowerCase().includes("key")||a.toLowerCase().includes("secret")||a.toLowerCase().includes("token")||("LANGCHAIN_REVISION_ID"===a?t.revision_id=n:t[a]=n);return t}(),a=e.extra??{},n=a.metadata;return e.extra={...a,runtime:{...t,...a?.runtime},metadata:{...r,...r.revision_id||e.revision_id?{revision_id:e.revision_id??r.revision_id}:{},...n}},e}function mi(e){if(void 0!==e)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const fi=async e=>{if(429===e?.status){const t=1e3*parseInt(e.headers.get("retry-after")??"30",10);if(t>0)return await new Promise((e=>setTimeout(e,t))),!0}return!1};function gi(e){return"number"==typeof e?Number(e.toFixed(4)):e}class yi{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(e){let t;const r=new Promise((e=>{t=e})),a=li(e.item).length;return this.items.push({action:e.action,payload:e.item,itemPromiseResolve:t,itemPromise:r,size:a}),this.sizeBytes+=a,r}pop(e){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const t=[];let r=0;for(;r+(this.peek()?.size??0)<e&&this.items.length>0;){const e=this.items.shift();e&&(t.push(e),r+=e.size,this.sizeBytes-=e.size)}if(0===t.length&&this.items.length>0){const e=this.items.shift();t.push(e),r+=e.size,this.sizeBytes-=e.size}return[t.map((e=>({action:e.action,item:e.payload}))),()=>t.forEach((e=>e.itemPromiseResolve()))]}}class _i{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,"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,"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:new yi}),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,"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:"false"===Ti("LANGSMITH_TRACING_BACKGROUND")}),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,"debug",{enumerable:!0,configurable:!0,writable:!0,value:"true"===Ti("LANGSMITH_DEBUG")});const t=_i.getDefaultClientConfig();if(this.tracingSampleRate=(e=>{const t=e?.toString()??xi("TRACING_SAMPLING_RATE");if(void 0===t)return;const r=parseFloat(t);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r})(e.tracingSamplingRate),this.apiUrl=mi(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=mi(e.apiKey??t.apiKey),this.webUrl=mi(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.timeout_ms=e.timeout_ms??9e4,this.caller=new Va({...e.callerOptions??{},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.batchIngestCaller=new Va({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:fi,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??t.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??t.hideOutputs,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode}static getDefaultClientConfig(){const e=xi("API_KEY");return{apiUrl:xi("ENDPOINT")??"https://api.smith.langchain.com",apiKey:e,webUrl:void 0,hideInputs:"true"===xi("HIDE_INPUTS"),hideOutputs:"true"===xi("HIDE_OUTPUTS")}}getHostUrl(){return this.webUrl?this.webUrl:(e=>{const t=e.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return"localhost"===t||"127.0.0.1"===t||"::1"===t})(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/${vi}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),e}async processInputs(e){return!1===this.hideInputs?e:!0===this.hideInputs?{}:"function"==typeof this.hideInputs?this.hideInputs(e):e}async processOutputs(e){return!1===this.hideOutputs?e:!0===this.hideOutputs?{}:"function"==typeof this.hideOutputs?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){const t={...e};return void 0!==t.inputs&&(t.inputs=await this.processInputs(t.inputs)),void 0!==t.outputs&&(t.outputs=await this.processOutputs(t.outputs)),t}async _getResponse(e,t){const r=t?.toString()??"",a=`${this.apiUrl}${e}?${r}`,n=await this.caller.call(qa(this.debug),a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ai(n,`Failed to fetch ${e}`),n}async _get(e,t){return(await this._getResponse(e,t)).json()}async*_getPaginated(e,t=new URLSearchParams,r){let a=Number(t.get("offset"))||0;const n=Number(t.get("limit"))||100;for(;;){t.set("offset",String(a)),t.set("limit",String(n));const i=`${this.apiUrl}${e}?${t}`,s=await this.caller.call(qa(this.debug),i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(s,`Failed to fetch ${e}`);const o=r?r(await s.json()):await s.json();if(0===o.length)break;if(yield o,o.length<n)break;a+=o.length}}async*_getCursorPaginatedList(e,t=null,r="POST",a="runs"){const n=t?{...t}:{};for(;;){const t=await this.caller.call(qa(this.debug),`${this.apiUrl}${e}`,{method:r,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(n)}),i=await t.json();if(!i)break;if(!i[a])break;yield i[a];const s=i.cursors;if(!s)break;if(!s.next)break;n.cursor=s.next}}_shouldSample(){return void 0===this.tracingSampleRate||Math.random()<this.tracingSampleRate}_filterForSampling(e,t=!1){if(void 0===this.tracingSampleRate)return e;if(t){const t=[];for(const r of e)this.filteredPostUuids.has(r.id)?this.filteredPostUuids.delete(r.id):t.push(r);return t}{const t=[];for(const r of e){const e=r.trace_id??r.id;this.filteredPostUuids.has(e)||(r.id===e?this._shouldSample()?t.push(r):this.filteredPostUuids.add(e):t.push(r))}return t}}async _getBatchSizeLimitBytes(){const e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e.batch_ingest_config?.size_limit_bytes??20971520}async _getMultiPartSupport(){const e=await this._ensureServerInfo();return e.instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue(e){const t=[];for(;this.autoBatchQueue.items.length>0;){const[r,a]=this.autoBatchQueue.pop(e);if(!r.length){a();break}const n=this._processBatch(r,a).catch(console.error);t.push(n)}return Promise.all(t)}async _processBatch(e,t){if(e.length)try{const t={runCreates:e.filter((e=>"create"===e.action)).map((e=>e.item)),runUpdates:e.filter((e=>"update"===e.action)).map((e=>e.item))},r=await this._ensureServerInfo();r?.batch_ingest_config?.use_multipart_endpoint?await this.multipartIngestRuns(t):await this.batchIngestRuns(t)}finally{t()}else t()}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,"create"===e.action&&(e.item=pi(e.item));const t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;const r=await this._getBatchSizeLimitBytes();return this.autoBatchQueue.sizeBytes>r&&this.drainAutoBatchQueue(r),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout((()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue(r)}),this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){const e=await qa(this.debug)(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(2500),...this.fetchOptions});await ai(e,"get server info");const t=await e.json();return this.debug&&console.log("\n=== LangSmith Server Configuration ===\n"+JSON.stringify(t,null,2)+"\n"),t}async _ensureServerInfo(){return void 0===this._getServerInfoPromise&&(this._getServerInfoPromise=(async()=>{if(void 0===this._serverInfo)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn("[WARNING]: LangSmith failed to fetch info on supported operations. Falling back to batch operations and default limits.")}return this._serverInfo??{}})()),this._getServerInfoPromise.then((e=>(void 0===this._serverInfo&&(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();await this.drainAutoBatchQueue(e)}async createRun(e){if(!this._filterForSampling([e]).length)return;const t={...this.headers,"Content-Type":"application/json"},r=e.project_name;delete e.project_name;const a=await this.prepareRunCreateOrUpdateInputs({session_name:r,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&void 0!==a.trace_id&&void 0!==a.dotted_order)return void this.processRunOperation({action:"create",item:a}).catch(console.error);const n=pi(a),i=await this.caller.call(qa(this.debug),`${this.apiUrl}/runs`,{method:"POST",headers:t,body:li(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(i,"create run",!0)}async batchIngestRuns({runCreates:e,runUpdates:t}){if(void 0===e&&void 0===t)return;let r=await Promise.all(e?.map((e=>this.prepareRunCreateOrUpdateInputs(e)))??[]),a=await Promise.all(t?.map((e=>this.prepareRunCreateOrUpdateInputs(e)))??[]);if(r.length>0&&a.length>0){const e=r.reduce(((e,t)=>t.id?(e[t.id]=t,e):e),{}),t=[];for(const r of a)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);r=Object.values(e),a=t}const n={post:r,patch:a};if(!n.post.length&&!n.patch.length)return;const i={post:[],patch:[]};for(const e of["post","patch"]){const t=e,r=n[t].reverse();let a=r.pop();for(;void 0!==a;)i[t].push(a),a=r.pop()}(i.post.length>0||i.patch.length>0)&&await this._postBatchIngestRuns(li(i))}async _postBatchIngestRuns(e){const t={...this.headers,"Content-Type":"application/json",Accept:"application/json"},r=await this.batchIngestCaller.call(qa(this.debug),`${this.apiUrl}/runs/batch`,{method:"POST",headers:t,body:e,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(r,"batch create run",!0)}async multipartIngestRuns({runCreates:e,runUpdates:t}){if(void 0===e&&void 0===t)return;const r={};let a=[];for(const t of e??[]){const e=await this.prepareRunCreateOrUpdateInputs(t);void 0!==e.id&&void 0!==e.attachments&&(r[e.id]=e.attachments),delete e.attachments,a.push(e)}let n=[];for(const e of t??[])n.push(await this.prepareRunCreateOrUpdateInputs(e));if(void 0!==a.find((e=>void 0===e.trace_id||void 0===e.dotted_order)))throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(void 0!==n.find((e=>void 0===e.trace_id||void 0===e.dotted_order)))throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(a.length>0&&n.length>0){const e=a.reduce(((e,t)=>t.id?(e[t.id]=t,e):e),{}),t=[];for(const r of n)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);a=Object.values(e),n=t}if(0===a.length&&0===n.length)return;const i=[],s=[];for(const[e,t]of[["post",a],["patch",n]])for(const a of t){const{inputs:t,outputs:n,events:o,attachments:c,...d}=a,l={inputs:t,outputs:n,events:o},u=li(d);s.push({name:`${e}.${d.id}`,payload:new Blob([u],{type:`application/json; length=${u.length}`})});for(const[t,r]of Object.entries(l)){if(void 0===r)continue;const a=li(r);s.push({name:`${e}.${d.id}.${t}`,payload:new Blob([a],{type:`application/json; length=${a.length}`})})}if(void 0!==d.id){const e=r[d.id];if(e){delete r[d.id];for(const[t,r]of Object.entries(e)){let e,a;Array.isArray(r)?[e,a]=r:(e=r.mimeType,a=r.data),t.includes(".")?console.warn(`Skipping attachment '${t}' for run ${d.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`):s.push({name:`attachment.${d.id}.${t}`,payload:new Blob([a],{type:`${e}; length=${a.byteLength}`})})}}}i.push(`trace=${d.trace_id},id=${d.id}`)}await this._sendMultipartRequest(s,i.join("; "))}async _sendMultipartRequest(e,t){try{const t="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),r=[];for(const a of e)r.push(new Blob([`--${t}\r\n`])),r.push(new Blob([`Content-Disposition: form-data; name="${a.name}"\r\n`,`Content-Type: ${a.payload.type}\r\n\r\n`])),r.push(a.payload),r.push(new Blob(["\r\n"]));r.push(new Blob([`--${t}--\r\n`]));const a=new Blob(r),n=await a.arrayBuffer(),i=await this.batchIngestCaller.call(qa(this.debug),`${this.apiUrl}/runs/multipart`,{method:"POST",headers:{...this.headers,"Content-Type":`multipart/form-data; boundary=${t}`},body:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(i,"ingest multipart runs",!0)}catch(e){console.warn(`${e.message.trim()}\n\nContext: ${t}`)}}async updateRun(e,t){Xa(e),t.inputs&&(t.inputs=await this.processInputs(t.inputs)),t.outputs&&(t.outputs=await this.processOutputs(t.outputs));const r={...t,id:e};if(!this._filterForSampling([r],!0).length)return;if(this.autoBatchTracing&&void 0!==r.trace_id&&void 0!==r.dotted_order)return void 0!==t.end_time&&void 0===r.parent_run_id&&this.blockOnRootRunFinalization&&!this.manualFlushMode?void await this.processRunOperation({action:"update",item:r}).catch(console.error):void this.processRunOperation({action:"update",item:r}).catch(console.error);const a={...this.headers,"Content-Type":"application/json"},n=await this.caller.call(qa(this.debug),`${this.apiUrl}/runs/${e}`,{method:"PATCH",headers:a,body:li(t),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(n,"update run",!0)}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){Xa(e);let r=await this._get(`/runs/${e}`);return t&&r.child_run_ids&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:t,projectOpts:r}){if(void 0!==t){let e;if(t.session_id)e=t.session_id;else if(r?.projectName)e=(await this.readProject({projectName:r?.projectName})).id;else if(r?.projectId)e=r?.projectId;else{e=(await this.readProject({projectName:xi("PROJECT")||"default"})).id}const a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${e}/r/${t.id}?poll=true`}if(void 0!==e){const t=await this.readRun(e);if(!t.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${t.app_path}`}throw new Error("Must provide either runId or run")}async _loadChildRuns(e){const t=await async function(e){const t=[];for await(const r of e)t.push(r);return t}(this.listRuns({id:e.child_run_ids})),r={},a={};t.sort(((e,t)=>(e?.dotted_order??"").localeCompare(t?.dotted_order??"")));for(const e of t){if(null===e.parent_run_id||void 0===e.parent_run_id)throw new Error(`Child run ${e.id} has no parent`);e.parent_run_id in r||(r[e.parent_run_id]=[]),r[e.parent_run_id].push(e),a[e.id]=e}e.child_runs=r[e.id]||[];for(const t in r)t!==e.id&&(a[t].child_runs=r[t]);return e}async*listRuns(e){const{projectId:t,projectName:r,parentRunId:a,traceId:n,referenceExampleId:i,startTime:s,executionOrder:o,isRoot:c,runType:d,error:l,id:u,query:h,filter:p,traceFilter:m,treeFilter:f,limit:g,select:y}=e;let _=[];if(t&&(_=Array.isArray(t)?t:[t]),r){const e=Array.isArray(r)?r:[r],t=await Promise.all(e.map((e=>this.readProject({projectName:e}).then((e=>e.id)))));_.push(...t)}const b={session:_.length?_:null,run_type:d,reference_example:i,query:h,filter:p,trace_filter:m,tree_filter:f,execution_order:o,parent_run:a,start_time:s?s.toISOString():null,error:l,id:u,limit:g,trace:n,select:y||["app_path","child_run_ids","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"],is_root:c};let v=0;for await(const e of this._getCursorPaginatedList("/runs/query",b))if(g){if(v>=g)break;if(e.length+v>g){const t=e.slice(0,g-v);yield*t;break}v+=e.length,yield*e}else yield*e}async getRunStats({id:e,trace:t,parentRun:r,runType:a,projectNames:n,projectIds:i,referenceExampleIds:s,startTime:o,endTime:c,error:d,query:l,filter:u,traceFilter:h,treeFilter:p,isRoot:m,dataSourceType:f}){let g=i||[];n&&(g=[...i||[],...await Promise.all(n.map((e=>this.readProject({projectName:e}).then((e=>e.id)))))]);const y={id:e,trace:t,parent_run:r,run_type:a,session:g,reference_example:s,start_time:o,end_time:c,error:d,query:l,filter:u,trace_filter:h,tree_filter:p,is_root:m,data_source_type:f},_=Object.fromEntries(Object.entries(y).filter((([e,t])=>void 0!==t))),b=await this.caller.call(qa(this.debug),`${this.apiUrl}/runs/stats`,{method:"POST",headers:this.headers,body:JSON.stringify(_),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await b.json()}async shareRun(e,{shareId:t}={}){const r={run_id:e,share_token:t||Yt()};Xa(e);const a=await this.caller.call(qa(this.debug),`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),n=await a.json();if(null===n||!("share_token"in n))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${n.share_token}/r`}async unshareRun(e){Xa(e);const t=await this.caller.call(qa(this.debug),`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(t,"unshare run",!0)}async readRunSharedLink(e){Xa(e);const t=await this.caller.call(qa(this.debug),`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),r=await t.json();if(null!==r&&"share_token"in r)return`${this.getHostUrl()}/public/${r.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){const r=new URLSearchParams({share_token:e});if(void 0!==t)for(const e of t)r.append("id",e);Xa(e);const a=await this.caller.call(qa(this.debug),`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await a.json()}async readDatasetSharedSchema(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");if(!e){e=(await this.readDataset({datasetName:t})).id}Xa(e);const r=await this.caller.call(qa(this.debug),`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),a=await r.json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async shareDataset(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");if(!e){e=(await this.readDataset({datasetName:t})).id}const r={dataset_id:e};Xa(e);const a=await this.caller.call(qa(this.debug),`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),n=await a.json();return n.url=`${this.getHostUrl()}/public/${n.share_token}/d`,n}async unshareDataset(e){Xa(e);const t=await this.caller.call(qa(this.debug),`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(t,"unshare dataset",!0)}async readSharedDataset(e){Xa(e);const t=await this.caller.call(qa(this.debug),`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await t.json()}async listSharedExamples(e,t){const r={};t?.exampleIds&&(r.id=t.exampleIds);const a=new URLSearchParams;Object.entries(r).forEach((([e,t])=>{Array.isArray(t)?t.forEach((t=>a.append(e,t))):a.append(e,t)}));const n=await this.caller.call(qa(this.debug),`${this.apiUrl}/public/${e}/examples?${a.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),i=await n.json();if(!n.ok){if("detail"in i)throw new Error(`Failed to list shared examples.\nStatus: ${n.status}\nMessage: ${i.detail.join("\n")}`);throw new Error(`Failed to list shared examples: ${n.status} ${n.statusText}`)}return i.map((e=>({...e,_hostUrl:this.getHostUrl()})))}async createProject({projectName:e,description:t=null,metadata:r=null,upsert:a=!1,projectExtra:n=null,referenceDatasetId:i=null}){const s=a?"?upsert=true":"",o=`${this.apiUrl}/sessions${s}`,c=n||{};r&&(c.metadata=r);const d={name:e,extra:c,description:t};null!==i&&(d.reference_dataset_id=i);const l=await this.caller.call(qa(this.debug),o,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(d),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(l,"create project");return await l.json()}async updateProject(e,{name:t=null,description:r=null,metadata:a=null,projectExtra:n=null,endTime:i=null}){const s=`${this.apiUrl}/sessions/${e}`;let o=n;a&&(o={...o||{},metadata:a});const c={name:t,extra:o,description:r,end_time:i?new Date(i).toISOString():null},d=await this.caller.call(qa(this.debug),s,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(c),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(d,"update project");return await d.json()}async hasProject({projectId:e,projectName:t}){let r="/sessions";const a=new URLSearchParams;if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");if(void 0!==e)Xa(e),r+=`/${e}`;else{if(void 0===t)throw new Error("Must provide projectName or projectId");a.append("name",t)}const n=await this.caller.call(qa(this.debug),`${this.apiUrl}${r}?${a}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});try{const e=await n.json();return!!n.ok&&(!Array.isArray(e)||e.length>0)}catch(e){return!1}}async readProject({projectId:e,projectName:t,includeStats:r}){let a="/sessions";const n=new URLSearchParams;if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");if(void 0!==e)Xa(e),a+=`/${e}`;else{if(void 0===t)throw new Error("Must provide projectName or projectId");n.append("name",t)}void 0!==r&&n.append("include_stats",r.toString());const i=await this._get(a,n);let s;if(Array.isArray(i)){if(0===i.length)throw new Error(`Project[id=${e}, name=${t}] not found`);s=i[0]}else s=i;return s}async getProjectUrl({projectId:e,projectName:t}){if(void 0===e&&void 0===t)throw new Error("Must provide either projectName or projectId");const r=await this.readProject({projectId:e,projectName:t}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(void 0===e&&void 0===t)throw new Error("Must provide either datasetName or datasetId");const r=await this.readDataset({datasetId:e,datasetName:t}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/datasets/${r.id}`}async _getTenantId(){if(null!==this._tenantId)return this._tenantId;const e=new URLSearchParams({limit:"1"});for await(const t of this._getPaginated("/sessions",e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:t,nameContains:r,referenceDatasetId:a,referenceDatasetName:n,referenceFree:i,metadata:s}={}){const o=new URLSearchParams;if(void 0!==e)for(const t of e)o.append("id",t);if(void 0!==t&&o.append("name",t),void 0!==r&&o.append("name_contains",r),void 0!==a)o.append("reference_dataset",a);else if(void 0!==n){const e=await this.readDataset({datasetName:n});o.append("reference_dataset",e.id)}void 0!==i&&o.append("reference_free",i.toString()),void 0!==s&&o.append("metadata",JSON.stringify(s));for await(const e of this._getPaginated("/sessions",o))yield*e}async deleteProject({projectId:e,projectName:t}){let r;if(void 0===e&&void 0===t)throw new Error("Must provide projectName or projectId");if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");r=void 0===e?(await this.readProject({projectName:t})).id:e,Xa(r);const a=await this.caller.call(qa(this.debug),`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(a,`delete session ${r} (${t})`,!0)}async uploadCsv({csvFile:e,fileName:t,inputKeys:r,outputKeys:a,description:n,dataType:i,name:s}){const o=`${this.apiUrl}/datasets/upload`,c=new FormData;c.append("file",e,t),r.forEach((e=>{c.append("input_keys",e)})),a.forEach((e=>{c.append("output_keys",e)})),n&&c.append("description",n),i&&c.append("data_type",i),s&&c.append("name",s);const d=await this.caller.call(qa(this.debug),o,{method:"POST",headers:this.headers,body:c,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(d,"upload CSV");return await d.json()}async createDataset(e,{description:t,dataType:r,inputsSchema:a,outputsSchema:n,metadata:i}={}){const s={name:e,description:t,extra:i?{metadata:i}:void 0};r&&(s.data_type=r),a&&(s.inputs_schema_definition=a),n&&(s.outputs_schema_definition=n);const o=await this.caller.call(qa(this.debug),`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(o,"create dataset");return await o.json()}async readDataset({datasetId:e,datasetName:t}){let r="/datasets";const a=new URLSearchParams({limit:"1"});if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0!==e)Xa(e),r+=`/${e}`;else{if(void 0===t)throw new Error("Must provide datasetName or datasetId");a.append("name",t)}const n=await this._get(r,a);let i;if(Array.isArray(n)){if(0===n.length)throw new Error(`Dataset[id=${e}, name=${t}] not found`);i=n[0]}else i=n;return i}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(e){if(e instanceof Error&&e.message.toLocaleLowerCase().includes("not found"))return!1;throw e}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:r,toVersion:a}){let n=e;if(void 0===n&&void 0===t)throw new Error("Must provide either datasetName or datasetId");if(void 0!==n&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===n){n=(await this.readDataset({datasetName:t})).id}const i=new URLSearchParams({from_version:"string"==typeof r?r:r.toISOString(),to_version:"string"==typeof a?a:a.toISOString()});return await this._get(`/datasets/${n}/versions/diff`,i)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){if(void 0!==e);else{if(void 0===t)throw new Error("Must provide either datasetName or datasetId");e=(await this.readDataset({datasetName:t})).id}const r=await this._getResponse(`/datasets/${e}/openai_ft`);return(await r.text()).trim().split("\n").map((e=>JSON.parse(e)))}async*listDatasets({limit:e=100,offset:t=0,datasetIds:r,datasetName:a,datasetNameContains:n,metadata:i}={}){const s=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(void 0!==r)for(const e of r)s.append("id",e);void 0!==a&&s.append("name",a),void 0!==n&&s.append("name_contains",n),void 0!==i&&s.append("metadata",JSON.stringify(i));for await(const e of this._getPaginated("/datasets",s))yield*e}async updateDataset(e){const{datasetId:t,datasetName:r,...a}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const n=t??(await this.readDataset({datasetName:r})).id;Xa(n);const i=await this.caller.call(qa(this.debug),`${this.apiUrl}/datasets/${n}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ai(i,"update dataset"),await i.json()}async updateDatasetTag(e){const{datasetId:t,datasetName:r,asOf:a,tag:n}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const i=t??(await this.readDataset({datasetName:r})).id;Xa(i);const s=await this.caller.call(qa(this.debug),`${this.apiUrl}/datasets/${i}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({as_of:"string"==typeof a?a:a.toISOString(),tag:n}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(s,"update dataset tags")}async deleteDataset({datasetId:e,datasetName:t}){let r="/datasets",a=e;if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0!==t){a=(await this.readDataset({datasetName:t})).id}if(void 0===a)throw new Error("Must provide datasetName or datasetId");Xa(a),r+=`/${a}`;const n=await this.caller.call(qa(this.debug),this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(n,`delete ${r}`),await n.json()}async indexDataset({datasetId:e,datasetName:t,tag:r}){let a=e;if(!a&&!t)throw new Error("Must provide either datasetName or datasetId");if(a&&t)throw new Error("Must provide either datasetName or datasetId, not both");if(!a){a=(await this.readDataset({datasetName:t})).id}Xa(a);const n={tag:r},i=await this.caller.call(qa(this.debug),`${this.apiUrl}/datasets/${a}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(i,"index dataset"),await i.json()}async similarExamples(e,t,r,{filter:a}={}){const n={limit:r,inputs:e};void 0!==a&&(n.filter=a),Xa(t);const i=await this.caller.call(qa(this.debug),`${this.apiUrl}/datasets/${t}/search`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(i,"fetch similar examples");return(await i.json()).examples}async createExample(e,t,r){if(bi(e)&&(void 0!==t||void 0!==r))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let a=t?r?.datasetId:e.dataset_id;const n=t?r?.datasetName:e.dataset_name;if(void 0===a&&void 0===n)throw new Error("Must provide either datasetName or datasetId");if(void 0!==a&&void 0!==n)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===a){a=(await this.readDataset({datasetName:n})).id}const i=(t?r?.createdAt:e.created_at)||new Date;let s;s=bi(e)?e:{inputs:e,outputs:t,created_at:i?.toISOString(),id:r?.exampleId,metadata:r?.metadata,split:r?.split,source_run_id:r?.sourceRunId,use_source_run_io:r?.useSourceRunIO,use_source_run_attachments:r?.useSourceRunAttachments,attachments:r?.attachments};const o=await this._uploadExamplesMultipart(a,[s]);return await this.readExample(o.example_ids?.[0]??Yt())}async createExamples(e){if(Array.isArray(e)){if(0===e.length)return[];const t=e;let r=t[0].dataset_id;const a=t[0].dataset_name;if(void 0===r&&void 0===a)throw new Error("Must provide either datasetName or datasetId");if(void 0!==r&&void 0!==a)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===r){r=(await this.readDataset({datasetName:a})).id}const n=await this._uploadExamplesMultipart(r,t);return await Promise.all(n.example_ids.map((e=>this.readExample(e))))}const{inputs:t,outputs:r,metadata:a,splits:n,sourceRunIds:i,useSourceRunIOs:s,useSourceRunAttachments:o,attachments:c,exampleIds:d,datasetId:l,datasetName:u}=e;if(void 0===t)throw new Error("Must provide inputs when using legacy parameters");let h=l;const p=u;if(void 0===h&&void 0===p)throw new Error("Must provide either datasetName or datasetId");if(void 0!==h&&void 0!==p)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===h){const e=await this.readDataset({datasetName:p});h=e.id}const m=t.map(((e,t)=>({dataset_id:h,inputs:e,outputs:r?.[t],metadata:a?.[t],split:n?.[t],id:d?.[t],attachments:c?.[t],source_run_id:i?.[t],use_source_run_io:s?.[t],use_source_run_attachments:o?.[t]}))),f=await this._uploadExamplesMultipart(h,m);return await Promise.all(f.example_ids.map((e=>this.readExample(e))))}async createLLMExample(e,t,r){return this.createExample({input:e},{output:t},r)}async createChatExample(e,t,r){const a=e.map((e=>Wa(e)?Ka(e):e)),n=Wa(t)?Ka(t):t;return this.createExample({input:a},{output:n},r)}async readExample(e){Xa(e);const t=`/examples/${e}`,r=await this._get(t),{attachment_urls:a,...n}=r,i=n;return a&&(i.attachments=Object.entries(a).reduce(((e,[t,r])=>(e[t.slice(11)]={presigned_url:r.presigned_url,mime_type:r.mime_type},e)),{})),i}async*listExamples({datasetId:e,datasetName:t,exampleIds:r,asOf:a,splits:n,inlineS3Urls:i,metadata:s,limit:o,offset:c,filter:d,includeAttachments:l}={}){let u;if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0!==e)u=e;else{if(void 0===t)throw new Error("Must provide a datasetName or datasetId");u=(await this.readDataset({datasetName:t})).id}const h=new URLSearchParams({dataset:u}),p=a?"string"==typeof a?a:a?.toISOString():void 0;p&&h.append("as_of",p);const m=i??!0;if(h.append("inline_s3_urls",m.toString()),void 0!==r)for(const e of r)h.append("id",e);if(void 0!==n)for(const e of n)h.append("splits",e);if(void 0!==s){const e=JSON.stringify(s);h.append("metadata",e)}void 0!==o&&h.append("limit",o.toString()),void 0!==c&&h.append("offset",c.toString()),void 0!==d&&h.append("filter",d),!0===l&&["attachment_urls","outputs","metadata"].forEach((e=>h.append("select",e)));let f=0;for await(const e of this._getPaginated("/examples",h)){for(const t of e){const{attachment_urls:e,...r}=t,a=r;e&&(a.attachments=Object.entries(e).reduce(((e,[t,r])=>(e[t.slice(11)]={presigned_url:r.presigned_url,mime_type:r.mime_type||void 0},e)),{})),yield a,f++}if(void 0!==o&&f>=o)break}}async deleteExample(e){Xa(e);const t=`/examples/${e}`,r=await this.caller.call(qa(this.debug),this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(r,`delete ${t}`),await r.json()}async updateExample(e,t){let r,a,n;if(r=t?e:e.id,Xa(r),a=t?{id:r,...t}:e,void 0!==a.dataset_id)n=a.dataset_id;else{n=(await this.readExample(r)).dataset_id}return this._updateExamplesMultipart(n,[a])}async updateExamples(e){let t;if(void 0===e[0].dataset_id){t=(await this.readExample(e[0].id)).dataset_id}else t=e[0].dataset_id;return this._updateExamplesMultipart(t,e)}async readDatasetVersion({datasetId:e,datasetName:t,asOf:r,tag:a}){let n;if(e)n=e;else{n=(await this.readDataset({datasetName:t})).id}if(Xa(n),r&&a||!r&&!a)throw new Error("Exactly one of asOf and tag must be specified.");const i=new URLSearchParams;void 0!==r&&i.append("as_of","string"==typeof r?r:r.toISOString()),void 0!==a&&i.append("tag",a);const s=await this.caller.call(qa(this.debug),`${this.apiUrl}/datasets/${n}/version?${i.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ai(s,"read dataset version"),await s.json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:r}){let a;if(void 0===e&&void 0===t)throw new Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===e){a=(await this.readDataset({datasetName:t})).id}else a=e;Xa(a);const n=new URLSearchParams,i=r?"string"==typeof r?r:r?.toISOString():void 0;i&&n.append("as_of",i);return await this._get(`/datasets/${a}/splits`,n)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:r,exampleIds:a,remove:n=!1}){let i;if(void 0===e&&void 0===t)throw new Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===e){i=(await this.readDataset({datasetName:t})).id}else i=e;Xa(i);const s={split_name:r,examples:a.map((e=>(Xa(e),e))),remove:n},o=await this.caller.call(qa(this.debug),`${this.apiUrl}/datasets/${i}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(o,"update dataset splits",!0)}async evaluateRun(e,t,{sourceInfo:r,loadChildRuns:a,referenceExample:n}={loadChildRuns:!1}){let i;if(Qa("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."),"string"==typeof e)i=await this.readRun(e,{loadChildRuns:a});else{if("object"!=typeof e||!("id"in e))throw new Error("Invalid run type: "+typeof e);i=e}null!==i.reference_example_id&&void 0!==i.reference_example_id&&(n=await this.readExample(i.reference_example_id));const s=await t.evaluateRun(i,n),[o,c]=await this._logEvaluationFeedback(s,i,r);return c[0]}async createFeedback(e,t,{score:r,value:a,correction:n,comment:i,sourceInfo:s,feedbackSourceType:o="api",sourceRunId:c,feedbackId:d,feedbackConfig:l,projectId:u,comparativeExperimentId:h}){if(!e&&!u)throw new Error("One of runId or projectId must be provided");if(e&&u)throw new Error("Only one of runId or projectId can be provided");const p={type:o??"api",metadata:s??{}};void 0===c||void 0===p?.metadata||p.metadata.__run||(p.metadata.__run={run_id:c}),void 0!==p?.metadata&&void 0!==p.metadata.__run?.run_id&&Xa(p.metadata.__run.run_id);const m={id:d??Yt(),run_id:e,key:t,score:gi(r),value:a,correction:n,comment:i,feedback_source:p,comparative_experiment_id:h,feedbackConfig:l,session_id:u},f=`${this.apiUrl}/feedback`,g=await this.caller.call(qa(this.debug),f,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(m),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ai(g,"create feedback",!0),m}async updateFeedback(e,{score:t,value:r,correction:a,comment:n}){const i={};null!=t&&(i.score=gi(t)),null!=r&&(i.value=r),null!=a&&(i.correction=a),null!=n&&(i.comment=n),Xa(e);const s=await this.caller.call(qa(this.debug),`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(s,"update feedback",!0)}async readFeedback(e){Xa(e);const t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){Xa(e);const t=`/feedback/${e}`,r=await this.caller.call(qa(this.debug),this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(r,`delete ${t}`),await r.json()}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:r}={}){const a=new URLSearchParams;if(e&&a.append("run",e.join(",")),t)for(const e of t)a.append("key",e);if(r)for(const e of r)a.append("source",e);for await(const e of this._getPaginated("/feedback",a))yield*e}async createPresignedFeedbackToken(e,t,{expiration:r,feedbackConfig:a}={}){const n={run_id:e,feedback_key:t,feedback_config:a};r?"string"==typeof r?n.expires_at=r:(r?.hours||r?.minutes||r?.days)&&(n.expires_in=r):n.expires_in={hours:3};const i=await this.caller.call(qa(this.debug),`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await i.json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:r,createdAt:a,description:n,metadata:i,id:s}){if(0===t.length)throw new Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:t[0]})).reference_dataset_id),null==!r)throw new Error("A reference dataset is required");const o={id:s,name:e,experiment_ids:t,reference_dataset_id:r,description:n,created_at:(a??new Date)?.toISOString(),extra:{}};i&&(o.extra.metadata=i);const c=await this.caller.call(qa(this.debug),`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await c.json()}async*listPresignedFeedbackTokens(e){Xa(e);const t=new URLSearchParams({run_id:e});for await(const e of this._getPaginated("/feedback/tokens",t))yield*e}_selectEvalResults(e){let t;return t="results"in e?e.results:Array.isArray(e)?e:[e],t}async _logEvaluationFeedback(e,t,r){const a=this._selectEvalResults(e),n=[];for(const e of a){let a=r||{};e.evaluatorInfo&&(a={...e.evaluatorInfo,...a});let i=null;e.targetRunId?i=e.targetRunId:t&&(i=t.id),n.push(await this.createFeedback(i,e.key,{score:e.score,value:e.value,comment:e.comment,correction:e.correction,sourceInfo:a,sourceRunId:e.sourceRunId,feedbackConfig:e.feedbackConfig,feedbackSourceType:"model"}))}return[a,n]}async logEvaluationFeedback(e,t,r){const[a]=await this._logEvaluationFeedback(e,t,r);return a}async*listAnnotationQueues(e={}){const{queueIds:t,name:r,nameContains:a,limit:n}=e,i=new URLSearchParams;t&&t.forEach(((e,t)=>{Xa(e,`queueIds[${t}]`),i.append("ids",e)})),r&&i.append("name",r),a&&i.append("name_contains",a),i.append("limit",(void 0!==n?Math.min(n,100):100).toString());let s=0;for await(const e of this._getPaginated("/annotation-queues",i))if(yield*e,s++,void 0!==n&&s>=n)break}async createAnnotationQueue(e){const{name:t,description:r,queueId:a,rubricInstructions:n}=e,i={name:t,description:r,id:a||Yt(),rubric_instructions:n},s=await this.caller.call(qa(this.debug),`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(Object.fromEntries(Object.entries(i).filter((([e,t])=>void 0!==t)))),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(s,"create annotation queue");return await s.json()}async readAnnotationQueue(e){const t=await this.caller.call(qa(this.debug),`${this.apiUrl}/annotation-queues/${Xa(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(t,"read annotation queue");return await t.json()}async updateAnnotationQueue(e,t){const{name:r,description:a,rubricInstructions:n}=t,i=await this.caller.call(qa(this.debug),`${this.apiUrl}/annotation-queues/${Xa(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({name:r,description:a,rubric_instructions:n}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(i,"update annotation queue")}async deleteAnnotationQueue(e){const t=await this.caller.call(qa(this.debug),`${this.apiUrl}/annotation-queues/${Xa(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(t,"delete annotation queue")}async addRunsToAnnotationQueue(e,t){const r=await this.caller.call(qa(this.debug),`${this.apiUrl}/annotation-queues/${Xa(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(t.map(((e,t)=>Xa(e,`runIds[${t}]`).toString()))),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(r,"add runs to annotation queue")}async getRunFromAnnotationQueue(e,t){const r=`/annotation-queues/${Xa(e,"queueId")}/run`,a=await this.caller.call(qa(this.debug),`${this.apiUrl}${r}/${t}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ai(a,"get run from annotation queue"),await a.json()}async deleteRunFromAnnotationQueue(e,t){const r=await this.caller.call(qa(this.debug),`${this.apiUrl}/annotation-queues/${Xa(e,"queueId")}/runs/${Xa(t,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(r,"delete run from annotation queue")}async getSizeFromAnnotationQueue(e){const t=await this.caller.call(qa(this.debug),`${this.apiUrl}/annotation-queues/${Xa(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ai(t,"get size from annotation queue"),await t.json()}async _currentTenantIsOwner(e){const t=await this._getSettings();return"-"==e||t.tenant_handle===e}async _ownerConflictError(e,t){const r=await this._getSettings();return new Error(`Cannot ${e} for another tenant.\n\n      Current tenant: ${r.tenant_handle}\n\n      Requested tenant: ${t}`)}async _getLatestCommitHash(e){const t=await this.caller.call(qa(this.debug),`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),r=await t.json();if(!t.ok){const e="string"==typeof r.detail?r.detail:JSON.stringify(r.detail),a=new Error(`Error ${t.status}: ${t.statusText}\n${e}`);throw a.statusCode=t.status,a}if(0!==r.commits.length)return r.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){const[r,a,n]=ti(e),i=await this.caller.call(qa(this.debug),`${this.apiUrl}/likes/${r}/${a}`,{method:"POST",body:JSON.stringify({like:t}),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ai(i,(t?"like":"unlike")+" prompt"),await i.json()}async _getPromptUrl(e){const[t,r,a]=ti(e);if(await this._currentTenantIsOwner(t)){const e=await this._getSettings();return"latest"!==a?`${this.getHostUrl()}/prompts/${r}/${a.substring(0,8)}?organizationId=${e.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${e.id}`}return"latest"!==a?`${this.getHostUrl()}/hub/${t}/${r}/${a.substring(0,8)}`:`${this.getHostUrl()}/hub/${t}/${r}`}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 t of this._getPaginated(`/commits/${e}/`,new URLSearchParams,(e=>e.commits)))yield*t}async*listPrompts(e){const t=new URLSearchParams;t.append("sort_field",e?.sortField??"updated_at"),t.append("sort_direction","desc"),t.append("is_archived",(!!e?.isArchived).toString()),void 0!==e?.isPublic&&t.append("is_public",e.isPublic.toString()),e?.query&&t.append("query",e.query);for await(const e of this._getPaginated("/repos",t,(e=>e.repos)))yield*e}async getPrompt(e){const[t,r,a]=ti(e),n=await this.caller.call(qa(this.debug),`${this.apiUrl}/repos/${t}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(404===n.status)return null;await ai(n,"get prompt");const i=await n.json();return i.repo?i.repo:null}async createPrompt(e,t){const r=await this._getSettings();if(t?.isPublic&&!r.tenant_handle)throw new Error("Cannot create a public prompt without first\n\n        creating a LangChain Hub handle. \n        You can add a handle by creating a public prompt at:\n\n        https://smith.langchain.com/prompts");const[a,n,i]=ti(e);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError("create a prompt",a);const s={repo_handle:n,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic},o=await this.caller.call(qa(this.debug),`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(o,"create prompt");const{repo:c}=await o.json();return c}async createCommit(e,t,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[a,n,i]=ti(e),s="latest"!==r?.parentCommitHash&&r?.parentCommitHash?r?.parentCommitHash:await this._getLatestCommitHash(`${a}/${n}`),o={manifest:JSON.parse(JSON.stringify(t)),parent_commit:s},c=await this.caller.call(qa(this.debug),`${this.apiUrl}/commits/${a}/${n}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(c,"create commit");const d=await c.json();return this._getPromptUrl(`${a}/${n}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(e,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){if(!await this._getMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const r=new FormData;for(const e of t){const t=e.id,a=li({...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split}}),n=new Blob([a],{type:"application/json"});if(r.append(t,n),e.inputs){const a=li(e.inputs),n=new Blob([a],{type:"application/json"});r.append(`${t}.inputs`,n)}if(e.outputs){const a=li(e.outputs),n=new Blob([a],{type:"application/json"});r.append(`${t}.outputs`,n)}if(e.attachments)for(const[a,n]of Object.entries(e.attachments)){let e,i;Array.isArray(n)?[e,i]=n:(e=n.mimeType,i=n.data);const s=new Blob([i],{type:`${e}; length=${i.byteLength}`});r.append(`${t}.attachment.${a}`,s)}if(e.attachments_operations){const a=li(e.attachments_operations),n=new Blob([a],{type:"application/json"});r.append(`${t}.attachments_operations`,n)}}const a=e??t[0]?.dataset_id,n=await this.caller.call(qa(this.debug),`${this.apiUrl}/v1/platform/datasets/${a}/examples`,{method:"PATCH",headers:this.headers,body:r});return await n.json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){if(!await this._getMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const r=new FormData;for(const e of t){const t=(e.id??Yt()).toString(),a=li({created_at:e.created_at,...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split},...e.source_run_id&&{source_run_id:e.source_run_id},...e.use_source_run_io&&{use_source_run_io:e.use_source_run_io},...e.use_source_run_attachments&&{use_source_run_attachments:e.use_source_run_attachments}}),n=new Blob([a],{type:"application/json"});if(r.append(t,n),e.inputs){const a=li(e.inputs),n=new Blob([a],{type:"application/json"});r.append(`${t}.inputs`,n)}if(e.outputs){const a=li(e.outputs),n=new Blob([a],{type:"application/json"});r.append(`${t}.outputs`,n)}if(e.attachments)for(const[a,n]of Object.entries(e.attachments)){let e,i;Array.isArray(n)?[e,i]=n:(e=n.mimeType,i=n.data);const s=new Blob([i],{type:`${e}; length=${i.byteLength}`});r.append(`${t}.attachment.${a}`,s)}}const a=await this.caller.call(qa(this.debug),`${this.apiUrl}/v1/platform/datasets/${e}/examples`,{method:"POST",headers:this.headers,body:r});await ai(a,"upload examples");return await a.json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[r,a]=ti(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);const n={};if(void 0!==t?.description&&(n.description=t.description),void 0!==t?.readme&&(n.readme=t.readme),void 0!==t?.tags&&(n.tags=t.tags),void 0!==t?.isPublic&&(n.is_public=t.isPublic),void 0!==t?.isArchived&&(n.is_archived=t.isArchived),0===Object.keys(n).length)throw new Error("No valid update options provided");const i=await this.caller.call(qa(this.debug),`${this.apiUrl}/repos/${r}/${a}`,{method:"PATCH",body:JSON.stringify(n),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ai(i,"update prompt"),i.json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[t,r,a]=ti(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);const n=await this.caller.call(qa(this.debug),`${this.apiUrl}/repos/${t}/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await n.json()}async pullPromptCommit(e,t){const[r,a,n]=ti(e),i=await this.caller.call(qa(this.debug),`${this.apiUrl}/commits/${r}/${a}/${n}${t?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ai(i,"pull prompt commit");const s=await i.json();return{owner:r,repo:a,commit_hash:s.commit_hash,manifest:s.manifest,examples:s.examples}}async _pullPrompt(e,t){const r=await this.pullPromptCommit(e,{includeModel:t?.includeModel});return JSON.stringify(r.manifest)}async pushPrompt(e,t){if(await this.promptExists(e)?t&&Object.keys(t).some((e=>"object"!==e))&&await this.updatePrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}):await this.createPrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}),!t?.object)return await this._getPromptUrl(e);return await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash})}async clonePublicDataset(e,t={}){const{sourceApiUrl:r=this.apiUrl,datasetName:a}=t,[n,i]=this.parseTokenOrUrl(e,r),s=new _i({apiUrl:n,apiKey:"placeholder"}),o=await s.readSharedDataset(i),c=a||o.name;try{if(await this.hasDataset({datasetId:c}))return void console.log(`Dataset ${c} already exists in your tenant. Skipping.`)}catch(e){}const d=await s.listSharedExamples(i),l=await this.createDataset(c,{description:o.description,dataType:o.data_type||"kv",inputsSchema:o.inputs_schema_definition??void 0,outputsSchema:o.outputs_schema_definition??void 0});try{await this.createExamples({inputs:d.map((e=>e.inputs)),outputs:d.flatMap((e=>e.outputs?[e.outputs]:[])),datasetId:l.id})}catch(e){throw console.error(`An error occurred while creating dataset ${c}. You should delete it manually.`),e}}parseTokenOrUrl(e,t,r=2,a="dataset"){try{return Xa(e),[t,e]}catch(e){}try{const n=new URL(e).pathname.split("/").filter((e=>""!==e));if(n.length>=r){return[t,n[n.length-r]]}throw new Error(`Invalid public ${a} URL: ${e}`)}catch(t){throw new Error(`Invalid public ${a} URL or token: ${e}`)}}awaitPendingTraceBatches(){return this.manualFlushMode?(console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve()):Promise.all([...this.autoBatchQueue.items.map((({itemPromise:e})=>e)),this.batchIngestCaller.queue.onIdle()])}}function bi(e){return"dataset_id"in e||"dataset_name"in e}const vi="0.3.25";let wi;const Ei=()=>"undefined"!=typeof Deno,Oi=()=>wi||(wi="undefined"!=typeof window&&void 0!==window.document?"browser":void 0===Zr.versions||void 0===Zr.versions.node||Ei()?"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name?"webworker":"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"))?"jsdom":Ei()?"deno":"other":"node",wi);let $i,ki;function Ii(){if(void 0===$i){const e=Oi(),t=function(){if(void 0!==ki)return ki;const e=["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"],t={};for(const r of e){const e=Ti(r);void 0!==e&&(t[r]=e)}return ki=t,t}();$i={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:vi,...t}}return $i}function Ti(e){try{return Zr.env?.[e]}catch(e){return}}function xi(e){return Ti(`LANGSMITH_${e}`)||Ti(`LANGCHAIN_${e}`)}const Si=Symbol.for("lc:context_variables");class Ai{constructor(e,t,r){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}),this.metadata=e,this.tags=t,this.project_name=r}static fromHeader(e){const t=e.split(",");let r,a={},n=[];for(const e of t){const[t,i]=e.split("="),s=decodeURIComponent(i);"langsmith-metadata"===t?a=JSON.parse(s):"langsmith-tags"===t?n=s.split(","):"langsmith-project"===t&&(r=s)}return new Ai(a,n,r)}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 ji{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,"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}),Pi(e))return void Object.assign(this,{...e});const t=ji.getDefaultConfig(),{metadata:r,...a}=e,n=a.client??ji.getSharedClient(),i={...r,...a?.extra?.metadata};if(a.extra={...a.extra,metadata:i},Object.assign(this,{...t,...a,client:n}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){const e=function(e,t,r=1){const a=r.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(e).toISOString().slice(0,-1)}${a}Z`.replace(/[-:.]/g,"")+t}(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+e:this.dotted_order=e}}static getDefaultConfig(){return{id:Yt(),run_type:"chain",project_name:xi("PROJECT")??Ti("LANGCHAIN_SESSION")??"default",child_runs:[],api_url:Ti("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Ti("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return ji.sharedClient||(ji.sharedClient=new _i),ji.sharedClient}createChild(e){const t=this.child_execution_order+1,r=new ji({...e,parent_run:this,project_name:this.project_name,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:t,child_execution_order:t});Si in this&&(r[Si]=this[Si]);const a=Symbol.for("lc:child_config"),n=e.extra?.[a]??this.extra[a];if(void 0!==(i=n)&&"object"==typeof i.callbacks&&(Ni(i.callbacks?.handlers)||Ni(i.callbacks))){const e={...n},t=function(e){return"object"==typeof e&&null!=e&&Array.isArray(e.handlers)}(e.callbacks)?e.callbacks.copy?.():void 0;t&&(Object.assign(t,{_parentRunId:r.id}),t.handlers?.find(Ri)?.updateFromRunTree?.(r),e.callbacks=t),r.extra[a]=e}var i;const s=new Set;let o=this;for(;null!=o&&!s.has(o.id);)s.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,t),o=o.parent_run;return this.child_runs.push(r),r}async end(e,t,r=Date.now(),a){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??r,a&&Object.keys(a).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...a}}:{metadata:a})}_convertToCreate(e,t,r=!0){const a=e.extra??{};if(a.runtime||(a.runtime={}),t)for(const[e,r]of Object.entries(t))a.runtime[e]||(a.runtime[e]=r);let n,i;r?(i=e.parent_run?.id,n=[]):(n=e.child_runs.map((e=>this._convertToCreate(e,t,r))),i=void 0);return{id:e.id,name:e.name,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:n,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments}}async postRun(e=!0){try{const t=Ii(),r=await this._convertToCreate(this,t,!0);if(await this.client.createRun(r),!e){Qa("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const e of this.child_runs)await e.postRun(!1)}}catch(e){console.error(`Error in postRun for run ${this.id}:`,e)}}async patchRun(){try{const e={end_time:this.end_time,error:this.error,inputs:this.inputs,outputs:this.outputs,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};await this.client.updateRun(this.id,e)}catch(e){console.error(`Error in patchRun for run ${this.id}`,e)}}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),"string"==typeof e?this.events.push({name:"event",time:(new Date).toISOString(),message:e}):this.events.push({...e,time:e.time??(new Date).toISOString()})}static fromRunnableConfig(e,t){const r=e?.callbacks;let a,n,i,s=!!["TRACING_V2","TRACING"].find((e=>"true"===xi(e)));if(r){const e=r?.getParentRunId?.()??"",t=r?.handlers?.find((e=>"langchain_tracer"==e?.name));a=t?.getRun?.(e),n=t?.projectName,i=t?.client,s=s||!!t}if(!a)return new ji({...t,client:i,tracingEnabled:s,project_name:n});return new ji({name:a.name,id:a.id,trace_id:a.trace_id,dotted_order:a.dotted_order,client:i,tracingEnabled:s,project_name:n,tags:[...new Set((a?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...a?.extra?.metadata,...e?.metadata}}}).createChild(t)}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){const r="get"in e&&"function"==typeof e.get?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,a=r["langsmith-trace"];if(!a||"string"!=typeof a)return;const n=a.trim(),i=n.split(".").map((e=>{const[t,r]=e.split("Z");return{strTime:t,time:Date.parse(t+"Z"),uuid:r}})),s=i[0].uuid,o={...t,name:t?.name??"parent",run_type:t?.run_type??"chain",start_time:t?.start_time??Date.now(),id:i.at(-1)?.uuid,trace_id:s,dotted_order:n};if(r.baggage&&"string"==typeof r.baggage){const e=Ai.fromHeader(r.baggage);o.metadata=e.metadata,o.tags=e.tags,o.project_name=e.project_name}return new ji(o)}toHeaders(e){const t={"langsmith-trace":this.dotted_order,baggage:new Ai(this.extra?.metadata,this.tags,this.project_name).toHeader()};if(e)for(const[r,a]of Object.entries(t))e.set(r,a);return t}}function Pi(e){return void 0!==e&&"function"==typeof e.createChild&&"function"==typeof e.postRun}function Ri(e){return"object"==typeof e&&null!=e&&"string"==typeof e.name&&"langchain_tracer"===e.name}function Ni(e){return Array.isArray(e)&&e.some((e=>Ri(e)))}Object.defineProperty(ji,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});const Ci=Symbol.for("ls:tracing_async_local_storage"),Li=new class{getStore(){}run(e,t){return t()}};const Mi=new class{getInstance(){return globalThis[Ci]??Li}initializeGlobalInstance(e){void 0===globalThis[Ci]&&(globalThis[Ci]=e)}};function Ui(e){return"function"==typeof e&&"langsmith:traceable"in e}let Di;const Fi=()=>{if(void 0===Di){const e="false"===Gr("LANGCHAIN_CALLBACKS_BACKGROUND")?{blockOnRootRunFinalization:!0}:{};Di=new _i(e)}return Di};class Zi extends ea{constructor(e={}){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const{exampleId:t,projectName:r,client:a}=e;this.projectName=r??Gr("LANGCHAIN_PROJECT")??Gr("LANGCHAIN_SESSION"),this.exampleId=t,this.client=a??Fi();const n=Zi.getTraceableRunTree();n&&this.updateFromRunTree(n)}async _convertToCreate(e,t=void 0){return{...e,extra:{...e.extra,runtime:await qr()},child_runs:void 0,session_name:this.projectName,reference_example_id:e.parent_run_id?void 0:t}}async persistRun(e){}async onRunCreate(e){const t=await this._convertToCreate(e,this.exampleId);await this.client.createRun(t)}async onRunUpdate(e){const t={end_time:e.end_time,error:e.error,outputs:e.outputs,events:e.events,inputs:e.inputs,trace_id:e.trace_id,dotted_order:e.dotted_order,parent_run_id:e.parent_run_id,extra:e.extra,session_name:this.projectName};await this.client.updateRun(e.id,t)}getRun(e){return this.runMap.get(e)}updateFromRunTree(e){let t=e;const r=new Set;for(;t.parent_run&&!r.has(t.id)&&(r.add(t.id),t.parent_run);)t=t.parent_run;r.clear();const a=[t];for(;a.length>0;){const e=a.shift();e&&!r.has(e.id)&&(r.add(e.id),this.runMap.set(e.id,e),e.child_runs&&a.push(...e.child_runs))}this.client=e.client??this.client,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}convertToRunTree(e){const t={},r=[];for(const[e,a]of this.runMap){const n=new ji({...a,child_runs:[],parent_run:void 0,client:this.client,project_name:this.projectName,reference_example_id:this.exampleId,tracingEnabled:!0});t[e]=n,r.push([e,a.dotted_order])}r.sort(((e,t)=>e[1]&&t[1]?e[1].localeCompare(t[1]):0));for(const[e]of r){const r=this.runMap.get(e),a=t[e];if(r&&a&&r.parent_run_id){const e=t[r.parent_run_id];e&&(e.child_runs.push(a),a.parent_run=e)}}return t[e]}static getTraceableRunTree(){try{return(()=>{const e=Mi.getInstance().getStore();if(!Pi(e))throw new Error(["Could not get the current run tree.","","Please make sure you are calling this method within a traceable function and that tracing is enabled."].join("\n"));return e})()}catch{return}}}const zi=Symbol.for("ls:tracing_async_local_storage"),Bi=Symbol.for("lc:context_variables"),Hi=()=>globalThis[zi];let qi;function Gi(){return void 0===qi&&(qi=new("default"in za?za.default:za)({autoStart:!0,concurrency:1})),qi}async function Ji(e,t){if(!0===t){const t=Hi();void 0!==t?await t.run(void 0,(async()=>e())):await e()}else qi=Gi(),qi.add((async()=>{const t=Hi();void 0!==t?await t.run(void 0,(async()=>e())):await e()}))}function Vi(e){const t=Hi();if(void 0===t)return;const r=t.getStore();return r?.[Bi]?.[e]}const Wi=Symbol("lc:configure_hooks");class Ki{setHandler(e){return this.setHandlers([e])}}class Xi{constructor(e,t,r,a,n,i,s,o){Object.defineProperty(this,"runId",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:o})}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map((t=>Ji((async()=>{try{await(t.handleText?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleCustomEvent(e,t,r,a,n){await Promise.all(this.handlers.map((r=>Ji((async()=>{try{await(r.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata))}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleCustomEvent: ${e}`),r.raiseError)throw e}}),r.awaitHandlers))))}}class Yi extends Xi{getChild(e){const t=new rs(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map((t=>Ji((async()=>{if(!t.ignoreRetriever)try{await(t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleRetrieverError(e){await Promise.all(this.handlers.map((t=>Ji((async()=>{if(!t.ignoreRetriever)try{await(t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags))}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${r}`),t.raiseError)throw e}}),t.awaitHandlers))))}}class Qi extends Xi{async handleLLMNewToken(e,t,r,a,n,i){await Promise.all(this.handlers.map((r=>Ji((async()=>{if(!r.ignoreLLM)try{await(r.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,i))}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMNewToken: ${e}`),r.raiseError)throw e}}),r.awaitHandlers))))}async handleLLMError(e,t,r,a,n){await Promise.all(this.handlers.map((t=>Ji((async()=>{if(!t.ignoreLLM)try{await(t.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,n))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMError: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleLLMEnd(e,t,r,a,n){await Promise.all(this.handlers.map((t=>Ji((async()=>{if(!t.ignoreLLM)try{await(t.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,n))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMEnd: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}}class es extends Xi{getChild(e){const t=new rs(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,r,a,n){await Promise.all(this.handlers.map((t=>Ji((async()=>{if(!t.ignoreChain)try{await(t.handleChainError?.(e,this.runId,this._parentRunId,this.tags,n))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainError: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleChainEnd(e,t,r,a,n){await Promise.all(this.handlers.map((t=>Ji((async()=>{if(!t.ignoreChain)try{await(t.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,n))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainEnd: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleAgentAction(e){await Promise.all(this.handlers.map((t=>Ji((async()=>{if(!t.ignoreAgent)try{await(t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleAgentEnd(e){await Promise.all(this.handlers.map((t=>Ji((async()=>{if(!t.ignoreAgent)try{await(t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}}class ts extends Xi{getChild(e){const t=new rs(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map((t=>Ji((async()=>{if(!t.ignoreAgent)try{await(t.handleToolError?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleToolEnd(e){await Promise.all(this.handlers.map((t=>Ji((async()=>{if(!t.ignoreAgent)try{await(t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}}class rs extends Ki{constructor(e,t){super(),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"callback_manager"}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.handlers=t?.handlers??this.handlers,this.inheritableHandlers=t?.inheritableHandlers??this.inheritableHandlers,this.tags=t?.tags??this.tags,this.inheritableTags=t?.inheritableTags??this.inheritableTags,this.metadata=t?.metadata??this.metadata,this.inheritableMetadata=t?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,t,r=void 0,a=void 0,n=void 0,i=void 0,s=void 0,o=void 0){return Promise.all(t.map((async(t,a)=>{const i=0===a&&r?r:Yt();return await Promise.all(this.handlers.map((r=>{if(!r.ignoreLLM)return Qr(r)&&r._createRunForLLMStart(e,[t],i,this._parentRunId,n,this.tags,this.metadata,o),Ji((async()=>{try{await(r.handleLLMStart?.(e,[t],i,this._parentRunId,n,this.tags,this.metadata,o))}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}}),r.awaitHandlers)}))),new Qi(i,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)})))}async handleChatModelStart(e,t,r=void 0,a=void 0,n=void 0,i=void 0,s=void 0,o=void 0){return Promise.all(t.map((async(t,a)=>{const i=0===a&&r?r:Yt();return await Promise.all(this.handlers.map((r=>{if(!r.ignoreLLM)return Qr(r)&&r._createRunForChatModelStart(e,[t],i,this._parentRunId,n,this.tags,this.metadata,o),Ji((async()=>{try{if(r.handleChatModelStart)await(r.handleChatModelStart?.(e,[t],i,this._parentRunId,n,this.tags,this.metadata,o));else if(r.handleLLMStart){const a=function(e,t="Human",r="AI"){const a=[];for(const n of e){let e;if("human"===n._getType())e=t;else if("ai"===n._getType())e=r;else if("system"===n._getType())e="System";else if("function"===n._getType())e="Function";else if("tool"===n._getType())e="Tool";else{if("generic"!==n._getType())throw new Error(`Got unsupported message type: ${n._getType()}`);e=n.role}const i=n.name?`${n.name}, `:"",s="string"==typeof n.content?n.content:JSON.stringify(n.content,null,2);a.push(`${e}: ${i}${s}`)}return a.join("\n")}(t);await(r.handleLLMStart?.(e,[a],i,this._parentRunId,n,this.tags,this.metadata,o))}}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}}),r.awaitHandlers)}))),new Qi(i,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)})))}async handleChainStart(e,t,r=Yt(),a=void 0,n=void 0,i=void 0,s=void 0){return await Promise.all(this.handlers.map((n=>{if(!n.ignoreChain)return Qr(n)&&n._createRunForChainStart(e,t,r,this._parentRunId,this.tags,this.metadata,a,s),Ji((async()=>{try{await(n.handleChainStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,a,s))}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleChainStart: ${e}`),n.raiseError)throw e}}),n.awaitHandlers)}))),new es(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,r=Yt(),a=void 0,n=void 0,i=void 0,s=void 0){return await Promise.all(this.handlers.map((a=>{if(!a.ignoreAgent)return Qr(a)&&a._createRunForToolStart(e,t,r,this._parentRunId,this.tags,this.metadata,s),Ji((async()=>{try{await(a.handleToolStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,s))}catch(e){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleToolStart: ${e}`),a.raiseError)throw e}}),a.awaitHandlers)}))),new ts(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,r=Yt(),a=void 0,n=void 0,i=void 0,s=void 0){return await Promise.all(this.handlers.map((a=>{if(!a.ignoreRetriever)return Qr(a)&&a._createRunForRetrieverStart(e,t,r,this._parentRunId,this.tags,this.metadata,s),Ji((async()=>{try{await(a.handleRetrieverStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,s))}catch(e){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleRetrieverStart: ${e}`),a.raiseError)throw e}}),a.awaitHandlers)}))),new Yi(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,r,a,n){await Promise.all(this.handlers.map((a=>Ji((async()=>{if(!a.ignoreCustomEvent)try{await(a.handleCustomEvent?.(e,t,r,this.tags,this.metadata))}catch(e){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${e}`),a.raiseError)throw e}}),a.awaitHandlers))))}addHandler(e,t=!0){this.handlers.push(e),t&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter((t=>t!==e)),this.inheritableHandlers=this.inheritableHandlers.filter((t=>t!==e))}setHandlers(e,t=!0){this.handlers=[],this.inheritableHandlers=[];for(const r of e)this.addHandler(r,t)}addTags(e,t=!0){this.removeTags(e),this.tags.push(...e),t&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter((t=>!e.includes(t))),this.inheritableTags=this.inheritableTags.filter((t=>!e.includes(t)))}addMetadata(e,t=!0){this.metadata={...this.metadata,...e},t&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(const t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(e=[],t=!0){const r=new rs(this._parentRunId);for(const e of this.handlers){const t=this.inheritableHandlers.includes(e);r.addHandler(e,t)}for(const e of this.tags){const t=this.inheritableTags.includes(e);r.addTags([e],t)}for(const e of Object.keys(this.metadata)){const t=Object.keys(this.inheritableMetadata).includes(e);r.addMetadata({[e]:this.metadata[e]},t)}for(const a of e)r.handlers.filter((e=>"console_callback_handler"===e.name)).some((e=>e.name===a.name))||r.addHandler(a,t);return r}static fromHandlers(e){const t=new this;return t.addHandler(new class extends Vr{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:Yt()}),Object.assign(this,e)}}),t}static configure(e,t,r,a,n,i,s){return this._configureSync(e,t,r,a,n,i,s)}static _configureSync(e,t,r,a,n,i,s){let o;(e||t)&&(Array.isArray(e)||!e?(o=new rs,o.setHandlers(e?.map(as)??[],!0)):o=e,o=o.copy(Array.isArray(t)?t.map(as):t?.handlers,!1));const c="true"===Gr("LANGCHAIN_VERBOSE")||s?.verbose,d=Zi.getTraceableRunTree()?.tracingEnabled||!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find((e=>"true"===Gr(e))),l=d||(Gr("LANGCHAIN_TRACING")??!1);if(c||l){if(o||(o=new rs),c&&!o.handlers.some((e=>e.name===sa.prototype.name))){const e=new sa;o.addHandler(e,!0)}if(l&&!o.handlers.some((e=>"langchain_tracer"===e.name))&&d){const e=new Zi;o.addHandler(e,!0),o._parentRunId=Zi.getTraceableRunTree()?.id??o._parentRunId}}for(const{contextVar:e,inheritable:t=!0,handlerClass:r,envVar:a}of Vi(Wi)||[]){const n=a&&"true"===Gr(a)&&r;let i;const s=void 0!==e?Vi(e):void 0;s&&Wr(s)?i=s:n&&(i=new r({})),void 0!==i&&(o||(o=new rs),o.handlers.some((e=>e.name===i.name))||o.addHandler(i,t))}return(r||a)&&o&&(o.addTags(r??[]),o.addTags(a??[],!1)),(n||i)&&o&&(o.addMetadata(n??{}),o.addMetadata(i??{},!1)),o}}function as(e){return"name"in e?e:Vr.fromMethods(e)}const ns=[400,401,402,403,404,405,406,407,409],is=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||"AbortError"===e.name)throw e;if("ECONNABORTED"===e?.code)throw e;const t=e?.response?.status??e?.status;if(t&&ns.includes(+t))throw e;if("insufficient_quota"===e?.error?.code){const t=new Error(e?.message);throw t.name="InsufficientQuotaError",t}};class ss{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,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??is;const t="default"in za?za.default:za;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add((()=>ka((()=>e(...t).catch((e=>{throw e instanceof Error?e:new Error(e)}))),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0})),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise(((t,r)=>{e.signal?.addEventListener("abort",(()=>{r(new Error("AbortError"))}))}))]):this.call(t,...r)}fetch(...e){return this.call((()=>fetch(...e).then((e=>e.ok?e:Promise.reject(e)))))}}for(var os={byteLength:function(e){var t=ps(e),r=t[0],a=t[1];return 3*(r+a)/4-a},toByteArray:function(e){var t,r,a=ps(e),n=a[0],i=a[1],s=new ls(function(e,t,r){return 3*(t+r)/4-r}(0,n,i)),o=0,c=i>0?n-4:n;for(r=0;r<c;r+=4)t=ds[e.charCodeAt(r)]<<18|ds[e.charCodeAt(r+1)]<<12|ds[e.charCodeAt(r+2)]<<6|ds[e.charCodeAt(r+3)],s[o++]=t>>16&255,s[o++]=t>>8&255,s[o++]=255&t;2===i&&(t=ds[e.charCodeAt(r)]<<2|ds[e.charCodeAt(r+1)]>>4,s[o++]=255&t);1===i&&(t=ds[e.charCodeAt(r)]<<10|ds[e.charCodeAt(r+1)]<<4|ds[e.charCodeAt(r+2)]>>2,s[o++]=t>>8&255,s[o++]=255&t);return s},fromByteArray:function(e){for(var t,r=e.length,a=r%3,n=[],i=16383,s=0,o=r-a;s<o;s+=i)n.push(ms(e,s,s+i>o?o:s+i));1===a?(t=e[r-1],n.push(cs[t>>2]+cs[t<<4&63]+"==")):2===a&&(t=(e[r-2]<<8)+e[r-1],n.push(cs[t>>10]+cs[t>>4&63]+cs[t<<2&63]+"="));return n.join("")}},cs=[],ds=[],ls="undefined"!=typeof Uint8Array?Uint8Array:Array,us="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",hs=0;hs<64;++hs)cs[hs]=us[hs],ds[us.charCodeAt(hs)]=hs;function ps(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function ms(e,t,r){for(var a,n,i=[],s=t;s<r;s+=3)a=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),i.push(cs[(n=a)>>18&63]+cs[n>>12&63]+cs[n>>6&63]+cs[63&n]);return i.join("")}ds["-".charCodeAt(0)]=62,ds["_".charCodeAt(0)]=63;var fs=Object.defineProperty;function gs(e,t){return 1===e.length?[t.get(e.join(","))]:function(e,t){let r=Array.from({length:e.length},((e,t)=>({start:t,end:t+1})));for(;r.length>1;){let a=null;for(let n=0;n<r.length-1;n++){const i=e.slice(r[n].start,r[n+1].end),s=t.get(i.join(","));null!=s&&(null==a||s<a[0])&&(a=[s,n])}if(null==a)break;{const e=a[1];r[e]={start:r[e].start,end:r[e+1].end},r.splice(e+1,1)}}return r}(e,t).map((r=>t.get(e.slice(r.start,r.end).join(",")))).filter((e=>null!=e))}var ys,_s=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,t){this.patStr=e.pat_str;const r=e.bpe_ranks.split("\n").filter(Boolean).reduce(((e,t)=>{const[r,a,...n]=t.split(" "),i=Number.parseInt(a,10);return n.forEach(((t,r)=>e[t]=i+r)),e}),{});for(const[e,t]of Object.entries(r)){const r=os.toByteArray(e);this.rankMap.set(r.join(","),t),this.textMap.set(t,r)}this.specialTokens={...e.special_tokens,...t},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce(((e,[t,r])=>(e[r]=this.textEncoder.encode(t),e)),{})}encode(e,t=[],r="all"){const a=new RegExp(this.patStr,"ug"),n=_s.specialTokenRegex(Object.keys(this.specialTokens)),i=[],s=new Set("all"===t?Object.keys(this.specialTokens):t),o=new Set("all"===r?Object.keys(this.specialTokens).filter((e=>!s.has(e))):r);if(o.size>0){const t=_s.specialTokenRegex([...o]),r=e.match(t);if(null!=r)throw new Error(`The text contains a special token that is not allowed: ${r[0]}`)}let c=0;for(;;){let t=null,r=c;for(;n.lastIndex=r,t=n.exec(e),null!=t&&!s.has(t[0]);)r=t.index+1;const o=t?.index??e.length;for(const t of e.substring(c,o).matchAll(a)){const e=this.textEncoder.encode(t[0]),r=this.rankMap.get(e.join(","));null==r?i.push(...gs(e,this.rankMap)):i.push(r)}if(null==t)break;let d=this.specialTokens[t[0]];i.push(d),c=t.index+t[0].length}return i}decode(e){const t=[];let r=0;for(let a=0;a<e.length;++a){const n=e[a],i=this.textMap.get(n)??this.inverseSpecialTokens[n];null!=i&&(t.push(i),r+=i.length)}const a=new Uint8Array(r);let n=0;for(const e of t)a.set(e,n),n+=e.length;return this.textDecoder.decode(a)}};ys=e=>new RegExp(e.map((e=>e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&"))).join("|"),"g"),((e,t,r)=>{t in e?fs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r})(_s,"specialTokenRegex"+"",ys);
/*!
 * https://github.com/Starcounter-Jack/JSON-Patch
 * (c) 2017-2022 Joachim Wester
 * MIT licensed
 */
const bs=Object.prototype.hasOwnProperty;function vs(e,t){return bs.call(e,t)}function ws(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function Es(e){let t=0;const r=e.length;let a;for(;t<r;){if(a=e.charCodeAt(t),!(a>=48&&a<=57))return!1;t++}return!0}function Os(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function $s(e){if(void 0===e)return!0;if(e)if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if($s(e[t]))return!0}else if("object"==typeof e){const r=function(e){if(Array.isArray(e)){const t=new Array(e.length);for(let e=0;e<t.length;e++)t[e]=""+e;return t}if(Object.keys)return Object.keys(e);let t=[];for(let r in e)vs(e,r)&&t.push(r);return t}(e),a=r.length;for(var t=0;t<a;t++)if($s(e[r[t]]))return!0}return!1}function ks(e,t){const r=[e];for(const e in t){const a="object"==typeof t[e]?JSON.stringify(t[e],null,2):t[e];void 0!==a&&r.push(`${e}: ${a}`)}return r.join("\n")}class Is extends Error{constructor(e,t,r,a,n){super(ks(e,{name:t,index:r,operation:a,tree:n})),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.setPrototypeOf(this,new.target.prototype),this.message=ks(e,{name:t,index:r,operation:a,tree:n})}}const Ts=Is,xs={add:function(e,t,r){return e[t]=this.value,{newDocument:r}},remove:function(e,t,r){var a=e[t];return delete e[t],{newDocument:r,removed:a}},replace:function(e,t,r){var a=e[t];return e[t]=this.value,{newDocument:r,removed:a}},move:function(e,t,r){let a=As(r,this.path);a&&(a=ws(a));const n=js(r,{op:"remove",path:this.from}).removed;return js(r,{op:"add",path:this.path,value:n}),{newDocument:r,removed:a}},copy:function(e,t,r){const a=As(r,this.from);return js(r,{op:"add",path:this.path,value:ws(a)}),{newDocument:r}},test:function(e,t,r){return{newDocument:r,test:Ns(e[t],this.value)}},_get:function(e,t,r){return this.value=e[t],{newDocument:r}}};var Ss={add:function(e,t,r){return Es(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:r,index:t}},remove:function(e,t,r){return{newDocument:r,removed:e.splice(t,1)[0]}},replace:function(e,t,r){var a=e[t];return e[t]=this.value,{newDocument:r,removed:a}},move:xs.move,copy:xs.copy,test:xs.test,_get:xs._get};function As(e,t){if(""==t)return e;var r={op:"_get",path:t};return js(e,r),r.value}function js(e,t,r=!1,a=!0,n=!0,i=0){if(r&&("function"==typeof r?r(t,0,e,t.path):Rs(t,0)),""===t.path){let a={newDocument:e};if("add"===t.op)return a.newDocument=t.value,a;if("replace"===t.op)return a.newDocument=t.value,a.removed=e,a;if("move"===t.op||"copy"===t.op)return a.newDocument=As(e,t.from),"move"===t.op&&(a.removed=e),a;if("test"===t.op){if(a.test=Ns(e,t.value),!1===a.test)throw new Ts("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return a.newDocument=e,a}if("remove"===t.op)return a.removed=e,a.newDocument=null,a;if("_get"===t.op)return t.value=e,a;if(r)throw new Ts("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,t,e);return a}{a||(e=ws(e));const s=(t.path||"").split("/");let o,c,d,l=e,u=1,h=s.length;for(d="function"==typeof r?r:Rs;;){if(c=s[u],c&&-1!=c.indexOf("~")&&(c=Os(c)),n&&("__proto__"==c||"prototype"==c&&u>0&&"constructor"==s[u-1]))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&&void 0===o&&(void 0===l[c]?o=s.slice(0,u).join("/"):u==h-1&&(o=t.path),void 0!==o&&d(t,0,e,o)),u++,Array.isArray(l)){if("-"===c)c=l.length;else{if(r&&!Es(c))throw new Ts("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",i,t,e);Es(c)&&(c=~~c)}if(u>=h){if(r&&"add"===t.op&&c>l.length)throw new Ts("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,t,e);const a=Ss[t.op].call(t,l,c,e);if(!1===a.test)throw new Ts("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return a}}else if(u>=h){const r=xs[t.op].call(t,l,c,e);if(!1===r.test)throw new Ts("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return r}if(l=l[c],r&&u<h&&(!l||"object"!=typeof l))throw new Ts("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,t,e)}}}function Ps(e,t,r,a=!0,n=!0){if(r&&!Array.isArray(t))throw new Ts("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");a||(e=ws(e));const i=new Array(t.length);for(let a=0,s=t.length;a<s;a++)i[a]=js(e,t[a],r,!0,n,a),e=i[a].newDocument;return i.newDocument=e,i}function Rs(e,t,r,a){if("object"!=typeof e||null===e||Array.isArray(e))throw new Ts("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,r);if(!xs[e.op])throw new Ts("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,r);if("string"!=typeof e.path)throw new Ts("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,r);if(0!==e.path.indexOf("/")&&e.path.length>0)throw new Ts('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);if(("move"===e.op||"copy"===e.op)&&"string"!=typeof e.from)throw new Ts("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&void 0===e.value)throw new Ts("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&$s(e.value))throw new Ts("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);if(r)if("add"==e.op){var n=e.path.split("/").length,i=a.split("/").length;if(n!==i+1&&n!==i)throw new Ts("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if("replace"===e.op||"remove"===e.op||"_get"===e.op){if(e.path!==a)throw new Ts("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if("move"===e.op||"copy"===e.op){var s=function(e,t,r){try{if(!Array.isArray(e))throw new Ts("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)Ps(ws(t),ws(e),r||!0);else{r=r||Rs;for(var a=0;a<e.length;a++)r(e[a],a,t,void 0)}}catch(e){if(e instanceof Ts)return e;throw e}}([{op:"_get",path:e.from,value:void 0}],r);if(s&&"OPERATION_PATH_UNRESOLVABLE"===s.name)throw new Ts("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}function Ns(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){var r,a,n,i=Array.isArray(e),s=Array.isArray(t);if(i&&s){if((a=e.length)!=t.length)return!1;for(r=a;0!=r--;)if(!Ns(e[r],t[r]))return!1;return!0}if(i!=s)return!1;var o=Object.keys(e);if((a=o.length)!==Object.keys(t).length)return!1;for(r=a;0!=r--;)if(!t.hasOwnProperty(o[r]))return!1;for(r=a;0!=r--;)if(!Ns(e[n=o[r]],t[n]))return!1;return!0}return e!=e&&t!=t}const Cs=new class{getStore(){}run(e,t){return t()}enterWith(e){}},Ls=Symbol.for("lc:child_config");const Ms=new class{getInstance(){return Hi()??Cs}getRunnableConfig(){const e=this.getInstance();return e.getStore()?.extra?.[Ls]}runWithConfig(e,t,r){const a=rs._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),n=this.getInstance(),i=n.getStore(),s=a?.getParentRunId(),o=a?.handlers?.find((e=>"langchain_tracer"===e?.name));let c;return o&&s?c=o.convertToRunTree(s):r||(c=new ji({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[Ls]:e}),void 0!==i&&void 0!==i[Bi]&&(void 0===c&&(c={}),c[Bi]=i[Bi]),n.run(c,t)}initializeGlobalInstance(e){void 0===Hi()&&(e=>{globalThis[zi]=e})(e)}};async function Us(e){return rs._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function Ds(...e){const t={};for(const r of e.filter((e=>!!e)))for(const e of Object.keys(r))if("metadata"===e)t[e]={...t[e],...r[e]};else if("tags"===e){const a=t[e]??[];t[e]=[...new Set(a.concat(r[e]??[]))]}else if("configurable"===e)t[e]={...t[e],...r[e]};else if("timeout"===e)void 0===t.timeout?t.timeout=r.timeout:void 0!==r.timeout&&(t.timeout=Math.min(t.timeout,r.timeout));else if("signal"===e)void 0===t.signal?t.signal=r.signal:void 0!==r.signal&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,r.signal]):t.signal=r.signal);else if("callbacks"===e){const e=t.callbacks,a=r.callbacks;if(Array.isArray(a))if(e)if(Array.isArray(e))t.callbacks=e.concat(a);else{const r=e.copy();for(const e of a)r.addHandler(as(e),!0);t.callbacks=r}else t.callbacks=a;else if(a)if(e)if(Array.isArray(e)){const r=a.copy();for(const t of e)r.addHandler(as(t),!0);t.callbacks=r}else t.callbacks=new rs(a._parentRunId,{handlers:e.handlers.concat(a.handlers),inheritableHandlers:e.inheritableHandlers.concat(a.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(a.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(a.inheritableTags))),metadata:{...e.metadata,...a.metadata}});else t.callbacks=a}else{const a=e;t[a]=r[a]??t[a]}return t}const Fs=new Set(["string","number","boolean"]);function Zs(e){const t=Ms.getRunnableConfig();let r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){const{runId:e,runName:a,...n}=t;r=Object.entries(n).reduce(((e,[t,r])=>(void 0!==r&&(e[t]=r),e)),r)}if(e&&(r=Object.entries(e).reduce(((e,[t,r])=>(void 0!==r&&(e[t]=r),e)),r)),r?.configurable)for(const e of Object.keys(r.configurable))Fs.has(typeof r.configurable[e])&&!r.metadata?.[e]&&(r.metadata||(r.metadata={}),r.metadata[e]=r.configurable[e]);if(void 0!==r.timeout){if(r.timeout<=0)throw new Error("Timeout must be a positive number");const e=AbortSignal.timeout(r.timeout);void 0!==r.signal?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,e])):r.signal=e,delete r.timeout}return r}function zs(e={},{callbacks:t,maxConcurrency:r,recursionLimit:a,runName:n,configurable:i,runId:s}={}){const o=Zs(e);return void 0!==t&&(delete o.runName,o.callbacks=t),void 0!==a&&(o.recursionLimit=a),void 0!==r&&(o.maxConcurrency=r),void 0!==n&&(o.runName=n),void 0!==i&&(o.configurable={...o.configurable,...i}),void 0!==s&&delete o.runId,o}function Bs(e){return e?{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal}:void 0}async function Hs(e,t){if(void 0===t)return e;let r;return Promise.race([e.catch((e=>{if(!t?.aborted)throw e})),new Promise(((e,a)=>{r=()=>{a(new Error("Aborted"))},t.addEventListener("abort",r),t.aborted&&a(new Error("Aborted"))}))]).finally((()=>t.removeEventListener("abort",r)))}class qs extends ReadableStream{constructor(){super(...arguments),Object.defineProperty(this,"reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}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 e=this.reader.cancel();this.reader.releaseLock(),await e}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){const t=e.getReader();return new qs({start:e=>function r(){return t.read().then((({done:t,value:a})=>{if(!t)return e.enqueue(a),r();e.close()}))}(),cancel(){t.releaseLock()}})}static fromAsyncGenerator(e){return new qs({async pull(t){const{value:r,done:a}=await e.next();a&&t.close(),t.enqueue(r)},async cancel(t){await e.return(t)}})}}function Gs(e,t=2){const r=Array.from({length:t},(()=>[]));return r.map((async function*(t){for(;;)if(0===t.length){const t=await e.next();for(const e of r)e.push(t)}else{if(t[0].done)return;yield t.shift().value}}))}function Js(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if("string"==typeof e&&"string"==typeof t)return e+t;if("number"==typeof e&&"number"==typeof t)return e+t;if("concat"in e&&"function"==typeof e.concat)return e.concat(t);if("object"==typeof e&&"object"==typeof t){const r={...e};for(const[e,a]of Object.entries(t))e in r&&!Array.isArray(r[e])?r[e]=Js(r[e],a):r[e]=a;return r}throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}class Vs{constructor(e){Object.defineProperty(this,"generator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"setup",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signal",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResult",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResultUsed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise(((t,r)=>{Ms.runWithConfig(Bs(e.config),(async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then((e=>t(void 0)),r)}),!0)}))}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?Ms.runWithConfig(Bs(this.config),this.signal?async()=>Hs(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}}class Ws{constructor(e){Object.defineProperty(this,"ops",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),r=Ps({},t);return new Ks({ops:t,state:r[r.length-1].newDocument})}}class Ks extends Ws{constructor(e){super(e),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.state=e.state}concat(e){const t=this.ops.concat(e.ops),r=Ps(this.state,e.ops);return new Ks({ops:t,state:r[r.length-1].newDocument})}static fromRunLogPatch(e){const t=Ps({},e.ops);return new Ks({ops:e.ops,state:t[t.length-1].newDocument})}}const Xs=e=>"log_stream_tracer"===e.name;async function Ys(e,t){if("original"===t)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}=e;return["retriever","llm","prompt"].includes(e.run_type)?r:1!==Object.keys(r).length||""!==r?.input?r.input:void 0}async function Qs(e,t){const{outputs:r}=e;return"original"===t||["retriever","llm","prompt"].includes(e.run_type)?r:void 0!==r&&1===Object.keys(r).length&&void 0!==r?.output?r.output:r}class eo extends ea{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schemaFormat",{enumerable:!0,configurable:!0,writable:!0,value:"original"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keyMapByRunId",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"counterMapByRunName",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"log_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=qs.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;const t=e.tags??[];let r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.run_type)),void 0!==this.includeTags&&(r=r||void 0!==t.find((e=>this.includeTags?.includes(e)))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.run_type)),void 0!==this.excludeTags&&(r=r&&t.every((e=>!this.excludeTags?.includes(e)))),r}async*tapOutputIterable(e,t){for await(const r of t){if(e!==this.rootId){const t=this.keyMapByRunId[e];t&&await this.writer.write(new Ws({ops:[{op:"add",path:`/logs/${t}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(void 0===this.rootId&&(this.rootId=e.id,await this.writer.write(new Ws({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;void 0===this.counterMapByRunName[e.name]&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;const t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=1===t?e.name:`${e.name}:${t}`;const r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};"streaming_events"===this._schemaFormat&&(r.inputs=await Ys(e,this._schemaFormat)),await this.writer.write(new Ws({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{const t=this.keyMapByRunId[e.id];if(void 0===t)return;const r=[];"streaming_events"===this._schemaFormat&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await Ys(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await Qs(e,this._schemaFormat)}),void 0!==e.end_time&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});const a=new Ws({ops:r});await this.writer.write(a)}finally{if(e.id===this.rootId){const t=new Ws({ops:[{op:"replace",path:"/final_output",value:await Qs(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){const a=this.keyMapByRunId[e.id];if(void 0===a)return;let n;var i;void 0!==e.inputs.messages?(i=r?.chunk,n=void 0!==i&&void 0!==i.message?r?.chunk:new ga({id:`run-${e.id}`,content:t})):n=t;const s=new Ws({ops:[{op:"add",path:`/logs/${a}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${a}/streamed_output/-`,value:n}]});await this.writer.write(s)}}class to{constructor(e){Object.defineProperty(this,"text",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"generationInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new to({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}}function ro({name:e,serialized:t}){return void 0!==e?e:void 0!==t?.name?t.name:void 0!==t?.id&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}const ao=e=>"event_stream_tracer"===e.name;class no extends ea{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"runInfoMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"tappedPromises",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"event_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=qs.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const t=e.tags??[];let r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.runType)),void 0!==this.includeTags&&(r=r||void 0!==t.find((e=>this.includeTags?.includes(e)))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.runType)),void 0!==this.excludeTags&&(r=r&&t.every((e=>!this.excludeTags?.includes(e)))),r}async*tapOutputIterable(e,t){const r=await t.next();if(r.done)return;const a=this.runInfoMap.get(e);if(void 0===a)return void(yield r.value);function n(e,t){return"llm"===e&&"string"==typeof t?new to({text:t}):t}let i=this.tappedPromises.get(e);if(void 0===i){let s;i=new Promise((e=>{s=e})),this.tappedPromises.set(e,i);try{const i={event:`on_${a.runType}_stream`,run_id:e,name:a.name,tags:a.tags,metadata:a.metadata,data:{}};await this.send({...i,data:{chunk:n(a.runType,r.value)}},a),yield r.value;for await(const e of t)"tool"!==a.runType&&"retriever"!==a.runType&&await this.send({...i,data:{chunk:n(a.runType,e)}},a),yield e}finally{s()}}else{yield r.value;for await(const e of t)yield e}}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){const r=this.tappedPromises.get(e.run_id);void 0!==r?r.then((()=>{this.send(e,t)})):await this.send(e,t)}async onLLMStart(e){const t=ro(e),r=void 0!==e.inputs.messages?"chat_model":"llm",a={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,a);const n=`on_${r}_start`;await this.send({event:n,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},a)}async onLLMNewToken(e,t,r){const a=this.runInfoMap.get(e.id);let n,i;if(void 0===a)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(1!==this.runInfoMap.size){if("chat_model"===a.runType)i="on_chat_model_stream",n=void 0===r?.chunk?new ga({content:t,id:`run-${e.id}`}):r.chunk.message;else{if("llm"!==a.runType)throw new Error(`Unexpected run type ${a.runType}`);i="on_llm_stream",n=void 0===r?.chunk?new to({text:t}):r.chunk}await this.send({event:i,data:{chunk:n},run_id:e.id,name:a.name,tags:a.tags,metadata:a.metadata},a)}}async onLLMEnd(e){const t=this.runInfoMap.get(e.id);let r;if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const a=e.outputs?.generations;let n;if("chat_model"===t.runType){for(const e of a??[]){if(void 0!==n)break;n=e[0]?.message}r="on_chat_model_end"}else{if("llm"!==t.runType)throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);n={generations:a?.map((e=>e.map((e=>({text:e.text,generationInfo:e.generationInfo}))))),llmOutput:e.outputs?.llmOutput??{}},r="on_llm_end"}await this.sendEndEvent({event:r,data:{output:n,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){const t=ro(e),r=e.run_type??"chain",a={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type};let n={};""===e.inputs.input&&1===Object.keys(e.inputs).length?(n={},a.inputs={}):void 0!==e.inputs.input?(n.input=e.inputs.input,a.inputs=e.inputs.input):(n.input=e.inputs,a.inputs=e.inputs),this.runInfoMap.set(e.id,a),await this.send({event:`on_${r}_start`,data:n,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},a)}async onChainEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const r=`on_${e.run_type}_end`,a=e.inputs??t.inputs??{},n={output:e.outputs?.output??e.outputs,input:a};a.input&&1===Object.keys(a).length&&(n.input=a.input,t.inputs=a.input),await this.sendEndEvent({event:r,data:n,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){const t=ro(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},r)}async onToolEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(void 0===t.inputs)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const r=void 0===e.outputs?.output?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){const t=ro(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,r),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onRetrieverEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,r){const a=this.runInfoMap.get(r);if(void 0===a)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:a.tags,metadata:a.metadata,data:t},a)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally((()=>{this.writer.close()}))}}class io extends ea{constructor({config:e,onStart:t,onEnd:r,onError:a}){super({_awaitHandler:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RootListenersTracer"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnEnd",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.config=e,this.argOnStart=t,this.argOnEnd=r,this.argOnError=a}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}}function so(e){return!!e&&e.lc_runnable}class oo{constructor(e){Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let r=void 0===this.includeNames&&void 0===this.includeTypes&&void 0===this.includeTags;const a=e.tags??[];return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(t)),void 0!==this.includeTags&&(r=r||a.some((e=>this.includeTags?.includes(e)))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(t)),void 0!==this.excludeTags&&(r=r&&a.every((e=>!this.excludeTags?.includes(e)))),r}}const co=Symbol("Let zodToJsonSchema decide on which parser to use"),lo={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},uo=e=>{const t=(e=>"string"==typeof e?{...lo,name:e}:{...lo,...e})(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map((([e,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}])))}};function ho(e,t,r,a){a?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function po(e,t,r,a,n){e[t]=r,ho(e,t,a,n)}function mo(e,t){return No(e.type._def,t)}function fo(e,t,r){const a=r??t.dateStrategy;if(Array.isArray(a))return{anyOf:a.map(((r,a)=>fo(e,t,r)))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return go(e,t)}}const go=(e,t)=>{const r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(const a of e.checks)switch(a.kind){case"min":po(r,"minimum",a.value,a.message,t);break;case"max":po(r,"maximum",a.value,a.message,t)}return r};let yo;const _o=/^[cC][^\s-]{8,}$/,bo=/^[0-9a-z]+$/,vo=/^[0-9A-HJKMNP-TV-Z]{26}$/,wo=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,Eo=()=>(void 0===yo&&(yo=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),yo),Oo=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$o=/^[a-zA-Z0-9_-]{21}$/;function ko(e,t){const r={type:"string"};function a(e){return"escape"===t.patternStrategy?Io(e):e}if(e.checks)for(const n of e.checks)switch(n.kind){case"min":po(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":po(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":To(r,"email",n.message,t);break;case"format:idn-email":To(r,"idn-email",n.message,t);break;case"pattern:zod":xo(r,wo,n.message,t)}break;case"url":To(r,"uri",n.message,t);break;case"uuid":To(r,"uuid",n.message,t);break;case"regex":xo(r,n.regex,n.message,t);break;case"cuid":xo(r,_o,n.message,t);break;case"cuid2":xo(r,bo,n.message,t);break;case"startsWith":xo(r,RegExp(`^${a(n.value)}`),n.message,t);break;case"endsWith":xo(r,RegExp(`${a(n.value)}$`),n.message,t);break;case"datetime":To(r,"date-time",n.message,t);break;case"date":To(r,"date",n.message,t);break;case"time":To(r,"time",n.message,t);break;case"duration":To(r,"duration",n.message,t);break;case"length":po(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t),po(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":xo(r,RegExp(a(n.value)),n.message,t);break;case"ip":"v6"!==n.version&&To(r,"ipv4",n.message,t),"v4"!==n.version&&To(r,"ipv6",n.message,t);break;case"emoji":xo(r,Eo,n.message,t);break;case"ulid":xo(r,vo,n.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":To(r,"binary",n.message,t);break;case"contentEncoding:base64":po(r,"contentEncoding","base64",n.message,t);break;case"pattern:zod":xo(r,Oo,n.message,t)}break;case"nanoid":xo(r,$o,n.message,t)}return r}const Io=e=>Array.from(e).map((e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`)).join(""),To=(e,t,r,a)=>{e.format||e.anyOf?.some((e=>e.format))?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&a.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&a.errorMessages&&{errorMessage:{format:r}}})):po(e,"format",t,r,a)},xo=(e,t,r,a)=>{e.pattern||e.allOf?.some((e=>e.pattern))?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&a.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:So(t,a),...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):po(e,"pattern",So(t,a),r,a)},So=(e,t)=>{const r="function"==typeof e?e():e;if(!t.applyRegexFlags||!r.flags)return r.source;const a=r.flags.includes("i"),n=r.flags.includes("m"),i=r.flags.includes("s"),s=a?r.source.toLowerCase():r.source;let o="",c=!1,d=!1,l=!1;for(let e=0;e<s.length;e++)if(c)o+=s[e],c=!1;else{if(a)if(d){if(s[e].match(/[a-z]/)){l?(o+=s[e],o+=`${s[e-2]}-${s[e]}`.toUpperCase(),l=!1):"-"===s[e+1]&&s[e+2]?.match(/[a-z]/)?(o+=s[e],l=!0):o+=`${s[e]}${s[e].toUpperCase()}`;continue}}else if(s[e].match(/[a-z]/)){o+=`[${s[e]}${s[e].toUpperCase()}]`;continue}if(n){if("^"===s[e]){o+="(^|(?<=[\r\n]))";continue}if("$"===s[e]){o+="($|(?=[\r\n]))";continue}}i&&"."===s[e]?o+=d?`${s[e]}\r\n`:`[${s[e]}\r\n]`:(o+=s[e],"\\"===s[e]?c=!0:d&&"]"===s[e]?d=!1:d||"["!==s[e]||(d=!0))}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return o};function Ao(e,t){if("openApi3"===t.target&&e.keyType?._def.typeName===Ze.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce(((r,a)=>({...r,[a]:No(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",a]})??{}})),{}),additionalProperties:!1};const r={type:"object",additionalProperties:No(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===Ze.ZodString&&e.keyType._def.checks?.length){const{type:a,...n}=ko(e.keyType._def,t);return{...r,propertyNames:n}}if(e.keyType?._def.typeName===Ze.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===Ze.ZodBranded&&e.keyType._def.type._def.typeName===Ze.ZodString&&e.keyType._def.type._def.checks?.length){const{type:a,...n}=mo(e.keyType._def,t);return{...r,propertyNames:n}}return r}const jo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const Po=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map(((e,r)=>No(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]}))).filter((e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0)));return r.length?{anyOf:r}:void 0};function Ro(e,t){return"strict"===t.removeAdditionalStrategy?"ZodNever"===e.catchall._def.typeName?"strict"!==e.unknownKeys:No(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0:"ZodNever"===e.catchall._def.typeName?"passthrough"===e.unknownKeys:No(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0}function No(e,t,r=!1){const a=t.seen.get(e);if(t.override){const n=t.override?.(e,t,a,r);if(n!==co)return n}if(a&&!r){const e=Co(a,t);if(void 0!==e)return e}const n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);const i=Mo(e,e.typeName,t);return i&&Uo(e,t,i),n.jsonSchema=i,i}const Co=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Lo(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every(((e,r)=>t.currentPath[r]===e))?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{}):"seen"===t.$refStrategy?{}:void 0}},Lo=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")},Mo=(e,t,r)=>{switch(t){case Ze.ZodString:return ko(e,r);case Ze.ZodNumber:return function(e,t){const r={type:"number"};if(!e.checks)return r;for(const a of e.checks)switch(a.kind){case"int":r.type="integer",ho(r,"type",a.message,t);break;case"min":"jsonSchema7"===t.target?a.inclusive?po(r,"minimum",a.value,a.message,t):po(r,"exclusiveMinimum",a.value,a.message,t):(a.inclusive||(r.exclusiveMinimum=!0),po(r,"minimum",a.value,a.message,t));break;case"max":"jsonSchema7"===t.target?a.inclusive?po(r,"maximum",a.value,a.message,t):po(r,"exclusiveMaximum",a.value,a.message,t):(a.inclusive||(r.exclusiveMaximum=!0),po(r,"maximum",a.value,a.message,t));break;case"multipleOf":po(r,"multipleOf",a.value,a.message,t)}return r}(e,r);case Ze.ZodObject:return function(e,t){const r={type:"object",...Object.entries(e.shape()).reduce(((e,[r,a])=>{if(void 0===a||void 0===a._def)return e;const n=No(a._def,{...t,currentPath:[...t.currentPath,"properties",r],propertyPath:[...t.currentPath,"properties",r]});return void 0===n?e:{properties:{...e.properties,[r]:n},required:a.isOptional()?e.required:[...e.required,r]}}),{properties:{},required:[]}),additionalProperties:Ro(e,t)};return r.required.length||delete r.required,r}(e,r);case Ze.ZodBigInt:return function(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const a of e.checks)switch(a.kind){case"min":"jsonSchema7"===t.target?a.inclusive?po(r,"minimum",a.value,a.message,t):po(r,"exclusiveMinimum",a.value,a.message,t):(a.inclusive||(r.exclusiveMinimum=!0),po(r,"minimum",a.value,a.message,t));break;case"max":"jsonSchema7"===t.target?a.inclusive?po(r,"maximum",a.value,a.message,t):po(r,"exclusiveMaximum",a.value,a.message,t):(a.inclusive||(r.exclusiveMaximum=!0),po(r,"maximum",a.value,a.message,t));break;case"multipleOf":po(r,"multipleOf",a.value,a.message,t)}return r}(e,r);case Ze.ZodBoolean:return{type:"boolean"};case Ze.ZodDate:return fo(e,r);case Ze.ZodUndefined:return{not:{}};case Ze.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(r);case Ze.ZodArray:return function(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==Ze.ZodAny&&(r.items=No(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&po(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&po(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(po(r,"minItems",e.exactLength.value,e.exactLength.message,t),po(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}(e,r);case Ze.ZodUnion:case Ze.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return Po(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((e=>e._def.typeName in jo&&(!e._def.checks||!e._def.checks.length)))){const e=r.reduce(((e,t)=>{const r=jo[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e}),[]);return{type:e.length>1?e:e[0]}}if(r.every((e=>"ZodLiteral"===e._def.typeName&&!e.description))){const e=r.reduce(((e,t)=>{const r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}}),[]);if(e.length===r.length){const t=e.filter(((e,t,r)=>r.indexOf(e)===t));return{type:t.length>1?t:t[0],enum:r.reduce(((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value]),[])}}}else if(r.every((e=>"ZodEnum"===e._def.typeName)))return{type:"string",enum:r.reduce(((e,t)=>[...e,...t._def.values.filter((t=>!e.includes(t)))]),[])};return Po(e,t)}(e,r);case Ze.ZodIntersection:return function(e,t){const r=[No(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),No(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((e=>!!e));let a="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const n=[];return r.forEach((e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:r,...a}=e;t=a}else a=void 0;n.push(t)}else n.push(...e.allOf),void 0===e.unevaluatedProperties&&(a=void 0);var t})),n.length?{allOf:n,...a}:void 0}(e,r);case Ze.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map(((e,r)=>No(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[]),additionalItems:No(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map(((e,r)=>No(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[])}}(e,r);case Ze.ZodRecord:return Ao(e,r);case Ze.ZodLiteral:return function(e,t){const r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}(e,r);case Ze.ZodEnum:return function(e){return{type:"string",enum:e.values}}(e);case Ze.ZodNativeEnum:return function(e){const t=e.values,r=Object.keys(e.values).filter((e=>"number"!=typeof t[t[e]])),a=r.map((e=>t[e])),n=Array.from(new Set(a.map((e=>typeof e))));return{type:1===n.length?"string"===n[0]?"string":"number":["string","number"],enum:a}}(e);case Ze.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:jo[e.innerType._def.typeName],nullable:!0}:{type:[jo[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const r=No(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const r=No(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}(e,r);case Ze.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return No(e.innerType._def,t);const r=No(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}})(e,r);case Ze.ZodMap:return function(e,t){return"record"===t.mapStrategy?Ao(e,t):{type:"array",maxItems:125,items:{type:"array",items:[No(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},No(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}(e,r);case Ze.ZodSet:return function(e,t){const r={type:"array",uniqueItems:!0,items:No(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&po(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&po(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}(e,r);case Ze.ZodLazy:return No(e.getter()._def,r);case Ze.ZodPromise:return function(e,t){return No(e.type._def,t)}(e,r);case Ze.ZodNaN:case Ze.ZodNever:return{not:{}};case Ze.ZodEffects:return function(e,t){return"input"===t.effectStrategy?No(e.schema._def,t):{}}(e,r);case Ze.ZodAny:case Ze.ZodUnknown:return{};case Ze.ZodDefault:return function(e,t){return{...No(e.innerType._def,t),default:e.defaultValue()}}(e,r);case Ze.ZodBranded:return mo(e,r);case Ze.ZodReadonly:case Ze.ZodCatch:return((e,t)=>No(e.innerType._def,t))(e,r);case Ze.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return No(e.in._def,t);if("output"===t.pipeStrategy)return No(e.out._def,t);const r=No(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,No(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter((e=>void 0!==e))}})(e,r);case Ze.ZodFunction:case Ze.ZodVoid:case Ze.ZodSymbol:default:return}},Uo=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),Do=(e,t)=>{const r=uo(t),a="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce(((e,[t,a])=>({...e,[t]:No(a._def,{...r,currentPath:[...r.basePath,r.definitionPath,t]},!0)??{}})),{}):void 0,n="string"==typeof t?t:"title"===t?.nameStrategy?void 0:t?.name,i=No(e._def,void 0===n?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},s="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==s&&(i.title=s);const o=void 0===n?a?{...i,[r.definitionPath]:a}:i:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...a,[n]:i}};return"jsonSchema7"===r.target?o.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"===r.target&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o};function Fo(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}const Zo=["*","_","`"];function zo(e,t,r){const{firstNode:a,lastNode:n,nodeColors:i,withStyles:s=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=r??{};let d=s?`%%{init: {'flowchart': {'curve': '${o}'}}}%%\ngraph TD;\n`:"graph TD;\n";if(s){const t="default",r={[t]:"{0}({1})"};void 0!==a&&(r[a]="{0}([{1}]):::first"),void 0!==n&&(r[n]="{0}([{1}]):::last");for(const[a,n]of Object.entries(e)){const e=n.name.split(":").pop()??"";let i=Zo.some((t=>e.startsWith(t)&&e.endsWith(t)))?`<p>${e}</p>`:e;Object.keys(n.metadata??{}).length&&(i+=`<hr/><small><em>${Object.entries(n.metadata??{}).map((([e,t])=>`${e} = ${t}`)).join("\n")}</em></small>`);const s=(r[a]??r[t]).replace("{0}",Fo(a)).replace("{1}",i);d+=`\t${s}\n`}}const l={};for(const e of t){const t=e.source.split(":"),r=e.target.split(":"),a=t.filter(((e,t)=>e===r[t])).join(":");l[a]||(l[a]=[]),l[a].push(e)}const u=new Set;function h(e,t){const r=1===e.length&&e[0].source===e[0].target;if(t&&!r){const e=t.split(":").pop();if(u.has(e))throw new Error(`Found duplicate subgraph '${e}' -- 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.`);u.add(e),d+=`\tsubgraph ${e}\n`}for(const t of e){const{source:e,target:r,data:a,conditional:n}=t;let i="";if(void 0!==a){let e=a;const t=e.split(" ");t.length>c&&(e=Array.from({length:Math.ceil(t.length/c)},((e,r)=>t.slice(r*c,(r+1)*c).join(" "))).join("&nbsp;<br>&nbsp;")),i=n?` -. &nbsp;${e}&nbsp; .-> `:` -- &nbsp;${e}&nbsp; --\x3e `}else i=n?" -.-> ":" --\x3e ";d+=`\t${Fo(e)}${i}${Fo(r)};\n`}for(const e in l)e.startsWith(`${t}:`)&&e!==t&&h(l[e],e);t&&!r&&(d+="\tend\n")}h(l[""]??[],"");for(const e in l)e.includes(":")||""===e||h(l[e],e);return s&&(d+=function(e){let t="";for(const[r,a]of Object.entries(e))t+=`\tclassDef ${r} ${a};\n`;return t}(i??{})),d}function Bo(e,t){if(void 0!==e&&!qt(e))return e;if(!so(t))return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e,e}catch(e){return t.getName()}}function Ho(e){return so(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...Do(e.data.schema),title:e.data.name}}}class qo{constructor(e){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach(((t,r)=>{e[t.id]=qt(t.id)?r:t.id})),{nodes:Object.values(this.nodes).map((t=>({id:e[t.id],...Ho(t)}))),edges:this.edges.map((t=>{const r={source:e[t.source],target:e[t.target]};return void 0!==t.data&&(r.data=t.data),void 0!==t.conditional&&(r.conditional=t.conditional),r}))}}addNode(e,t,r){if(void 0!==t&&void 0!==this.nodes[t])throw new Error(`Node with id ${t} already exists`);const a=t??Yt(),n={id:a,data:e,name:Bo(t,e),metadata:r};return this.nodes[a]=n,n}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter((t=>t.source!==e.id&&t.target!==e.id))}addEdge(e,t,r,a){if(void 0===this.nodes[e.id])throw new Error(`Source node ${e.id} not in graph`);if(void 0===this.nodes[t.id])throw new Error(`Target node ${t.id} not in graph`);const n={source:e.id,target:t.id,data:r,conditional:a};return this.edges.push(n),n}firstNode(){return Go(this)}lastNode(){return Jo(this)}extend(e,t=""){let r=t;Object.values(e.nodes).map((e=>e.id)).every(qt)&&(r="");const a=e=>r?`${r}:${e}`:e;Object.entries(e.nodes).forEach((([e,t])=>{this.nodes[a(e)]={...t,id:a(e)}}));const n=e.edges.map((e=>({...e,source:a(e.source),target:a(e.target)})));this.edges=[...this.edges,...n];const i=e.firstNode(),s=e.lastNode();return[i?{id:a(i.id),data:i.data}:void 0,s?{id:a(s.id),data:s.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&Go(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&Jo(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map((e=>[e.id,e.name]))),t=new Map;Object.values(e).forEach((e=>{t.set(e,(t.get(e)||0)+1)}));const r=r=>{const a=e[r];return qt(r)&&1===t.get(a)?a:r};return new qo({nodes:Object.fromEntries(Object.entries(this.nodes).map((([e,t])=>[r(e),{...t,id:r(e)}]))),edges:this.edges.map((e=>({...e,source:r(e.source),target:r(e.target)})))})}drawMermaid(e){const{withStyles:t,curveStyle:r,nodeColors:a={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:n}=e??{},i=this.reid(),s=i.firstNode(),o=i.lastNode();return zo(i.nodes,i.edges,{firstNode:s?.id,lastNode:o?.id,withStyles:t,curveStyle:r,nodeColors:a,wrapLabelNWords:n})}async drawMermaidPng(e){return async function(e,t){let{backgroundColor:r="white"}=t??{};const a=btoa(e);void 0!==r&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));const n=`https://mermaid.ink/img/${a}?bgColor=${r}`,i=await fetch(n);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("\n"));return await i.blob()}(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}}function Go(e,t=[]){const r=new Set(e.edges.filter((e=>!t.includes(e.source))).map((e=>e.target))),a=[];for(const n of Object.values(e.nodes))t.includes(n.id)||r.has(n.id)||a.push(n);return 1===a.length?a[0]:void 0}function Jo(e,t=[]){const r=new Set(e.edges.filter((e=>!t.includes(e.target))).map((e=>e.source))),a=[];for(const n of Object.values(e.nodes))t.includes(n.id)||r.has(n.id)||a.push(n);return 1===a.length?a[0]:void 0}function Vo(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.iterator]&&"function"==typeof e.next}function Wo(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.asyncIterator]}function*Ko(e,t){for(;;){const{value:r,done:a}=Ms.runWithConfig(Bs(e),t.next.bind(t),!0);if(a)break;yield r}}async function*Xo(e,t){const r=t[Symbol.asyncIterator]();for(;;){const{value:a,done:n}=await Ms.runWithConfig(Bs(e),r.next.bind(t),!0);if(n)break;yield a}}function Yo(e,t){return!e||Array.isArray(e)||e instanceof Date||"object"!=typeof e?{[t]:e}:e}class Qo extends gr{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(e){const t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}bind(e){return new ec({bound:this,kwargs:e,config:{}})}map(){return new tc({bound:this})}withRetry(e){return new rc({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new ec({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new oc({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(Zs);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");const r=Object.fromEntries(Object.entries(e).filter((([e])=>"runId"!==e)));return Array.from({length:t},((t,a)=>Zs(0===a?e:r)))}return Array.from({length:t},(()=>Zs(e)))}async batch(e,t,r){const a=this._getOptionsList(t??{},e.length),n=a[0]?.maxConcurrency??r?.maxConcurrency,i=new ss({maxConcurrency:n,onFailedAttempt:e=>{throw e}}),s=e.map(((e,t)=>i.call((async()=>{try{return await this.invoke(e,a[t])}catch(e){if(r?.returnExceptions)return e;throw e}}))));return Promise.all(s)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const r=Zs(t),a=new Vs({generator:this._streamIterator(e,r),config:r});return await a.setup,qs.fromAsyncGenerator(a)}_separateRunnableConfigFromCallOptions(e){let t;t=Zs(void 0===e?e:{callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});const r={...e};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,[t,r]}async _callWithConfig(e,t,r){const a=Zs(r),n=await Us(a),i=await(n?.handleChainStart(this.toJSON(),Yo(t,"input"),a.runId,a?.runType,void 0,void 0,a?.runName??this.getName()));let s;delete a.runId;try{const n=e.call(this,t,a,i);s=await Hs(n,r?.signal)}catch(e){throw await(i?.handleChainError(e)),e}return await(i?.handleChainEnd(Yo(s,"output"))),s}async _batchWithConfig(e,t,r,a){const n=this._getOptionsList(r??{},t.length),i=await Promise.all(n.map(Us)),s=await Promise.all(i.map((async(e,r)=>{const a=await(e?.handleChainStart(this.toJSON(),Yo(t[r],"input"),n[r].runId,n[r].runType,void 0,void 0,n[r].runName??this.getName()));return delete n[r].runId,a})));let o;try{const r=e.call(this,t,n,s,a);o=await Hs(r,n?.[0]?.signal)}catch(e){throw await Promise.all(s.map((t=>t?.handleChainError(e)))),e}return await Promise.all(s.map((e=>e?.handleChainEnd(Yo(o,"output"))))),o}async*_transformStreamWithConfig(e,t,r){let a,n,i=!0,s=!0;const o=Zs(r),c=await Us(o);let d;try{const l=await async function(e,t,r,a,...n){const i=new Vs({generator:t,startSetup:r,signal:a}),s=await i.setup;return{output:e(i,s,...n),setup:s}}(t.bind(this),async function*(){for await(const t of e){if(i)if(void 0===a)a=t;else try{a=Js(a,t)}catch{a=void 0,i=!1}yield t}}(),(async()=>c?.handleChainStart(this.toJSON(),{input:""},o.runId,o.runType,void 0,void 0,o.runName??this.getName())),r?.signal,o);delete o.runId,d=l.setup;const u=d?.handlers.find(ao);let h=l.output;void 0!==u&&void 0!==d&&(h=u.tapOutputIterable(d.runId,h));const p=d?.handlers.find(Xs);void 0!==p&&void 0!==d&&(h=p.tapOutputIterable(d.runId,h));for await(const e of h)if(yield e,s)if(void 0===n)n=e;else try{n=Js(n,e)}catch{n=void 0,s=!1}}catch(e){throw await(d?.handleChainError(e,void 0,void 0,void 0,{inputs:Yo(a,"input")})),e}await(d?.handleChainEnd(n??{},void 0,void 0,void 0,{inputs:Yo(a,"input")}))}getGraph(e){const t=new qo,r=t.addNode({name:`${this.getName()}Input`,schema:$t.any()}),a=t.addNode(this),n=t.addNode({name:`${this.getName()}Output`,schema:$t.any()});return t.addEdge(r,a),t.addEdge(a,n),t}pipe(e){return new ac({first:this,last:cc(e)})}pick(e){return this.pipe(new lc(e))}assign(e){return this.pipe(new dc(new nc({steps:e})))}async*transform(e,t){let r;for await(const t of e)r=void 0===r?t:Js(r,t);yield*this._streamIterator(r,Zs(t))}async*streamLog(e,t,r){const a=new eo({...r,autoClose:!1,_schemaFormat:"original"}),n=Zs(t);yield*this._streamLog(e,a,n)}async*_streamLog(e,t,r){const{callbacks:a}=r;if(void 0===a)r.callbacks=[t];else if(Array.isArray(a))r.callbacks=a.concat([t]);else{const e=a.copy();e.addHandler(t,!0),r.callbacks=e}const n=this.stream(e,r);const i=async function(){try{const e=await n;for await(const r of e){const e=new Ws({ops:[{op:"add",path:"/streamed_output/-",value:r}]});await t.writer.write(e)}}finally{await t.writer.close()}}();try{for await(const e of t)yield e}finally{await i}}streamEvents(e,t,r){let a;if("v1"===t.version)a=this._streamEventsV1(e,t,r);else{if("v2"!==t.version)throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');a=this._streamEventsV2(e,t,r)}return"text/event-stream"===t.encoding?function(e){const t=new TextEncoder,r=new ReadableStream({async start(r){for await(const a of e)r.enqueue(t.encode(`event: data\ndata: ${JSON.stringify(a)}\n\n`));r.enqueue(t.encode("event: end\n\n")),r.close()}});return qs.fromReadableStream(r)}(a):qs.fromAsyncGenerator(a)}async*_streamEventsV2(e,t,r){const a=new no({...r,autoClose:!1}),n=Zs(t),i=n.runId??Yt();n.runId=i;const s=n.callbacks;if(void 0===s)n.callbacks=[a];else if(Array.isArray(s))n.callbacks=s.concat(a);else{const e=s.copy();e.addHandler(a,!0),n.callbacks=e}const o=new AbortController,c=this;const d=async function(){try{let r;t?.signal?"any"in AbortSignal?r=AbortSignal.any([o.signal,t.signal]):(r=t.signal,t.signal.addEventListener("abort",(()=>{o.abort()}),{once:!0})):r=o.signal;const s=await c.stream(e,{...n,signal:r}),d=a.tapOutputIterable(i,s);for await(const e of d)if(o.signal.aborted)break}finally{await a.finish()}}();let l,u=!1;try{for await(const t of a)u?(t.run_id===l&&t.event.endsWith("_end")&&t.data?.input&&delete t.data.input,yield t):(t.data.input=e,u=!0,l=t.run_id,yield t)}finally{o.abort(),await d}}async*_streamEventsV1(e,t,r){let a,n=!1;const i=Zs(t),s=i.tags??[],o=i.metadata??{},c=i.runName??this.getName(),d=new eo({...r,autoClose:!1,_schemaFormat:"streaming_events"}),l=new oo({...r}),u=this._streamLog(e,d,i);for await(const t of u){if(a=a?a.concat(t):Ks.fromRunLogPatch(t),void 0===a.state)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!n){n=!0;const t={...a.state},r={run_id:t.id,event:`on_${t.type}_start`,name:c,tags:s,metadata:o,data:{input:e}};l.includeEvent(r,t.type)&&(yield r)}const r=t.ops.filter((e=>e.path.startsWith("/logs/"))).map((e=>e.path.split("/")[2])),i=[...new Set(r)];for(const e of i){let t,r={};const n=a.state.logs[e];if(t=void 0===n.end_time?n.streamed_output.length>0?"stream":"start":"end","start"===t)void 0!==n.inputs&&(r.input=n.inputs);else if("end"===t)void 0!==n.inputs&&(r.input=n.inputs),r.output=n.final_output;else if("stream"===t){const e=n.streamed_output.length;if(1!==e)throw new Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${n.name}"`);r={chunk:n.streamed_output[0]},n.streamed_output=[]}yield{event:`on_${n.type}_${t}`,name:n.name,run_id:n.id,tags:n.tags,metadata:n.metadata,data:r}}const{state:d}=a;if(d.streamed_output.length>0){const e=d.streamed_output.length;if(1!==e)throw new Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${d.name}"`);const t={chunk:d.streamed_output[0]};d.streamed_output=[];const r={event:`on_${d.type}_stream`,run_id:d.id,tags:s,metadata:o,name:c,data:t};l.includeEvent(r,d.type)&&(yield r)}}const h=a?.state;if(void 0!==h){const e={event:`on_${h.type}_end`,name:c,run_id:h.id,tags:s,metadata:o,data:{output:h.final_output}};l.includeEvent(e,h.type)&&(yield e)}}static isRunnable(e){return so(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new ec({bound:this,config:{},configFactories:[a=>({callbacks:[new io({config:a,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return function(e,t){const r=t.name??e.getName(),a=t.description??t.schema?.description;if(t.schema.constructor===$t.ZodString)return new uc({name:r,description:a,schema:$t.object({input:$t.string()}).transform((e=>e.input)),bound:e});return new uc({name:r,description:a,schema:t.schema,bound:e})}(this,e)}}class ec extends Qo{static lc_name(){return"RunnableBinding"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"configFactories",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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 t=Ds(this.config,...e);return Ds(t,...this.configFactories?await Promise.all(this.configFactories.map((async e=>await e(t)))):[])}bind(e){return new this.constructor({bound:this.bound,kwargs:{...this.kwargs,...e},config:this.config})}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new this.constructor({bound:this.bound.withRetry(e),kwargs:this.kwargs,config:this.config})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(Zs(t),this.kwargs))}async batch(e,t,r){const a=Array.isArray(t)?await Promise.all(t.map((async e=>this._mergeConfig(Zs(e),this.kwargs)))):await this._mergeConfig(Zs(t),this.kwargs);return this.bound.batch(e,a,r)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(Zs(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(Zs(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(Zs(t),this.kwargs))}streamEvents(e,t,r){const a=this;return qs.fromAsyncGenerator(async function*(){yield*a.bound.streamEvents(e,{...await a._mergeConfig(Zs(t),a.kwargs),version:t.version},r)}())}static isRunnableBinding(e){return e.bound&&Qo.isRunnable(e.bound)}withListeners({onStart:e,onEnd:t,onError:r}){return new ec({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[a=>({callbacks:[new io({config:a,onStart:e,onEnd:t,onError:r})]})]})}}class tc extends Qo{static lc_name(){return"RunnableEach"}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound}bind(e){return new tc({bound:this.bound.bind(e)})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _invoke(e,t,r){return this.bound.batch(e,zs(t,{callbacks:r?.getChild()}))}withListeners({onStart:e,onEnd:t,onError:r}){return new tc({bound:this.bound.withListeners({onStart:e,onEnd:t,onError:r})})}}class rc extends ec{static lc_name(){return"RunnableRetry"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"maxAttemptNumber",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:()=>{}}),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,r){const a=e>1?`retry:attempt:${e}`:void 0;return zs(t,{callbacks:r?.getChild(a)})}async _invoke(e,t,r){return ka((a=>super.invoke(e,this._patchConfigForRetry(a,t,r))),{onFailedAttempt:t=>this.onFailedAttempt(t,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,r,a){const n={};try{await ka((async i=>{const s=e.map(((e,t)=>t)).filter((e=>void 0===n[e.toString()]||n[e.toString()]instanceof Error)),o=s.map((t=>e[t])),c=s.map((e=>this._patchConfigForRetry(i,t?.[e],r?.[e]))),d=await super.batch(o,c,{...a,returnExceptions:!0});let l;for(let e=0;e<d.length;e+=1){const t=d[e],r=s[e];t instanceof Error&&void 0===l&&(l=t,l.input=o[e]),n[r.toString()]=t}if(l)throw l;return d}),{onFailedAttempt:e=>this.onFailedAttempt(e,e.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(e){if(!0!==a?.returnExceptions)throw e}return Object.keys(n).sort(((e,t)=>parseInt(e,10)-parseInt(t,10))).map((e=>n[parseInt(e,10)]))}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}}class ac extends Qo{static lc_name(){return"RunnableSequence"}constructor(e){super(e),Object.defineProperty(this,"first",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"middle",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"last",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitSequenceTags",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),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,t){const r=Zs(t),a=await Us(r),n=await(a?.handleChainStart(this.toJSON(),Yo(e,"input"),r.runId,void 0,void 0,void 0,r?.runName));delete r.runId;let i,s=e;try{const e=[this.first,...this.middle];for(let a=0;a<e.length;a+=1){const i=e[a].invoke(s,zs(r,{callbacks:n?.getChild(this.omitSequenceTags?void 0:`seq:step:${a+1}`)}));s=await Hs(i,t?.signal)}if(t?.signal?.aborted)throw new Error("Aborted");i=await this.last.invoke(s,zs(r,{callbacks:n?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(e){throw await(n?.handleChainError(e)),e}return await(n?.handleChainEnd(Yo(i,"output"))),i}async batch(e,t,r){const a=this._getOptionsList(t??{},e.length),n=await Promise.all(a.map(Us)),i=await Promise.all(n.map((async(t,r)=>{const n=await(t?.handleChainStart(this.toJSON(),Yo(e[r],"input"),a[r].runId,void 0,void 0,void 0,a[r].runName));return delete a[r].runId,n})));let s=e;try{for(let e=0;e<this.steps.length;e+=1){const t=this.steps[e].batch(s,i.map(((t,r)=>{const n=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return zs(a[r],{callbacks:n})})),r);s=await Hs(t,a[0]?.signal)}}catch(e){throw await Promise.all(i.map((t=>t?.handleChainError(e)))),e}return await Promise.all(i.map((e=>e?.handleChainEnd(Yo(s,"output"))))),s}async*_streamIterator(e,t){const r=await Us(t),{runId:a,...n}=t??{},i=await(r?.handleChainStart(this.toJSON(),Yo(e,"input"),a,void 0,void 0,void 0,n?.runName)),s=[this.first,...this.middle,this.last];let o,c=!0;try{let r=s[0].transform(async function*(){yield e}(),zs(n,{callbacks:i?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let e=1;e<s.length;e+=1){const t=s[e];r=await t.transform(r,zs(n,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`)}))}for await(const e of r)if(t?.signal?.throwIfAborted(),yield e,c)if(void 0===o)o=e;else try{o=Js(o,e)}catch(e){o=void 0,c=!1}}catch(e){throw await(i?.handleChainError(e)),e}await(i?.handleChainEnd(Yo(o,"output")))}getGraph(e){const t=new qo;let r=null;return this.steps.forEach(((a,n)=>{const i=a.getGraph(e);0!==n&&i.trimFirstNode(),n!==this.steps.length-1&&i.trimLastNode(),t.extend(i);const s=i.firstNode();if(!s)throw new Error(`Runnable ${a} has no first node`);r&&t.addEdge(r,s),r=i.lastNode()})),t}pipe(e){return ac.isRunnableSequence(e)?new ac({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new ac({first:this.first,middle:[...this.middle,this.last],last:cc(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&Qo.isRunnable(e)}static from([e,...t],r){let a={};return"string"==typeof r?a.name=r:void 0!==r&&(a=r),new ac({...a,first:cc(e),middle:t.slice(0,-1).map(cc),last:cc(t[t.length-1])})}}class nc extends Qo{static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"steps",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.steps={};for(const[t,r]of Object.entries(e.steps))this.steps[t]=cc(r)}static from(e){return new nc({steps:e})}async invoke(e,t){const r=Zs(t),a=await Us(r),n=await(a?.handleChainStart(this.toJSON(),{input:e},r.runId,void 0,void 0,void 0,r?.runName));delete r.runId;const i={};try{const a=Object.entries(this.steps).map((async([t,a])=>{i[t]=await a.invoke(e,zs(r,{callbacks:n?.getChild(`map:key:${t}`)}))}));await Hs(Promise.all(a),t?.signal)}catch(e){throw await(n?.handleChainError(e)),e}return await(n?.handleChainEnd(i)),i}async*_transform(e,t,r){const a={...this.steps},n=Gs(e,Object.keys(a).length),i=new Map(Object.entries(a).map((([e,a],i)=>{const s=a.transform(n[i],zs(r,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,s.next().then((t=>({key:e,gen:s,result:t})))]})));for(;i.size;){const e=Promise.race(i.values()),{key:t,result:a,gen:n}=await Hs(e,r?.signal);i.delete(t),a.done||(yield{[t]:a.value},i.set(t,n.next().then((e=>({key:t,gen:n,result:e})))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=Zs(t),a=new Vs({generator:this.transform(async function*(){yield e}(),r),config:r});return await a.setup,qs.fromAsyncGenerator(a)}}class ic extends Qo{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!Ui(e.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,t){const[r]=this._getOptionsList(t??{},1),a=await Us(r);return Hs(this.func(zs(r,{callbacks:a}),e),r?.signal)}async*_streamIterator(e,t){const[r]=this._getOptionsList(t??{},1),a=await this.invoke(e,t);var n;if(Wo(a))for await(const e of a)r?.signal?.throwIfAborted(),yield e;else if(null!=(n=a)&&"object"==typeof n&&"next"in n&&"function"==typeof n.next)for(;;){r?.signal?.throwIfAborted();const e=a.next();if(e.done)break;yield e.value}else yield a}static from(e){return new ic({func:e})}}class sc extends Qo{static lc_name(){return"RunnableLambda"}constructor(e){if(Ui(e.func))return ic.from(e.func);super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),function(e){if(Ui(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}(e.func),this.func=e.func}static from(e){return new sc({func:e})}async _invoke(e,t,r){return new Promise(((a,n)=>{const i=zs(t,{callbacks:r?.getChild(),recursionLimit:(t?.recursionLimit??25)-1});Ms.runWithConfig(Bs(i),(async()=>{try{let r=await this.func(e,{...i});if(r&&Qo.isRunnable(r)){if(0===t?.recursionLimit)throw new Error("Recursion limit reached.");r=await r.invoke(e,{...i,recursionLimit:(i.recursionLimit??25)-1})}else if(Wo(r)){let e;for await(const a of Xo(i,r))if(t?.signal?.throwIfAborted(),void 0===e)e=a;else try{e=Js(e,a)}catch(t){e=a}r=e}else if(Vo(r)){let e;for(const a of Ko(i,r))if(t?.signal?.throwIfAborted(),void 0===e)e=a;else try{e=Js(e,a)}catch(t){e=a}r=e}a(r)}catch(e){n(e)}}))}))}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async*_transform(e,t,r){let a;for await(const t of e)if(void 0===a)a=t;else try{a=Js(a,t)}catch(e){a=t}const n=zs(r,{callbacks:t?.getChild(),recursionLimit:(r?.recursionLimit??25)-1}),i=await new Promise(((e,t)=>{Ms.runWithConfig(Bs(n),(async()=>{try{const t=await this.func(a,{...n,config:n});e(t)}catch(e){t(e)}}))}));if(i&&Qo.isRunnable(i)){if(0===r?.recursionLimit)throw new Error("Recursion limit reached.");const e=await i.stream(a,n);for await(const t of e)yield t}else if(Wo(i))for await(const e of Xo(n,i))r?.signal?.throwIfAborted(),yield e;else if(Vo(i))for(const e of Ko(n,i))r?.signal?.throwIfAborted(),yield e;else yield i}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=Zs(t),a=new Vs({generator:this.transform(async function*(){yield e}(),r),config:r});return await a.setup,qs.fromAsyncGenerator(a)}}class oc extends Qo{static lc_name(){return"RunnableWithFallbacks"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"runnable",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fallbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,t){const r=Zs(t),a=await Us(r),{runId:n,...i}=r,s=await(a?.handleChainStart(this.toJSON(),Yo(e,"input"),n,void 0,void 0,void 0,i?.runName)),o=zs(i,{callbacks:s?.getChild()});return await Ms.runWithConfig(o,(async()=>{let t;for(const a of this.runnables()){r?.signal?.throwIfAborted();try{const t=await a.invoke(e,o);return await(s?.handleChainEnd(Yo(t,"output"))),t}catch(e){void 0===t&&(t=e)}}if(void 0===t)throw new Error("No error stored at end of fallback.");throw await(s?.handleChainError(t)),t}))}async*_streamIterator(e,t){const r=Zs(t),a=await Us(r),{runId:n,...i}=r,s=await(a?.handleChainStart(this.toJSON(),Yo(e,"input"),n,void 0,void 0,void 0,i?.runName));let o,c,d;for(const t of this.runnables()){r?.signal?.throwIfAborted();const a=zs(i,{callbacks:s?.getChild()});try{c=Xo(a,await t.stream(e,a));break}catch(e){void 0===o&&(o=e)}}if(void 0===c){const e=o??new Error("No error stored at end of fallback.");throw await(s?.handleChainError(e)),e}try{for await(const e of c){yield e;try{d=void 0===d?d:Js(d,e)}catch(e){d=void 0}}}catch(e){throw await(s?.handleChainError(e)),e}await(s?.handleChainEnd(Yo(d,"output")))}async batch(e,t,r){if(r?.returnExceptions)throw new Error("Not implemented.");const a=this._getOptionsList(t??{},e.length),n=await Promise.all(a.map((e=>Us(e)))),i=await Promise.all(n.map((async(t,r)=>{const n=await(t?.handleChainStart(this.toJSON(),Yo(e[r],"input"),a[r].runId,void 0,void 0,void 0,a[r].runName));return delete a[r].runId,n})));let s;for(const t of this.runnables()){a[0].signal?.throwIfAborted();try{const n=await t.batch(e,i.map(((e,t)=>zs(a[t],{callbacks:e?.getChild()}))),r);return await Promise.all(i.map(((e,t)=>e?.handleChainEnd(Yo(n[t],"output"))))),n}catch(e){void 0===s&&(s=e)}}if(!s)throw new Error("No error stored at end of fallbacks.");throw await Promise.all(i.map((e=>e?.handleChainError(s)))),s}}function cc(e){if("function"==typeof e)return new sc({func:e});if(Qo.isRunnable(e))return e;if(Array.isArray(e)||"object"!=typeof e)throw new Error("Expected a Runnable, function or object.\nInstead got an unsupported type.");{const t={};for(const[r,a]of Object.entries(e))t[r]=cc(a);return new nc({steps:t})}}class dc extends Qo{static lc_name(){return"RunnableAssign"}constructor(e){e instanceof nc&&(e={mapper:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mapper=e.mapper}async invoke(e,t){const r=await this.mapper.invoke(e,t);return{...e,...r}}async*_transform(e,t,r){const a=this.mapper.getStepsKeys(),[n,i]=Gs(e),s=this.mapper.transform(i,zs(r,{callbacks:t?.getChild()})),o=s.next();for await(const e of n){if("object"!=typeof e||Array.isArray(e))throw new Error("RunnableAssign can only be used with objects as input, got "+typeof e);const t=Object.fromEntries(Object.entries(e).filter((([e])=>!a.includes(e))));Object.keys(t).length>0&&(yield t)}yield(await o).value;for await(const e of s)yield e}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=Zs(t),a=new Vs({generator:this.transform(async function*(){yield e}(),r),config:r});return await a.setup,qs.fromAsyncGenerator(a)}}class lc extends Qo{static lc_name(){return"RunnablePick"}constructor(e){("string"==typeof e||Array.isArray(e))&&(e={keys:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"keys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keys=e.keys}async _pick(e){if("string"==typeof this.keys)return e[this.keys];{const t=this.keys.map((t=>[t,e[t]])).filter((e=>void 0!==e[1]));return 0===t.length?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(const t of e){const e=await this._pick(t);void 0!==e&&(yield e)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=Zs(t),a=new Vs({generator:this.transform(async function*(){yield e}(),r),config:r});return await a.setup,qs.fromAsyncGenerator(a)}}class uc extends ec{constructor(e){super({bound:ac.from([sc.from((async e=>{let t;if(oa(e))try{t=await this.schema.parseAsync(e.args)}catch(t){throw new ca("Received tool input did not match expected schema",JSON.stringify(e.args))}else t=e;return t})).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name}),config:e.config??{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}}class hc extends Qo{get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{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,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.verbose=e.verbose??!1,this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}}class pc extends hc{get lc_namespace(){return["langchain","tools"]}constructor(e){super(e??{}),Object.defineProperty(this,"returnDirect",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"verboseParsingErrors",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"responseFormat",{enumerable:!0,configurable:!0,writable:!0,value:"content"}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat}async invoke(e,t){let r,a,n=Zs(t);return oa(e)?(r=e.id,a=e.args,n={...n,toolCall:e,configurable:{...n.configurable,tool_call_id:r}}):a=e,this.call(a,n)}async call(e,t,r){let a=e;if(function(e){if(!e)return!1;if("object"!=typeof e)return!1;if(Array.isArray(e))return!1;const t=e;return!!t._def||(!!Object.values($t.ZodFirstPartyTypeKind).includes(t.constructor?.name??"NOT_INCLUDED")||"function"==typeof t.parse&&"function"==typeof t.parseAsync&&"function"==typeof t.safeParse&&"function"==typeof t.safeParseAsync)}(this.schema))try{a=await this.schema.parseAsync(e)}catch(t){let r="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(r=`${r}\nDetails: ${t.message}`),new ca(r,JSON.stringify(e))}else{const t=Bt(e,this.schema);if(!t.valid){let r="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(r=`${r}\nDetails: ${t.errors.map((e=>`${e.keywordLocation}: ${e.error}`)).join("\n")}`),new ca(r,JSON.stringify(e))}}const n=function(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}(t),i=rs.configure(n.callbacks,this.callbacks,n.tags||r,this.tags,n.metadata,this.metadata,{verbose:this.verbose}),s=await(i?.handleToolStart(this.toJSON(),"string"==typeof a?a:JSON.stringify(a),n.runId,void 0,void 0,void 0,n.runName));let o,c,d,l;delete n.runId;try{o=await this._call(a,s,n)}catch(e){throw await(s?.handleToolError(e)),e}if("content_and_artifact"===this.responseFormat){if(!Array.isArray(o)||2!==o.length)throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(o)}`);[c,d]=o}else c=o;n&&"configurable"in n&&(l=n.configurable.tool_call_id);const u=function(e){const{content:t,artifact:r,toolCallId:a}=e;return a&&(n=t,null==n||"object"!=typeof n||!("lc_direct_tool_output"in n)||!0!==n.lc_direct_tool_output)?"string"==typeof t||Array.isArray(t)&&t.every((e=>"object"==typeof e))?new fa({content:t,artifact:r,tool_call_id:a,name:e.name}):new fa({content:mc(t),artifact:r,tool_call_id:a,name:e.name}):t;var n}({content:c,artifact:d,toolCallId:l,name:this.name});return await(s?.handleToolEnd(u)),u}}function mc(e){try{return JSON.stringify(e,null,2)}catch(t){return`${e}`}}class fc extends Error{response;request;options;constructor(e,t,r){const a=`${e.status||0===e.status?e.status:""} ${e.statusText||""}`.trim();super(`Request failed with ${a?`status code ${a}`:"an unknown error"}: ${t.method} ${t.url}`),this.name="HTTPError",this.response=e,this.request=t,this.options=r}}class gc extends Error{request;constructor(e){super(`Request timed out: ${e.method} ${e.url}`),this.name="TimeoutError",this.request=e}}const yc=e=>null!==e&&"object"==typeof e,_c=(...e)=>{for(const t of e)if((!yc(t)||Array.isArray(t))&&void 0!==t)throw new TypeError("The `options` argument must be an object");return Ec({},...e)},bc=(e={},t={})=>{const r=new globalThis.Headers(e),a=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(const[e,t]of n.entries())a&&"undefined"===t||void 0===t?r.delete(e):r.set(e,t);return r};function vc(e,t,r){return Object.hasOwn(t,r)&&void 0===t[r]?[]:Ec(e[r]??[],t[r]??[])}const wc=(e={},t={})=>({beforeRequest:vc(e,t,"beforeRequest"),beforeRetry:vc(e,t,"beforeRetry"),afterResponse:vc(e,t,"afterResponse"),beforeError:vc(e,t,"beforeError")}),Ec=(...e)=>{let t={},r={},a={};for(const n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(yc(n)){for(let[e,r]of Object.entries(n))yc(r)&&e in t&&(r=Ec(t[e],r)),t={...t,[e]:r};yc(n.hooks)&&(a=wc(a,n.hooks),t.hooks=a),yc(n.headers)&&(r=bc(r,n.headers),t.headers=r)}return t},Oc=(()=>{let e=!1,t=!1;const r="function"==typeof globalThis.ReadableStream,a="function"==typeof globalThis.Request;if(r&&a)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(e){if(e instanceof Error&&"unsupported BodyInit type"===e.message)return!1;throw e}return e&&!t})(),$c="function"==typeof globalThis.AbortController,kc="function"==typeof globalThis.ReadableStream,Ic="function"==typeof globalThis.FormData,Tc=["get","post","put","patch","head","delete"],xc={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},Sc=2147483647,Ac=Symbol("stop"),jc={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},Pc={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0},Rc=e=>Tc.includes(e)?e.toUpperCase():e,Nc={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:[413,429,503],maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Cc=(e={})=>{if("number"==typeof e)return{...Nc,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Nc,...e}};class Lc{static create(e,t){const r=new Lc(e,t),a=async()=>{if("number"==typeof r._options.timeout&&r._options.timeout>Sc)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let e=await r._fetch();for(const t of r._options.hooks.afterResponse){const a=await t(r.request,r._options,r._decorateResponse(e.clone()));a instanceof globalThis.Response&&(e=a)}if(r._decorateResponse(e),!e.ok&&r._options.throwHttpErrors){let t=new fc(e,r.request,r._options);for(const e of r._options.hooks.beforeError)t=await e(t);throw t}if(r._options.onDownloadProgress){if("function"!=typeof r._options.onDownloadProgress)throw new TypeError("The `onDownloadProgress` option must be a function");if(!kc)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(e.clone(),r._options.onDownloadProgress)}return e},n=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(a):a();for(const[e,a]of Object.entries(xc))n[e]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||a);const i=(await n).clone();if("json"===e){if(204===i.status)return"";if(0===(await i.clone().arrayBuffer()).byteLength)return"";if(t.parseJson)return t.parseJson(await i.text())}return i[e]()};return n}request;abortController;_retryCount=0;_input;_options;constructor(e,t={}){if(this._input=e,this._options={...t,headers:bc(this._input.headers,t.headers),hooks:wc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:Rc(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:Cc(t.retry),throwHttpErrors:!1!==t.throwHttpErrors,timeout:t.timeout??1e4,fetch:t.fetch??globalThis.fetch.bind(globalThis)},"string"!=typeof this._input&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&"string"==typeof this._input){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if($c){this.abortController=new globalThis.AbortController;const e=this._options.signal??this._input.signal;e?.addEventListener("abort",(()=>{this.abortController.abort(e.reason)})),this._options.signal=this.abortController.signal}if(Oc&&(this._options.duplex="half"),void 0!==this._options.json&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const e="?"+("string"==typeof this._options.searchParams?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),t=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,e);!(Ic&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)||this._options.headers&&this._options.headers["content-type"]||this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(t,{...this.request}),this._options)}}_calculateRetryDelay(e){if(this._retryCount++,this._retryCount>this._options.retry.limit||e instanceof gc)throw e;if(e instanceof fc){if(!this._options.retry.statusCodes.includes(e.response.status))throw e;const t=e.response.headers.get("Retry-After")??e.response.headers.get("RateLimit-Reset")??e.response.headers.get("X-RateLimit-Reset")??e.response.headers.get("X-Rate-Limit-Reset");if(t&&this._options.retry.afterStatusCodes.includes(e.response.status)){let e=1e3*Number(t);Number.isNaN(e)?e=Date.parse(t)-Date.now():e>=Date.parse("2024-01-01")&&(e-=Date.now());const r=this._options.retry.maxRetryAfter??e;return e<r?e:r}if(413===e.response.status)throw e}const t=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,t)}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(t){const r=Math.min(this._calculateRetryDelay(t),Sc);if(this._retryCount<1)throw t;await async function(e,{signal:t}){return new Promise(((r,a)=>{function n(){clearTimeout(i),a(t.reason)}t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));const i=setTimeout((()=>{t?.removeEventListener("abort",n),r()}),e)}))}(r,{signal:this._options.signal});for(const e of this._options.hooks.beforeRetry){if(await e({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===Ac)return}return this._retry(e)}}async _fetch(){for(const e of this._options.hooks.beforeRequest){const t=await e(this.request,this._options);if(t instanceof Request){this.request=t;break}if(t instanceof Response)return t}const e=((e,t)=>{const r={};for(const a in t)a in Pc||a in jc||a in e||(r[a]=t[a]);return r})(this.request,this._options),t=this.request;return this.request=t.clone(),!1===this._options.timeout?this._options.fetch(t,e):async function(e,t,r,a){return new Promise(((n,i)=>{const s=setTimeout((()=>{r&&r.abort(),i(new gc(e))}),a.timeout);a.fetch(e,t).then(n).catch(i).then((()=>{clearTimeout(s)}))}))}(t,e,this.abortController,this._options)}_stream(e,t){const r=Number(e.headers.get("content-length"))||0;let a=0;return 204===e.status?(t&&t({percent:1,totalBytes:r,transferredBytes:a},new Uint8Array),new globalThis.Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(n){const i=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array),await async function e(){const{done:s,value:o}=await i.read();if(s)n.close();else{if(t){a+=o.byteLength;t({percent:0===r?0:a/r,transferredBytes:a,totalBytes:r},o)}n.enqueue(o),await e()}}()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}
/*! MIT License © Sindre Sorhus */const Mc=e=>{const t=(t,r)=>Lc.create(t,_c(e,r));for(const r of Tc)t[r]=(t,a)=>Lc.create(t,_c(e,a,{method:r}));return t.create=e=>Mc(_c(e)),t.extend=t=>("function"==typeof t&&(t=t(e??{})),Mc(_c(e,t))),t.stop=Ac,t},Uc=Mc();exports.JinaUrlToMarkdown=class extends pc{constructor(e){super(),this.name="jina-url-to-markdown",this.description='Fetches web content from a specified URL and returns it in Markdown format. Input should be a JSON object with a "url".',this.schema=$t.object({url:$t.string().describe("The URL to scrape and retrieve content from.")}),this.apiKey=e?.apiKey,this.options=e?.options||{},this.headers={"Content-Type":"application/json"},this.apiKey&&(this.headers.Authorization=`Bearer ${this.apiKey}`),this.httpClient=Uc}async _call(e){try{const t=await this.httpClient.post("https://r.jina.ai/",{json:{url:e.url,...this.options},headers:this.headers}).json();return t?.data||"The API returned an empty response."}catch(e){if(e instanceof fc){const t=e.response.status;let r="Unknown";return t>=400&&t<500?r="Client Error":t>=500&&(r="Server Error"),`API request failed: ${r} (${t})`}return`An unexpected error occurred: ${e.message}`}}};