@mcp-use/inspector 0.12.1 → 0.12.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,27 +1,25 @@
1
- import{$ as Yu,f as $e,h as Xu,g as br,i as nc,j as xt,k as Qu,l as el,m as ac,d as os,n as tl,o as rl,q as nl,s as al}from"./index-BC5u-13_.js";class Vs{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??$e,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;const a=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;const o={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,o);const c=e._zod.toJSONSchema?.();if(c)o.schema=c;else{const d={...r,schemaPath:[...r.schemaPath,e],path:r.path},f=e._zod.parent;if(f)o.ref=f,this.process(f,d),this.seen.get(f).isParent=!0;else{const h=o.schema;switch(a.type){case"string":{const p=h;p.type="string";const{minimum:m,maximum:g,format:y,patterns:v,contentEncoding:_}=e._zod.bag;if(typeof m=="number"&&(p.minLength=m),typeof g=="number"&&(p.maxLength=g),y&&(p.format=s[y]??y,p.format===""&&delete p.format),_&&(p.contentEncoding=_),v&&v.size>0){const E=[...v];E.length===1?p.pattern=E[0].source:E.length>1&&(o.schema.allOf=[...E.map($=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:$.source}))])}break}case"number":{const p=h,{minimum:m,maximum:g,format:y,multipleOf:v,exclusiveMaximum:_,exclusiveMinimum:E}=e._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof E=="number"&&(this.target==="draft-4"||this.target==="openapi-3.0"?(p.minimum=E,p.exclusiveMinimum=!0):p.exclusiveMinimum=E),typeof m=="number"&&(p.minimum=m,typeof E=="number"&&this.target!=="draft-4"&&(E>=m?delete p.minimum:delete p.exclusiveMinimum)),typeof _=="number"&&(this.target==="draft-4"||this.target==="openapi-3.0"?(p.maximum=_,p.exclusiveMaximum=!0):p.exclusiveMaximum=_),typeof g=="number"&&(p.maximum=g,typeof _=="number"&&this.target!=="draft-4"&&(_<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof v=="number"&&(p.multipleOf=v);break}case"boolean":{const p=h;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{this.target==="openapi-3.0"?(h.type="string",h.nullable=!0,h.enum=[null]):h.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const p=h,{minimum:m,maximum:g}=e._zod.bag;typeof m=="number"&&(p.minItems=m),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(a.element,{...d,path:[...d.path,"items"]});break}case"object":{const p=h;p.type="object",p.properties={};const m=a.shape;for(const v in m)p.properties[v]=this.process(m[v],{...d,path:[...d.path,"properties",v]});const g=new Set(Object.keys(m)),y=new Set([...g].filter(v=>{const _=a.shape[v]._zod;return this.io==="input"?_.optin===void 0:_.optout===void 0}));y.size>0&&(p.required=Array.from(y)),a.catchall?._zod.def.type==="never"?p.additionalProperties=!1:a.catchall?a.catchall&&(p.additionalProperties=this.process(a.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{const p=h,m=a.discriminator!==void 0,g=a.options.map((y,v)=>this.process(y,{...d,path:[...d.path,m?"oneOf":"anyOf",v]}));m?p.oneOf=g:p.anyOf=g;break}case"intersection":{const p=h,m=this.process(a.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(a.right,{...d,path:[...d.path,"allOf",1]}),y=_=>"allOf"in _&&Object.keys(_).length===1,v=[...y(m)?m.allOf:[m],...y(g)?g.allOf:[g]];p.allOf=v;break}case"tuple":{const p=h;p.type="array";const m=this.target==="draft-2020-12"?"prefixItems":"items",g=this.target==="draft-2020-12"||this.target==="openapi-3.0"?"items":"additionalItems",y=a.items.map(($,U)=>this.process($,{...d,path:[...d.path,m,U]})),v=a.rest?this.process(a.rest,{...d,path:[...d.path,g,...this.target==="openapi-3.0"?[a.items.length]:[]]}):null;this.target==="draft-2020-12"?(p.prefixItems=y,v&&(p.items=v)):this.target==="openapi-3.0"?(p.items={anyOf:y},v&&p.items.anyOf.push(v),p.minItems=y.length,v||(p.maxItems=y.length)):(p.items=y,v&&(p.additionalItems=v));const{minimum:_,maximum:E}=e._zod.bag;typeof _=="number"&&(p.minItems=_),typeof E=="number"&&(p.maxItems=E);break}case"record":{const p=h;p.type="object",(this.target==="draft-7"||this.target==="draft-2020-12")&&(p.propertyNames=this.process(a.keyType,{...d,path:[...d.path,"propertyNames"]})),p.additionalProperties=this.process(a.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const p=h,m=Xu(a.entries);m.every(g=>typeof g=="number")&&(p.type="number"),m.every(g=>typeof g=="string")&&(p.type="string"),p.enum=m;break}case"literal":{const p=h,m=[];for(const g of a.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");m.push(Number(g))}else m.push(g);if(m.length!==0)if(m.length===1){const g=m[0];p.type=g===null?"null":typeof g,this.target==="draft-4"||this.target==="openapi-3.0"?p.enum=[g]:p.const=g}else m.every(g=>typeof g=="number")&&(p.type="number"),m.every(g=>typeof g=="string")&&(p.type="string"),m.every(g=>typeof g=="boolean")&&(p.type="string"),m.every(g=>g===null)&&(p.type="null"),p.enum=m;break}case"file":{const p=h,m={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:v}=e._zod.bag;g!==void 0&&(m.minLength=g),y!==void 0&&(m.maxLength=y),v?v.length===1?(m.contentMediaType=v[0],Object.assign(p,m)):p.anyOf=v.map(_=>({...m,contentMediaType:_})):Object.assign(p,m);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const p=this.process(a.innerType,d);this.target==="openapi-3.0"?(o.ref=a.innerType,h.nullable=!0):h.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(a.innerType,d),o.ref=a.innerType;break}case"success":{const p=h;p.type="boolean";break}case"default":{this.process(a.innerType,d),o.ref=a.innerType,h.default=JSON.parse(JSON.stringify(a.defaultValue));break}case"prefault":{this.process(a.innerType,d),o.ref=a.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(a.defaultValue)));break}case"catch":{this.process(a.innerType,d),o.ref=a.innerType;let p;try{p=a.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const p=h,m=e._zod.pattern;if(!m)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=m.source;break}case"pipe":{const p=this.io==="input"?a.in._zod.def.type==="transform"?a.out:a.in:a.out;this.process(p,d),o.ref=p;break}case"readonly":{this.process(a.innerType,d),o.ref=a.innerType,h.readOnly=!0;break}case"promise":{this.process(a.innerType,d),o.ref=a.innerType;break}case"optional":{this.process(a.innerType,d),o.ref=a.innerType;break}case"lazy":{const p=e._zod.innerType;this.process(p,d),o.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}case"function":{if(this.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema");break}}}}const u=this.metadataRegistry.get(e);return u&&Object.assign(o.schema,u),this.io==="input"&&Se(e)&&(delete o.schema.examples,delete o.schema.default),this.io==="input"&&o.schema._prefault&&((n=o.schema).default??(n.default=o.schema._prefault)),delete o.schema._prefault,this.seen.get(e).schema}emit(e,r){const n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},a=this.seen.get(e);if(!a)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=l=>{const d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const m=n.external.registry.get(l[0])?.id,g=n.external.uri??(v=>v);if(m)return{ref:g(m)};const y=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=y,{defId:y,ref:`${g("__shared")}#/${d}/${y}`}}if(l[1]===a)return{ref:"#"};const h=`#/${d}/`,p=l[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:h+p}},i=l=>{if(l[1].schema.$ref)return;const d=l[1],{ref:f,defId:h}=s(l);d.def={...d.schema},h&&(d.defId=h);const p=d.schema;for(const m in p)delete p[m];p.$ref=f};if(n.cycles==="throw")for(const l of this.seen.entries()){const d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
2
-
3
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const l of this.seen.entries()){const d=l[1];if(e===l[0]){i(l);continue}if(n.external){const h=n.external.registry.get(l[0])?.id;if(e!==l[0]&&h){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&n.reused==="ref"){i(l);continue}}const o=(l,d)=>{const f=this.seen.get(l),h=f.def??f.schema,p={...h};if(f.ref===null)return;const m=f.ref;if(f.ref=null,m){o(m,d);const g=this.seen.get(m).schema;g.$ref&&(d.target==="draft-7"||d.target==="draft-4"||d.target==="openapi-3.0")?(h.allOf=h.allOf??[],h.allOf.push(g)):(Object.assign(h,g),Object.assign(h,p))}f.isParent||this.override({zodSchema:l,jsonSchema:h,path:f.path??[]})};for(const l of[...this.seen.entries()].reverse())o(l[0],{target:this.target});const c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":this.target==="draft-4"?c.$schema="http://json-schema.org/draft-04/schema#":this.target==="openapi-3.0"||console.warn(`Invalid target: ${this.target}`),n.external?.uri){const l=n.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(l)}Object.assign(c,a.def);const u=n.external?.defs??{};for(const l of this.seen.entries()){const d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}function Js(t,e){if(t instanceof Yu){const n=new Vs(e),a={};for(const o of t._idmap.entries()){const[c,u]=o;n.process(u)}const s={},i={registry:t,uri:e?.uri,defs:a};for(const o of t._idmap.entries()){const[c,u]=o;s[c]=n.emit(u,{...e,external:i})}if(Object.keys(a).length>0){const o=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[o]:a}}return{schemas:s}}const r=new Vs(e);return r.process(t),r.emit(t,e)}function Se(t,e){const r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);const n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Se(n.element,r);if(n.type==="set")return Se(n.valueType,r);if(n.type==="lazy")return Se(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return Se(n.innerType,r);if(n.type==="intersection")return Se(n.left,r)||Se(n.right,r);if(n.type==="record"||n.type==="map")return Se(n.keyType,r)||Se(n.valueType,r);if(n.type==="pipe")return Se(n.in,r)||Se(n.out,r);if(n.type==="object"){for(const a in n.shape)if(Se(n.shape[a],r))return!0;return!1}if(n.type==="union"){for(const a of n.options)if(Se(a,r))return!0;return!1}if(n.type==="tuple"){for(const a of n.items)if(Se(a,r))return!0;return!!(n.rest&&Se(n.rest,r))}return!1}var te;(function(t){t.assertEqual=a=>{};function e(a){}t.assertIs=e;function r(a){throw new Error}t.assertNever=r,t.arrayToEnum=a=>{const s={};for(const i of a)s[i]=i;return s},t.getValidEnumValues=a=>{const s=t.objectKeys(a).filter(o=>typeof a[a[o]]!="number"),i={};for(const o of s)i[o]=a[o];return t.objectValues(i)},t.objectValues=a=>t.objectKeys(a).map(function(s){return a[s]}),t.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{const s=[];for(const i in a)Object.prototype.hasOwnProperty.call(a,i)&&s.push(i);return s},t.find=(a,s)=>{for(const i of a)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function n(a,s=" | "){return a.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(a,s)=>typeof s=="bigint"?s.toString():s})(te||(te={}));var Ws;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Ws||(Ws={}));const R=te.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ft=t=>{switch(typeof t){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(t)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(t)?R.array:t===null?R.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?R.promise:typeof Map<"u"&&t instanceof Map?R.map:typeof Set<"u"&&t instanceof Set?R.set:typeof Date<"u"&&t instanceof Date?R.date:R.object;default:return R.unknown}},w=te.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class De extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(s){return s.message},n={_errors:[]},a=s=>{for(const i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(a);else if(i.code==="invalid_return_type")a(i.returnTypeError);else if(i.code==="invalid_arguments")a(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let o=n,c=0;for(;c<i.path.length;){const u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(r(i))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return a(this),n}static assert(e){if(!(e instanceof De))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,te.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r=Object.create(null),n=[];for(const a of this.issues)if(a.path.length>0){const s=a.path[0];r[s]=r[s]||[],r[s].push(e(a))}else n.push(e(a));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}De.create=t=>new De(t);const cr=(t,e)=>{let r;switch(t.code){case w.invalid_type:t.received===R.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case w.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,te.jsonStringifyReplacer)}`;break;case w.unrecognized_keys:r=`Unrecognized key(s) in object: ${te.joinValues(t.keys,", ")}`;break;case w.invalid_union:r="Invalid input";break;case w.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${te.joinValues(t.options)}`;break;case w.invalid_enum_value:r=`Invalid enum value. Expected ${te.joinValues(t.options)}, received '${t.received}'`;break;case w.invalid_arguments:r="Invalid function arguments";break;case w.invalid_return_type:r="Invalid function return type";break;case w.invalid_date:r="Invalid date";break;case w.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:te.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case w.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case w.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case w.custom:r="Invalid input";break;case w.invalid_intersection_types:r="Intersection results could not be merged";break;case w.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case w.not_finite:r="Number must be finite";break;default:r=e.defaultError,te.assertNever(t)}return{message:r}};let sl=cr;function Da(){return sl}const Ua=t=>{const{data:e,path:r,errorMaps:n,issueData:a}=t,s=[...r,...a.path||[]],i={...a,path:s};if(a.message!==void 0)return{...a,path:s,message:a.message};let o="";const c=n.filter(u=>!!u).slice().reverse();for(const u of c)o=u(i,{data:e,defaultError:o}).message;return{...a,path:s,message:o}};function x(t,e){const r=Da(),n=Ua({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===cr?void 0:cr].filter(a=>!!a)});t.common.issues.push(n)}class xe{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const a of r){if(a.status==="aborted")return V;a.status==="dirty"&&e.dirty(),n.push(a.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const a of r){const s=await a.key,i=await a.value;n.push({key:s,value:i})}return xe.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const a of r){const{key:s,value:i}=a;if(s.status==="aborted"||i.status==="aborted")return V;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||a.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}}const V=Object.freeze({status:"aborted"}),tr=t=>({status:"dirty",value:t}),Ne=t=>({status:"valid",value:t}),Ks=t=>t.status==="aborted",Ys=t=>t.status==="dirty",Bt=t=>t.status==="valid",Jr=t=>typeof Promise<"u"&&t instanceof Promise;var N;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(N||(N={}));class Qe{constructor(e,r,n,a){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Xs=(t,e)=>{if(Bt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new De(t.common.issues);return this._error=r,this._error}}};function X(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:a}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:a}:{errorMap:(i,o)=>{const{message:c}=t;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:a}}class ee{get description(){return this._def.description}_getType(e){return ft(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:ft(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new xe,ctx:{common:e.parent.common,data:e.data,parsedType:ft(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(Jr(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ft(e)},a=this._parseSync({data:e,path:n.path,parent:n});return Xs(n,a)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ft(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return Bt(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Bt(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ft(e)},a=this._parse({data:e,path:n.path,parent:n}),s=await(Jr(a)?a:Promise.resolve(a));return Xs(n,s)}refine(e,r){const n=a=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(a):r;return this._refinement((a,s)=>{const i=e(a),o=()=>s.addIssue({code:w.custom,...n(a)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,a)=>e(n)?!0:(a.addIssue(typeof r=="function"?r(n,a):r),!1))}_refinement(e){return new Gt({schema:this,typeName:b.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return pt.create(this,this._def)}nullable(){return Ht.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ye.create(this)}promise(){return fr.create(this,this._def)}or(e){return Kr.create([this,e],this._def)}and(e){return Yr.create(this,e,this._def)}transform(e){return new Gt({...X(this._def),schema:this,typeName:b.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new Ga({...X(this._def),innerType:this,defaultValue:r,typeName:b.ZodDefault})}brand(){return new Ol({typeName:b.ZodBranded,type:this,...X(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new Ha({...X(this._def),innerType:this,catchValue:r,typeName:b.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return cs.create(this,e)}readonly(){return Za.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const il=/^c[^\s-]{8,}$/i,ol=/^[0-9a-z]+$/,cl=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ul=/^[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,ll=/^[a-z0-9_-]{21}$/i,dl=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,fl=/^[-+]?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)?)??$/,hl=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,pl="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Sn;const ml=/^(?:(?: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])$/,gl=/^(?:(?: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])$/,yl=/^(([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]))$/,_l=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,vl=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,wl=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,sc="((\\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])))",bl=new RegExp(`^${sc}$`);function ic(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function El(t){return new RegExp(`^${ic(t)}$`)}function Sl(t){let e=`${sc}T${ic(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Tl(t,e){return!!((e==="v4"||!e)&&ml.test(t)||(e==="v6"||!e)&&yl.test(t))}function xl(t,e){if(!dl.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),a=JSON.parse(atob(n));return!(typeof a!="object"||a===null||"typ"in a&&a?.typ!=="JWT"||!a.alg||e&&a.alg!==e)}catch{return!1}}function Il(t,e){return!!((e==="v4"||!e)&&gl.test(t)||(e==="v6"||!e)&&_l.test(t))}class nt extends ee{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){const s=this._getOrReturnCtx(e);return x(s,{code:w.invalid_type,expected:R.string,received:s.parsedType}),V}const n=new xe;let a;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(a=this._getOrReturnCtx(e,a),x(a,{code:w.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(a=this._getOrReturnCtx(e,a),x(a,{code:w.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){const i=e.data.length>s.value,o=e.data.length<s.value;(i||o)&&(a=this._getOrReturnCtx(e,a),i?x(a,{code:w.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&x(a,{code:w.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")hl.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"email",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Sn||(Sn=new RegExp(pl,"u")),Sn.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"emoji",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")ul.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"uuid",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")ll.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"nanoid",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")il.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"cuid",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")ol.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"cuid2",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")cl.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"ulid",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{a=this._getOrReturnCtx(e,a),x(a,{validation:"url",code:w.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"regex",code:w.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(a=this._getOrReturnCtx(e,a),x(a,{code:w.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(a=this._getOrReturnCtx(e,a),x(a,{code:w.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(a=this._getOrReturnCtx(e,a),x(a,{code:w.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Sl(s).test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{code:w.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?bl.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{code:w.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?El(s).test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{code:w.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?fl.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"duration",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Tl(e.data,s.version)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"ip",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?xl(e.data,s.alg)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"jwt",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Il(e.data,s.version)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"cidr",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?vl.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"base64",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?wl.test(e.data)||(a=this._getOrReturnCtx(e,a),x(a,{validation:"base64url",code:w.invalid_string,message:s.message}),n.dirty()):te.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(a=>e.test(a),{validation:r,code:w.invalid_string,...N.errToObj(n)})}_addCheck(e){return new nt({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...N.errToObj(e)})}url(e){return this._addCheck({kind:"url",...N.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...N.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...N.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...N.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...N.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...N.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...N.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...N.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...N.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...N.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...N.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...N.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...N.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...N.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...N.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...N.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...N.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...N.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...N.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...N.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...N.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...N.errToObj(r)})}nonempty(e){return this.min(1,N.errToObj(e))}trim(){return new nt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new nt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new nt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}nt.create=t=>new nt({checks:[],typeName:b.ZodString,coerce:t?.coerce??!1,...X(t)});function Al(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,a=r>n?r:n,s=Number.parseInt(t.toFixed(a).replace(".","")),i=Number.parseInt(e.toFixed(a).replace(".",""));return s%i/10**a}class zt extends ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==R.number){const s=this._getOrReturnCtx(e);return x(s,{code:w.invalid_type,expected:R.number,received:s.parsedType}),V}let n;const a=new xe;for(const s of this._def.checks)s.kind==="int"?te.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{code:w.invalid_type,expected:"integer",received:"float",message:s.message}),a.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),x(n,{code:w.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),x(n,{code:w.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty()):s.kind==="multipleOf"?Al(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),x(n,{code:w.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{code:w.not_finite,message:s.message}),a.dirty()):te.assertNever(s);return{status:a.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,N.toString(r))}gt(e,r){return this.setLimit("min",e,!1,N.toString(r))}lte(e,r){return this.setLimit("max",e,!0,N.toString(r))}lt(e,r){return this.setLimit("max",e,!1,N.toString(r))}setLimit(e,r,n,a){return new zt({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:N.toString(a)}]})}_addCheck(e){return new zt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:N.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:N.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&te.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}}zt.create=t=>new zt({checks:[],typeName:b.ZodNumber,coerce:t?.coerce||!1,...X(t)});class ur extends ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==R.bigint)return this._getInvalidInput(e);let n;const a=new xe;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),x(n,{code:w.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),x(n,{code:w.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),x(n,{code:w.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):te.assertNever(s);return{status:a.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return x(r,{code:w.invalid_type,expected:R.bigint,received:r.parsedType}),V}gte(e,r){return this.setLimit("min",e,!0,N.toString(r))}gt(e,r){return this.setLimit("min",e,!1,N.toString(r))}lte(e,r){return this.setLimit("max",e,!0,N.toString(r))}lt(e,r){return this.setLimit("max",e,!1,N.toString(r))}setLimit(e,r,n,a){return new ur({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:N.toString(a)}]})}_addCheck(e){return new ur({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}ur.create=t=>new ur({checks:[],typeName:b.ZodBigInt,coerce:t?.coerce??!1,...X(t)});class Fa extends ee{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){const n=this._getOrReturnCtx(e);return x(n,{code:w.invalid_type,expected:R.boolean,received:n.parsedType}),V}return Ne(e.data)}}Fa.create=t=>new Fa({typeName:b.ZodBoolean,coerce:t?.coerce||!1,...X(t)});class Wr extends ee{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){const s=this._getOrReturnCtx(e);return x(s,{code:w.invalid_type,expected:R.date,received:s.parsedType}),V}if(Number.isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return x(s,{code:w.invalid_date}),V}const n=new xe;let a;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(a=this._getOrReturnCtx(e,a),x(a,{code:w.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(a=this._getOrReturnCtx(e,a),x(a,{code:w.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):te.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Wr({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:N.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:N.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}Wr.create=t=>new Wr({checks:[],coerce:t?.coerce||!1,typeName:b.ZodDate,...X(t)});class Qs extends ee{_parse(e){if(this._getType(e)!==R.symbol){const n=this._getOrReturnCtx(e);return x(n,{code:w.invalid_type,expected:R.symbol,received:n.parsedType}),V}return Ne(e.data)}}Qs.create=t=>new Qs({typeName:b.ZodSymbol,...X(t)});class Ba extends ee{_parse(e){if(this._getType(e)!==R.undefined){const n=this._getOrReturnCtx(e);return x(n,{code:w.invalid_type,expected:R.undefined,received:n.parsedType}),V}return Ne(e.data)}}Ba.create=t=>new Ba({typeName:b.ZodUndefined,...X(t)});class ei extends ee{_parse(e){if(this._getType(e)!==R.null){const n=this._getOrReturnCtx(e);return x(n,{code:w.invalid_type,expected:R.null,received:n.parsedType}),V}return Ne(e.data)}}ei.create=t=>new ei({typeName:b.ZodNull,...X(t)});class lr extends ee{constructor(){super(...arguments),this._any=!0}_parse(e){return Ne(e.data)}}lr.create=t=>new lr({typeName:b.ZodAny,...X(t)});class Ut extends ee{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ne(e.data)}}Ut.create=t=>new Ut({typeName:b.ZodUnknown,...X(t)});class mt extends ee{_parse(e){const r=this._getOrReturnCtx(e);return x(r,{code:w.invalid_type,expected:R.never,received:r.parsedType}),V}}mt.create=t=>new mt({typeName:b.ZodNever,...X(t)});class ti extends ee{_parse(e){if(this._getType(e)!==R.undefined){const n=this._getOrReturnCtx(e);return x(n,{code:w.invalid_type,expected:R.void,received:n.parsedType}),V}return Ne(e.data)}}ti.create=t=>new ti({typeName:b.ZodVoid,...X(t)});class Ye extends ee{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),a=this._def;if(r.parsedType!==R.array)return x(r,{code:w.invalid_type,expected:R.array,received:r.parsedType}),V;if(a.exactLength!==null){const i=r.data.length>a.exactLength.value,o=r.data.length<a.exactLength.value;(i||o)&&(x(r,{code:i?w.too_big:w.too_small,minimum:o?a.exactLength.value:void 0,maximum:i?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),n.dirty())}if(a.minLength!==null&&r.data.length<a.minLength.value&&(x(r,{code:w.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),n.dirty()),a.maxLength!==null&&r.data.length>a.maxLength.value&&(x(r,{code:w.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,o)=>a.type._parseAsync(new Qe(r,i,r.path,o)))).then(i=>xe.mergeArray(n,i));const s=[...r.data].map((i,o)=>a.type._parseSync(new Qe(r,i,r.path,o)));return xe.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new Ye({...this._def,minLength:{value:e,message:N.toString(r)}})}max(e,r){return new Ye({...this._def,maxLength:{value:e,message:N.toString(r)}})}length(e,r){return new Ye({...this._def,exactLength:{value:e,message:N.toString(r)}})}nonempty(e){return this.min(1,e)}}Ye.create=(t,e)=>new Ye({type:t,minLength:null,maxLength:null,exactLength:null,typeName:b.ZodArray,...X(e)});function Mt(t){if(t instanceof le){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=pt.create(Mt(n))}return new le({...t._def,shape:()=>e})}else return t instanceof Ye?new Ye({...t._def,type:Mt(t.element)}):t instanceof pt?pt.create(Mt(t.unwrap())):t instanceof Ht?Ht.create(Mt(t.unwrap())):t instanceof it?it.create(t.items.map(e=>Mt(e))):t}class le extends ee{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=te.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==R.object){const u=this._getOrReturnCtx(e);return x(u,{code:w.invalid_type,expected:R.object,received:u.parsedType}),V}const{status:n,ctx:a}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof mt&&this._def.unknownKeys==="strip"))for(const u in a.data)i.includes(u)||o.push(u);const c=[];for(const u of i){const l=s[u],d=a.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Qe(a,d,a.path,u)),alwaysSet:u in a.data})}if(this._def.catchall instanceof mt){const u=this._def.unknownKeys;if(u==="passthrough")for(const l of o)c.push({key:{status:"valid",value:l},value:{status:"valid",value:a.data[l]}});else if(u==="strict")o.length>0&&(x(a,{code:w.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const l of o){const d=a.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Qe(a,d,a.path,l)),alwaysSet:l in a.data})}}return a.common.async?Promise.resolve().then(async()=>{const u=[];for(const l of c){const d=await l.key,f=await l.value;u.push({key:d,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>xe.mergeObjectSync(n,u)):xe.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return N.errToObj,new le({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{const a=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:N.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new le({...this._def,unknownKeys:"strip"})}passthrough(){return new le({...this._def,unknownKeys:"passthrough"})}extend(e){return new le({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new le({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:b.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new le({...this._def,catchall:e})}pick(e){const r={};for(const n of te.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new le({...this._def,shape:()=>r})}omit(e){const r={};for(const n of te.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new le({...this._def,shape:()=>r})}deepPartial(){return Mt(this)}partial(e){const r={};for(const n of te.objectKeys(this.shape)){const a=this.shape[n];e&&!e[n]?r[n]=a:r[n]=a.optional()}return new le({...this._def,shape:()=>r})}required(e){const r={};for(const n of te.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof pt;)s=s._def.innerType;r[n]=s}return new le({...this._def,shape:()=>r})}keyof(){return oc(te.objectKeys(this.shape))}}le.create=(t,e)=>new le({shape:()=>t,unknownKeys:"strip",catchall:mt.create(),typeName:b.ZodObject,...X(e)});le.strictCreate=(t,e)=>new le({shape:()=>t,unknownKeys:"strict",catchall:mt.create(),typeName:b.ZodObject,...X(e)});le.lazycreate=(t,e)=>new le({shape:t,unknownKeys:"strip",catchall:mt.create(),typeName:b.ZodObject,...X(e)});class Kr extends ee{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function a(s){for(const o of s)if(o.result.status==="valid")return o.result;for(const o of s)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;const i=s.map(o=>new De(o.ctx.common.issues));return x(r,{code:w.invalid_union,unionErrors:i}),V}if(r.common.async)return Promise.all(n.map(async s=>{const i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(a);{let s;const i=[];for(const c of n){const u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const o=i.map(c=>new De(c));return x(r,{code:w.invalid_union,unionErrors:o}),V}}get options(){return this._def.options}}Kr.create=(t,e)=>new Kr({options:t,typeName:b.ZodUnion,...X(e)});function za(t,e){const r=ft(t),n=ft(e);if(t===e)return{valid:!0,data:t};if(r===R.object&&n===R.object){const a=te.objectKeys(e),s=te.objectKeys(t).filter(o=>a.indexOf(o)!==-1),i={...t,...e};for(const o of s){const c=za(t[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(r===R.array&&n===R.array){if(t.length!==e.length)return{valid:!1};const a=[];for(let s=0;s<t.length;s++){const i=t[s],o=e[s],c=za(i,o);if(!c.valid)return{valid:!1};a.push(c.data)}return{valid:!0,data:a}}else return r===R.date&&n===R.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class Yr extends ee{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),a=(s,i)=>{if(Ks(s)||Ks(i))return V;const o=za(s.value,i.value);return o.valid?((Ys(s)||Ys(i))&&r.dirty(),{status:r.value,value:o.data}):(x(n,{code:w.invalid_intersection_types}),V)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>a(s,i)):a(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Yr.create=(t,e,r)=>new Yr({left:t,right:e,typeName:b.ZodIntersection,...X(r)});class it extends ee{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return x(n,{code:w.invalid_type,expected:R.array,received:n.parsedType}),V;if(n.data.length<this._def.items.length)return x(n,{code:w.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),V;!this._def.rest&&n.data.length>this._def.items.length&&(x(n,{code:w.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...n.data].map((i,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new Qe(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>xe.mergeArray(r,i)):xe.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new it({...this._def,rest:e})}}it.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new it({items:t,typeName:b.ZodTuple,rest:null,...X(e)})};class Xr extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.object)return x(n,{code:w.invalid_type,expected:R.object,received:n.parsedType}),V;const a=[],s=this._def.keyType,i=this._def.valueType;for(const o in n.data)a.push({key:s._parse(new Qe(n,o,n.path,o)),value:i._parse(new Qe(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?xe.mergeObjectAsync(r,a):xe.mergeObjectSync(r,a)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ee?new Xr({keyType:e,valueType:r,typeName:b.ZodRecord,...X(n)}):new Xr({keyType:nt.create(),valueType:e,typeName:b.ZodRecord,...X(r)})}}class ri extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.map)return x(n,{code:w.invalid_type,expected:R.map,received:n.parsedType}),V;const a=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([o,c],u)=>({key:a._parse(new Qe(n,o,n.path,[u,"key"])),value:s._parse(new Qe(n,c,n.path,[u,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of i){const u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return V;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(u.value,l.value)}return{status:r.value,value:o}})}else{const o=new Map;for(const c of i){const u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return V;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(u.value,l.value)}return{status:r.value,value:o}}}}ri.create=(t,e,r)=>new ri({valueType:e,keyType:t,typeName:b.ZodMap,...X(r)});class dr extends ee{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return x(n,{code:w.invalid_type,expected:R.set,received:n.parsedType}),V;const a=this._def;a.minSize!==null&&n.data.size<a.minSize.value&&(x(n,{code:w.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),r.dirty()),a.maxSize!==null&&n.data.size>a.maxSize.value&&(x(n,{code:w.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),r.dirty());const s=this._def.valueType;function i(c){const u=new Set;for(const l of c){if(l.status==="aborted")return V;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}const o=[...n.data.values()].map((c,u)=>s._parse(new Qe(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,r){return new dr({...this._def,minSize:{value:e,message:N.toString(r)}})}max(e,r){return new dr({...this._def,maxSize:{value:e,message:N.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}dr.create=(t,e)=>new dr({valueType:t,minSize:null,maxSize:null,typeName:b.ZodSet,...X(e)});class sr extends ee{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.function)return x(r,{code:w.invalid_type,expected:R.function,received:r.parsedType}),V;function n(o,c){return Ua({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Da(),cr].filter(u=>!!u),issueData:{code:w.invalid_arguments,argumentsError:c}})}function a(o,c){return Ua({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Da(),cr].filter(u=>!!u),issueData:{code:w.invalid_return_type,returnTypeError:c}})}const s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof fr){const o=this;return Ne(async function(...c){const u=new De([]),l=await o._def.args.parseAsync(c,s).catch(h=>{throw u.addIssue(n(c,h)),u}),d=await Reflect.apply(i,this,l);return await o._def.returns._def.type.parseAsync(d,s).catch(h=>{throw u.addIssue(a(d,h)),u})})}else{const o=this;return Ne(function(...c){const u=o._def.args.safeParse(c,s);if(!u.success)throw new De([n(c,u.error)]);const l=Reflect.apply(i,this,u.data),d=o._def.returns.safeParse(l,s);if(!d.success)throw new De([a(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new sr({...this._def,args:it.create(e).rest(Ut.create())})}returns(e){return new sr({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new sr({args:e||it.create([]).rest(Ut.create()),returns:r||Ut.create(),typeName:b.ZodFunction,...X(n)})}}class ni extends ee{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}ni.create=(t,e)=>new ni({getter:t,typeName:b.ZodLazy,...X(e)});class qa extends ee{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return x(r,{received:r.data,code:w.invalid_literal,expected:this._def.value}),V}return{status:"valid",value:e.data}}get value(){return this._def.value}}qa.create=(t,e)=>new qa({value:t,typeName:b.ZodLiteral,...X(e)});function oc(t,e){return new qt({values:t,typeName:b.ZodEnum,...X(e)})}class qt extends ee{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return x(r,{expected:te.joinValues(n),received:r.parsedType,code:w.invalid_type}),V}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return x(r,{received:r.data,code:w.invalid_enum_value,options:n}),V}return Ne(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return qt.create(e,{...this._def,...r})}exclude(e,r=this._def){return qt.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}qt.create=oc;class ai extends ee{_parse(e){const r=te.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){const a=te.objectValues(r);return x(n,{expected:te.joinValues(a),received:n.parsedType,code:w.invalid_type}),V}if(this._cache||(this._cache=new Set(te.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const a=te.objectValues(r);return x(n,{received:n.data,code:w.invalid_enum_value,options:a}),V}return Ne(e.data)}get enum(){return this._def.values}}ai.create=(t,e)=>new ai({values:t,typeName:b.ZodNativeEnum,...X(e)});class fr extends ee{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.promise&&r.common.async===!1)return x(r,{code:w.invalid_type,expected:R.promise,received:r.parsedType}),V;const n=r.parsedType===R.promise?r.data:Promise.resolve(r.data);return Ne(n.then(a=>this._def.type.parseAsync(a,{path:r.path,errorMap:r.common.contextualErrorMap})))}}fr.create=(t,e)=>new fr({type:t,typeName:b.ZodPromise,...X(e)});class Gt extends ee{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===b.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),a=this._def.effect||null,s={addIssue:i=>{x(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),a.type==="preprocess"){const i=a.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async o=>{if(r.value==="aborted")return V;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?V:c.status==="dirty"||r.value==="dirty"?tr(c.value):c});{if(r.value==="aborted")return V;const o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?V:o.status==="dirty"||r.value==="dirty"?tr(o.value):o}}if(a.type==="refinement"){const i=o=>{const c=a.refinement(o,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?V:(o.status==="dirty"&&r.dirty(),i(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?V:(o.status==="dirty"&&r.dirty(),i(o.value).then(()=>({status:r.value,value:o.value}))))}if(a.type==="transform")if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Bt(i))return V;const o=a.transform(i.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Bt(i)?Promise.resolve(a.transform(i.value,s)).then(o=>({status:r.value,value:o})):V);te.assertNever(a)}}Gt.create=(t,e,r)=>new Gt({schema:t,typeName:b.ZodEffects,effect:e,...X(r)});Gt.createWithPreprocess=(t,e,r)=>new Gt({schema:e,effect:{type:"preprocess",transform:t},typeName:b.ZodEffects,...X(r)});class pt extends ee{_parse(e){return this._getType(e)===R.undefined?Ne(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}pt.create=(t,e)=>new pt({innerType:t,typeName:b.ZodOptional,...X(e)});class Ht extends ee{_parse(e){return this._getType(e)===R.null?Ne(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ht.create=(t,e)=>new Ht({innerType:t,typeName:b.ZodNullable,...X(e)});class Ga extends ee{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}Ga.create=(t,e)=>new Ga({innerType:t,typeName:b.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...X(e)});class Ha extends ee{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},a=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Jr(a)?a.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new De(n.common.issues)},input:n.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new De(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Ha.create=(t,e)=>new Ha({innerType:t,typeName:b.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...X(e)});class si extends ee{_parse(e){if(this._getType(e)!==R.nan){const n=this._getOrReturnCtx(e);return x(n,{code:w.invalid_type,expected:R.nan,received:n.parsedType}),V}return{status:"valid",value:e.data}}}si.create=t=>new si({typeName:b.ZodNaN,...X(t)});class Ol extends ee{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class cs extends ee{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?V:s.status==="dirty"?(r.dirty(),tr(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const a=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?V:a.status==="dirty"?(r.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:n.path,parent:n})}}static create(e,r){return new cs({in:e,out:r,typeName:b.ZodPipeline})}}class Za extends ee{_parse(e){const r=this._def.innerType._parse(e),n=a=>(Bt(a)&&(a.value=Object.freeze(a.value)),a);return Jr(r)?r.then(a=>n(a)):n(r)}unwrap(){return this._def.innerType}}Za.create=(t,e)=>new Za({innerType:t,typeName:b.ZodReadonly,...X(e)});function ii(t,e){const r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Rl(t,e={},r){return t?lr.create().superRefine((n,a)=>{const s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){const o=ii(e,n),c=o.fatal??r??!0;a.addIssue({code:"custom",...o,fatal:c})}});if(!s){const i=ii(e,n),o=i.fatal??r??!0;a.addIssue({code:"custom",...i,fatal:o})}}):lr.create()}var b;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(b||(b={}));const wg=(t,e={message:`Input not instance of ${t.name}`})=>Rl(r=>r instanceof t,e),kl=nt.create,bg=zt.create,Eg=Fa.create,Sg=Ba.create,oi=lr.create;Ut.create;mt.create;const Tg=Ye.create,$l=le.create,xg=Kr.create;Yr.create;it.create;const Ig=Xr.create,Ag=sr.create,Og=qa.create,Rg=qt.create,kg=fr.create;pt.create;Ht.create;var Cl=Object.defineProperty,me=(t,e)=>{for(var r in e)Cl(t,r,{get:e[r],enumerable:!0})};function ot(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}function us(t){return ot(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function ls(t){return ot(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function cc(t){return ot(t)&&t.source_type==="text"&&"text"in t&&typeof t.text=="string"}function ds(t){return ot(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}function uc(t){if(ot(t)){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url}};if(t.source_type==="base64"){if(!t.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${t.mime_type};base64,${t.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function lc(t){const e=t.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${t}" - does not match type/subtype format.`);const r=e[0].trim(),n=e[1].trim();if(r===""||n==="")throw new Error(`Invalid mime type: "${t}" - type or subtype is empty.`);const a={};for(const s of t.split(";").slice(1)){const i=s.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${t}".`);const o=i[0].trim(),c=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${t}".`);a[o]=c}return{type:r,subtype:n,parameters:a}}function Qr({dataUrl:t,asTypedArray:e=!1}){const r=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let n;if(r){n=r[1].toLowerCase();const a=e?Uint8Array.from(atob(r[2]),s=>s.charCodeAt(0)):r[2];return{mime_type:n,data:a}}}function dc(t,e){if(t.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(t)}if(t.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(t)}if(t.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(t)}if(t.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(t)}throw new Error(`Unable to convert content block type '${t.type}' to provider-specific format: not recognized.`)}function fs(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}var Tn,ci;function Nl(){return ci||(ci=1,Tn=function(t,e){if(typeof t!="string")throw new TypeError("Expected a string");return e=typeof e>"u"?"_":e,t.replace(/([a-z\d])([A-Z])/g,"$1"+e+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+e+"$2").toLowerCase()}),Tn}var Pl=Nl();const Ml=br(Pl);var Lr={exports:{}},ui;function Ll(){if(ui)return Lr.exports;ui=1;const t=/[\p{Lu}]/u,e=/[\p{Ll}]/u,r=/^[\p{Lu}](?![\p{Lu}])/gu,n=/([\p{Alpha}\p{N}_]|$)/u,a=/[_.\- ]+/,s=new RegExp("^"+a.source),i=new RegExp(a.source+n.source,"gu"),o=new RegExp("\\d+"+n.source,"gu"),c=(f,h,p)=>{let m=!1,g=!1,y=!1;for(let v=0;v<f.length;v++){const _=f[v];m&&t.test(_)?(f=f.slice(0,v)+"-"+f.slice(v),m=!1,y=g,g=!0,v++):g&&y&&e.test(_)?(f=f.slice(0,v-1)+"-"+f.slice(v-1),y=g,g=!1,m=!0):(m=h(_)===_&&p(_)!==_,y=g,g=p(_)===_&&h(_)!==_)}return f},u=(f,h)=>(r.lastIndex=0,f.replace(r,p=>h(p))),l=(f,h)=>(i.lastIndex=0,o.lastIndex=0,f.replace(i,(p,m)=>h(m)).replace(o,p=>h(p))),d=(f,h)=>{if(!(typeof f=="string"||Array.isArray(f)))throw new TypeError("Expected the input to be `string | string[]`");if(h={pascalCase:!1,preserveConsecutiveUppercase:!1,...h},Array.isArray(f)?f=f.map(y=>y.trim()).filter(y=>y.length).join("-"):f=f.trim(),f.length===0)return"";const p=h.locale===!1?y=>y.toLowerCase():y=>y.toLocaleLowerCase(h.locale),m=h.locale===!1?y=>y.toUpperCase():y=>y.toLocaleUpperCase(h.locale);return f.length===1?h.pascalCase?m(f):p(f):(f!==p(f)&&(f=c(f,p,m)),f=f.replace(s,""),h.preserveConsecutiveUppercase?f=u(f,p):f=p(f),h.pascalCase&&(f=m(f.charAt(0))+f.slice(1)),l(f,m))};return Lr.exports=d,Lr.exports.default=d,Lr.exports}var jl=Ll();const Dl=br(jl);function Ul(t,e){return e?.[t]||Ml(t)}function $g(t,e){return e?.[t]||Dl(t)}function Fl(t,e,r){const n={};for(const a in t)Object.hasOwn(t,a)&&(n[e(a,r)]=t[a]);return n}var Bl={};me(Bl,{Serializable:()=>hr,get_lc_unique_name:()=>hs});function li(t){return Array.isArray(t)?[...t]:{...t}}function zl(t,e){const r=li(t);for(const[n,a]of Object.entries(e)){const[s,...i]=n.split(".").reverse();let o=r;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=li(o[c]),o=o[c]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[a]})}return r}function hs(t){const e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}var hr=class fc{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,hs(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...r){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof fc||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},r={},n=Object.keys(this.lc_kwargs).reduce((a,s)=>(a[s]=s in this?this[s]:this.lc_kwargs[s],a),{});for(let a=Object.getPrototypeOf(this);a;a=Object.getPrototypeOf(a))Object.assign(e,Reflect.get(a,"lc_aliases",this)),Object.assign(r,Reflect.get(a,"lc_secrets",this)),Object.assign(n,Reflect.get(a,"lc_attributes",this));return Object.keys(r).forEach(a=>{let s=this,i=n;const[o,...c]=a.split(".").reverse();for(const u of c.reverse()){if(!(u in s)||s[u]===void 0)return;(!(u in i)||i[u]===void 0)&&(typeof s[u]=="object"&&s[u]!=null?i[u]={}:Array.isArray(s[u])&&(i[u]=[])),s=s[u],i=i[u]}o in s&&s[o]!==void 0&&(i[o]=i[o]||s[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:Fl(Object.keys(r).length?zl(n,r):n,Ul,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function D(t,e){return W(t)&&t.type===e}function W(t){return typeof t=="object"&&t!==null}function Xe(t){return Array.isArray(t)}function k(t){return typeof t=="string"}function qe(t){return typeof t=="number"}function ps(t){return t instanceof Uint8Array}function di(t){try{return JSON.parse(t)}catch{return}}const pr=t=>t();function ql(t){if(t.type==="char_location"&&k(t.document_title)&&qe(t.start_char_index)&&qe(t.end_char_index)&&k(t.cited_text)){const{document_title:e,start_char_index:r,end_char_index:n,cited_text:a,...s}=t;return{...s,type:"citation",source:"char",title:e??void 0,startIndex:r,endIndex:n,citedText:a}}if(t.type==="page_location"&&k(t.document_title)&&qe(t.start_page_number)&&qe(t.end_page_number)&&k(t.cited_text)){const{document_title:e,start_page_number:r,end_page_number:n,cited_text:a,...s}=t;return{...s,type:"citation",source:"page",title:e??void 0,startIndex:r,endIndex:n,citedText:a}}if(t.type==="content_block_location"&&k(t.document_title)&&qe(t.start_block_index)&&qe(t.end_block_index)&&k(t.cited_text)){const{document_title:e,start_block_index:r,end_block_index:n,cited_text:a,...s}=t;return{...s,type:"citation",source:"block",title:e??void 0,startIndex:r,endIndex:n,citedText:a}}if(t.type==="web_search_result_location"&&k(t.url)&&k(t.title)&&k(t.encrypted_index)&&k(t.cited_text)){const{url:e,title:r,encrypted_index:n,cited_text:a,...s}=t;return{...s,type:"citation",source:"url",url:e,title:r,startIndex:Number(n),endIndex:Number(n),citedText:a}}if(t.type==="search_result_location"&&k(t.source)&&k(t.title)&&qe(t.start_block_index)&&qe(t.end_block_index)&&k(t.cited_text)){const{source:e,title:r,start_block_index:n,end_block_index:a,cited_text:s,...i}=t;return{...i,type:"citation",source:"search",url:e,title:r??void 0,startIndex:n,endIndex:a,citedText:s}}}function hc(t){if(D(t,"document")&&W(t.source)&&"type"in t.source){if(t.source.type==="base64"&&k(t.source.media_type)&&k(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&k(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&k(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&k(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(D(t,"image")&&W(t.source)&&"type"in t.source){if(t.source.type==="base64"&&k(t.source.media_type)&&k(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&k(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&k(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}function Gl(t){function*e(){for(const r of t){const n=hc(r);n?yield n:yield r}}return Array.from(e())}function fi(t){function*e(){const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r){if(D(n,"text")&&k(n.text)){const{text:a,citations:s,...i}=n;if(Xe(s)&&s.length){const o=s.reduce((c,u)=>{const l=ql(u);return l?[...c,l]:c},[]);yield{...i,type:"text",text:a,annotations:o};continue}else{yield{...i,type:"text",text:a};continue}}else if(D(n,"thinking")&&k(n.thinking)){const{thinking:a,signature:s,...i}=n;yield{...i,type:"reasoning",reasoning:a,signature:s};continue}else if(D(n,"redacted_thinking")){yield{type:"non_standard",value:n};continue}else if(D(n,"tool_use")&&k(n.name)&&k(n.id)){yield{type:"tool_call",id:n.id,name:n.name,args:n.input};continue}else if(D(n,"input_json_delta")){if(Zl(t)&&t.tool_call_chunks?.length){const a=t.tool_call_chunks[0];yield{type:"tool_call_chunk",id:a.id,name:a.name,args:a.args,index:a.index};continue}}else if(D(n,"server_tool_use")&&k(n.name)&&k(n.id)){const{name:a,id:s}=n;if(a==="web_search"){const i=pr(()=>{if(typeof n.input=="string")return n.input;if(W(n.input)&&k(n.input.query))return n.input.query;if(k(n.partial_json)){const o=di(n.partial_json);if(o?.query)return o.query}return""});yield{id:s,type:"server_tool_call",name:"web_search",args:{query:i}};continue}else if(n.name==="code_execution"){const i=pr(()=>{if(typeof n.input=="string")return n.input;if(W(n.input)&&k(n.input.code))return n.input.code;if(k(n.partial_json)){const o=di(n.partial_json);if(o?.code)return o.code}return""});yield{id:s,type:"server_tool_call",name:"code_execution",args:{code:i}};continue}}else if(D(n,"web_search_tool_result")&&k(n.tool_use_id)&&Xe(n.content)){const{content:a,tool_use_id:s}=n,i=a.reduce((o,c)=>D(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:s,status:"success",output:{urls:i}};continue}else if(D(n,"code_execution_tool_result")&&k(n.tool_use_id)&&W(n.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(D(n,"mcp_tool_use")){yield{id:n.id,type:"server_tool_call",name:"mcp_tool_use",args:n.input};continue}else if(D(n,"mcp_tool_result")&&k(n.tool_use_id)&&W(n.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(D(n,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:n.input};continue}else if(D(n,"search_result")){yield{id:n.id,type:"non_standard",value:n};continue}else if(D(n,"tool_result")){yield{id:n.id,type:"non_standard",value:n};continue}else{const a=hc(n);if(a){yield a;continue}}yield{type:"non_standard",value:n}}}return Array.from(e())}const Hl={translateContent:fi,translateContentChunk:fi};function Zl(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}function Vl(t){return us(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:ls(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:ds(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}function Jl(t){return t.map(Vl)}function Wl(t){return!!(D(t,"image_url")&&W(t.image_url)||D(t,"input_audio")&&W(t.input_audio)||D(t,"file")&&W(t.file))}function Kl(t){if(D(t,"image_url")&&W(t.image_url)&&k(t.image_url.url)){const e=Qr({dataUrl:t.image_url.url});return e?{type:"image",mimeType:e.mime_type,data:e.data}:{type:"image",url:t.image_url.url}}else{if(D(t,"input_audio")&&W(t.input_audio)&&k(t.input_audio.data)&&k(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(D(t,"file")&&W(t.file)&&k(t.file.data)){const e=Qr({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(k(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}function Yl(t){const e=[];typeof t.content=="string"?e.push({type:"text",text:t.content}):e.push(...ms(t.content));for(const r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}function Xl(t){const e=[];typeof t.content=="string"?e.push({type:"text",text:t.content}):e.push(...ms(t.content));for(const r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}function ms(t){const e=[];for(const r of t)Wl(r)?e.push(Kl(r)):e.push(r);return e}function Ql(t){if(t.type==="url_citation"){const{url:e,title:r,start_index:n,end_index:a}=t;return{type:"citation",url:e,title:r,startIndex:n,endIndex:a}}if(t.type==="file_citation"){const{file_id:e,filename:r,index:n}=t;return{type:"citation",title:r,startIndex:n,endIndex:n,fileId:e}}return t}function pc(t){function*e(){W(t.additional_kwargs?.reasoning)&&Xe(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((a,s)=>W(s)&&k(s.text)?`${a}${s.text}`:a,"")});const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r)if(D(n,"text")){const{text:a,annotations:s,...i}=n;Array.isArray(s)?yield{...i,type:"text",text:String(a),annotations:s.map(Ql)}:yield{...i,type:"text",text:String(a)}}for(const n of t.tool_calls??[])yield{type:"tool_call",id:n.id,name:n.name,args:n.args};if(W(t.additional_kwargs)&&Xe(t.additional_kwargs.tool_outputs))for(const n of t.additional_kwargs.tool_outputs){if(D(n,"web_search_call")){yield{id:n.id,type:"server_tool_call",name:"web_search",args:{query:n.query}};continue}else if(D(n,"file_search_call")){yield{id:n.id,type:"server_tool_call",name:"file_search",args:{query:n.query}};continue}else if(D(n,"computer_call")){yield{type:"non_standard",value:n};continue}else if(D(n,"code_interpreter_call")){if(k(n.code)&&(yield{id:n.id,type:"server_tool_call",name:"code_interpreter",args:{code:n.code}}),Xe(n.outputs)){const a=pr(()=>{if(n.status!=="in_progress"){if(n.status==="completed")return 0;if(n.status==="incomplete")return 127;if(n.status!=="interpreting"&&n.status==="failed")return 1}});for(const s of n.outputs)if(D(s,"logs")){yield{type:"server_tool_call_result",toolCallId:n.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:a??0,stderr:[0,void 0].includes(a)?void 0:String(s.logs),stdout:[0,void 0].includes(a)?String(s.logs):void 0}};continue}}continue}else if(D(n,"mcp_call")){yield{id:n.id,type:"server_tool_call",name:"mcp_call",args:n.input};continue}else if(D(n,"mcp_list_tools")){yield{id:n.id,type:"server_tool_call",name:"mcp_list_tools",args:n.input};continue}else if(D(n,"mcp_approval_request")){yield{type:"non_standard",value:n};continue}else if(D(n,"image_generation_call")){yield{type:"non_standard",value:n};continue}W(n)&&(yield{type:"non_standard",value:n})}}return Array.from(e())}function ed(t){function*e(){yield*pc(t);for(const r of t.tool_call_chunks??[])yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args}}return Array.from(e())}const td={translateContent:t=>typeof t.content=="string"?Yl(t):pc(t),translateContentChunk:t=>typeof t.content=="string"?Xl(t):ed(t)};function rd(t,e="pretty"){return e==="pretty"?nd(t):JSON.stringify(t)}function nd(t){const e=[],r=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,n=Math.floor((80-r.length)/2),a="=".repeat(n),s=r.length%2===0?a:`${a}=`;if(e.push(`${a}${r}${s}`),t.type==="ai"){const i=t;if(i.tool_calls&&i.tool_calls.length>0){e.push("Tool Calls:");for(const o of i.tool_calls){e.push(` ${o.name} (${o.id})`),e.push(` Call ID: ${o.id}`),e.push(" Args:");for(const[c,u]of Object.entries(o.args))e.push(` ${c}: ${u}`)}}}if(t.type==="tool"){const i=t;i.name&&e.push(`Name: ${i.name}`)}return typeof t.content=="string"&&t.content.trim()&&(e.length>1&&e.push(""),e.push(t.content)),e.join(`
4
- `)}const xn=Symbol.for("langchain.message");function yt(t,e){return typeof t=="string"?t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.some(r=>ot(r))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e]:Array.isArray(e)?Vt(t,e)??[...t,...e]:e===""?t:Array.isArray(t)&&t.some(r=>ot(r))?[...t,{type:"file",source_type:"text",text:e}]:[...t,{type:"text",text:e}]}function gs(t,e){return t==="error"||e==="error"?"error":"success"}function ad(t,e){function r(n,a){if(typeof n!="object"||n===null||n===void 0)return n;if(a>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(i=>r(i,a+1));const s={};for(const i of Object.keys(n))s[i]=r(n[i],a+1);return s}return JSON.stringify(r(t,0),null,2)}var tt=class extends hr{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[xn]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(t){const e=typeof t=="string"||Array.isArray(t)?{content:t}:t;e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),this.name=e.name,e.content===void 0&&e.contentBlocks!==void 0?(this.content=e.contentBlocks,this.response_metadata={output_version:"v1",...e.response_metadata}):e.content!==void 0?(this.content=e.content??[],this.response_metadata=e.response_metadata):(this.content=[],this.response_metadata=e.response_metadata),this.additional_kwargs=e.additional_kwargs,this.id=e.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(t=>typeof t=="string"?t:t.type==="text"?t.text:"").join(""):""}get contentBlocks(){const t=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[Jl,ms,Gl].reduce((n,a)=>a(n),t)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(t){return typeof t=="object"&&t!==null&&xn in t&&t[xn]===!0&&fs(t)}_updateId(t){this.id=t,this.lc_kwargs.id=t}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](t){if(t===null)return this;const e=ad(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return rd(this,t)}};function mc(t){return Array.isArray(t)&&t.every(e=>typeof e.index=="number")}function ve(t={},e={}){const r={...t};for(const[n,a]of Object.entries(e))if(r[n]==null)r[n]=a;else{if(a==null)continue;if(typeof r[n]!=typeof a||Array.isArray(r[n])!==Array.isArray(a))throw new Error(`field[${n}] already exists in the message chunk, but with a different type.`);if(typeof r[n]=="string"){if(n==="type")continue;["id","name","output_version","model_provider"].includes(n)?r[n]=a:r[n]+=a}else if(typeof r[n]=="object"&&!Array.isArray(r[n]))r[n]=ve(r[n],a);else if(Array.isArray(r[n]))r[n]=Vt(r[n],a);else{if(r[n]===a)continue;console.warn(`field[${n}] already exists in this message chunk and value has unsupported type.`)}}return r}function Vt(t,e){if(!(t===void 0&&e===void 0)){if(t===void 0||e===void 0)return t||e;{const r=[...t];for(const n of e)if(typeof n=="object"&&n!==null&&"index"in n&&typeof n.index=="number"){const a=r.findIndex(s=>{const i=typeof s=="object",o="index"in s&&s.index===n.index,c="id"in s&&"id"in n&&s?.id===n?.id,u=!("id"in s)||!s?.id||!("id"in n)||!n?.id;return i&&o&&(c||u)});a!==-1&&typeof r[a]=="object"&&r[a]!==null?r[a]=ve(r[a],n):r.push(n)}else{if(typeof n=="object"&&n!==null&&"text"in n&&n.text==="")continue;r.push(n)}return r}}}function ys(t,e){if(!t&&!e)throw new Error("Cannot merge two undefined objects.");if(!t||!e)return t||e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types.
1
+ import{g as wr,f as Le,h as tc,i as Tt,j as Ju,$ as Ku,k as rc,d as is,l as Yu,m as Xu,n as Qu,o as el,t as Zs}from"./index-BHRzjpbc.js";var te;(function(t){t.assertEqual=a=>{};function e(a){}t.assertIs=e;function r(a){throw new Error}t.assertNever=r,t.arrayToEnum=a=>{const s={};for(const i of a)s[i]=i;return s},t.getValidEnumValues=a=>{const s=t.objectKeys(a).filter(o=>typeof a[a[o]]!="number"),i={};for(const o of s)i[o]=a[o];return t.objectValues(i)},t.objectValues=a=>t.objectKeys(a).map(function(s){return a[s]}),t.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{const s=[];for(const i in a)Object.prototype.hasOwnProperty.call(a,i)&&s.push(i);return s},t.find=(a,s)=>{for(const i of a)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function n(a,s=" | "){return a.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(a,s)=>typeof s=="bigint"?s.toString():s})(te||(te={}));var Vs;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Vs||(Vs={}));const O=te.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),dt=t=>{switch(typeof t){case"undefined":return O.undefined;case"string":return O.string;case"number":return Number.isNaN(t)?O.nan:O.number;case"boolean":return O.boolean;case"function":return O.function;case"bigint":return O.bigint;case"symbol":return O.symbol;case"object":return Array.isArray(t)?O.array:t===null?O.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?O.promise:typeof Map<"u"&&t instanceof Map?O.map:typeof Set<"u"&&t instanceof Set?O.set:typeof Date<"u"&&t instanceof Date?O.date:O.object;default:return O.unknown}},v=te.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class je extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(s){return s.message},n={_errors:[]},a=s=>{for(const i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(a);else if(i.code==="invalid_return_type")a(i.returnTypeError);else if(i.code==="invalid_arguments")a(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let o=n,c=0;for(;c<i.path.length;){const u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(r(i))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return a(this),n}static assert(e){if(!(e instanceof je))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,te.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r=Object.create(null),n=[];for(const a of this.issues)if(a.path.length>0){const s=a.path[0];r[s]=r[s]||[],r[s].push(e(a))}else n.push(e(a));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}je.create=t=>new je(t);const or=(t,e)=>{let r;switch(t.code){case v.invalid_type:t.received===O.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case v.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,te.jsonStringifyReplacer)}`;break;case v.unrecognized_keys:r=`Unrecognized key(s) in object: ${te.joinValues(t.keys,", ")}`;break;case v.invalid_union:r="Invalid input";break;case v.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${te.joinValues(t.options)}`;break;case v.invalid_enum_value:r=`Invalid enum value. Expected ${te.joinValues(t.options)}, received '${t.received}'`;break;case v.invalid_arguments:r="Invalid function arguments";break;case v.invalid_return_type:r="Invalid function return type";break;case v.invalid_date:r="Invalid date";break;case v.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:te.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case v.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case v.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case v.custom:r="Invalid input";break;case v.invalid_intersection_types:r="Intersection results could not be merged";break;case v.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case v.not_finite:r="Number must be finite";break;default:r=e.defaultError,te.assertNever(t)}return{message:r}};let tl=or;function ja(){return tl}const Da=t=>{const{data:e,path:r,errorMaps:n,issueData:a}=t,s=[...r,...a.path||[]],i={...a,path:s};if(a.message!==void 0)return{...a,path:s,message:a.message};let o="";const c=n.filter(u=>!!u).slice().reverse();for(const u of c)o=u(i,{data:e,defaultError:o}).message;return{...a,path:s,message:o}};function T(t,e){const r=ja(),n=Da({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===or?void 0:or].filter(a=>!!a)});t.common.issues.push(n)}class Te{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const a of r){if(a.status==="aborted")return V;a.status==="dirty"&&e.dirty(),n.push(a.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const a of r){const s=await a.key,i=await a.value;n.push({key:s,value:i})}return Te.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const a of r){const{key:s,value:i}=a;if(s.status==="aborted"||i.status==="aborted")return V;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||a.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}}const V=Object.freeze({status:"aborted"}),er=t=>({status:"dirty",value:t}),ke=t=>({status:"valid",value:t}),Ws=t=>t.status==="aborted",Js=t=>t.status==="dirty",Ft=t=>t.status==="valid",Vr=t=>typeof Promise<"u"&&t instanceof Promise;var N;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(N||(N={}));class Xe{constructor(e,r,n,a){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ks=(t,e)=>{if(Ft(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new je(t.common.issues);return this._error=r,this._error}}};function X(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:a}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:a}:{errorMap:(i,o)=>{const{message:c}=t;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:a}}class ee{get description(){return this._def.description}_getType(e){return dt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:dt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Te,ctx:{common:e.parent.common,data:e.data,parsedType:dt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(Vr(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:dt(e)},a=this._parseSync({data:e,path:n.path,parent:n});return Ks(n,a)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:dt(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return Ft(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Ft(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:dt(e)},a=this._parse({data:e,path:n.path,parent:n}),s=await(Vr(a)?a:Promise.resolve(a));return Ks(n,s)}refine(e,r){const n=a=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(a):r;return this._refinement((a,s)=>{const i=e(a),o=()=>s.addIssue({code:v.custom,...n(a)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,a)=>e(n)?!0:(a.addIssue(typeof r=="function"?r(n,a):r),!1))}_refinement(e){return new qt({schema:this,typeName:b.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return ht.create(this,this._def)}nullable(){return Gt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ke.create(this)}promise(){return dr.create(this,this._def)}or(e){return Jr.create([this,e],this._def)}and(e){return Kr.create(this,e,this._def)}transform(e){return new qt({...X(this._def),schema:this,typeName:b.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new qa({...X(this._def),innerType:this,defaultValue:r,typeName:b.ZodDefault})}brand(){return new Tl({typeName:b.ZodBranded,type:this,...X(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new Ga({...X(this._def),innerType:this,catchValue:r,typeName:b.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return os.create(this,e)}readonly(){return Ha.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const rl=/^c[^\s-]{8,}$/i,nl=/^[0-9a-z]+$/,al=/^[0-9A-HJKMNP-TV-Z]{26}$/i,sl=/^[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,il=/^[a-z0-9_-]{21}$/i,ol=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,cl=/^[-+]?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)?)??$/,ul=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ll="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let En;const dl=/^(?:(?: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])$/,fl=/^(?:(?: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])$/,hl=/^(([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]))$/,pl=/^(([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])$/,ml=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,gl=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nc="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",_l=new RegExp(`^${nc}$`);function ac(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function yl(t){return new RegExp(`^${ac(t)}$`)}function vl(t){let e=`${nc}T${ac(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function wl(t,e){return!!((e==="v4"||!e)&&dl.test(t)||(e==="v6"||!e)&&hl.test(t))}function bl(t,e){if(!ol.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),a=JSON.parse(atob(n));return!(typeof a!="object"||a===null||"typ"in a&&a?.typ!=="JWT"||!a.alg||e&&a.alg!==e)}catch{return!1}}function El(t,e){return!!((e==="v4"||!e)&&fl.test(t)||(e==="v6"||!e)&&pl.test(t))}class rt extends ee{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==O.string){const s=this._getOrReturnCtx(e);return T(s,{code:v.invalid_type,expected:O.string,received:s.parsedType}),V}const n=new Te;let a;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(a=this._getOrReturnCtx(e,a),T(a,{code:v.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(a=this._getOrReturnCtx(e,a),T(a,{code:v.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){const i=e.data.length>s.value,o=e.data.length<s.value;(i||o)&&(a=this._getOrReturnCtx(e,a),i?T(a,{code:v.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&T(a,{code:v.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")ul.test(e.data)||(a=this._getOrReturnCtx(e,a),T(a,{validation:"email",code:v.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")En||(En=new RegExp(ll,"u")),En.test(e.data)||(a=this._getOrReturnCtx(e,a),T(a,{validation:"emoji",code:v.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")sl.test(e.data)||(a=this._getOrReturnCtx(e,a),T(a,{validation:"uuid",code:v.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")il.test(e.data)||(a=this._getOrReturnCtx(e,a),T(a,{validation:"nanoid",code:v.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")rl.test(e.data)||(a=this._getOrReturnCtx(e,a),T(a,{validation:"cuid",code:v.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")nl.test(e.data)||(a=this._getOrReturnCtx(e,a),T(a,{validation:"cuid2",code:v.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")al.test(e.data)||(a=this._getOrReturnCtx(e,a),T(a,{validation:"ulid",code:v.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{a=this._getOrReturnCtx(e,a),T(a,{validation:"url",code:v.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(a=this._getOrReturnCtx(e,a),T(a,{validation:"regex",code:v.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(a=this._getOrReturnCtx(e,a),T(a,{code:v.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(a=this._getOrReturnCtx(e,a),T(a,{code:v.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(a=this._getOrReturnCtx(e,a),T(a,{code:v.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?vl(s).test(e.data)||(a=this._getOrReturnCtx(e,a),T(a,{code:v.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?_l.test(e.data)||(a=this._getOrReturnCtx(e,a),T(a,{code:v.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?yl(s).test(e.data)||(a=this._getOrReturnCtx(e,a),T(a,{code:v.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?cl.test(e.data)||(a=this._getOrReturnCtx(e,a),T(a,{validation:"duration",code:v.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?wl(e.data,s.version)||(a=this._getOrReturnCtx(e,a),T(a,{validation:"ip",code:v.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?bl(e.data,s.alg)||(a=this._getOrReturnCtx(e,a),T(a,{validation:"jwt",code:v.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?El(e.data,s.version)||(a=this._getOrReturnCtx(e,a),T(a,{validation:"cidr",code:v.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?ml.test(e.data)||(a=this._getOrReturnCtx(e,a),T(a,{validation:"base64",code:v.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?gl.test(e.data)||(a=this._getOrReturnCtx(e,a),T(a,{validation:"base64url",code:v.invalid_string,message:s.message}),n.dirty()):te.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(a=>e.test(a),{validation:r,code:v.invalid_string,...N.errToObj(n)})}_addCheck(e){return new rt({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...N.errToObj(e)})}url(e){return this._addCheck({kind:"url",...N.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...N.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...N.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...N.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...N.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...N.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...N.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...N.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...N.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...N.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...N.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...N.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...N.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...N.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...N.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...N.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...N.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...N.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...N.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...N.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...N.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...N.errToObj(r)})}nonempty(e){return this.min(1,N.errToObj(e))}trim(){return new rt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new rt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new rt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}rt.create=t=>new rt({checks:[],typeName:b.ZodString,coerce:t?.coerce??!1,...X(t)});function Sl(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,a=r>n?r:n,s=Number.parseInt(t.toFixed(a).replace(".","")),i=Number.parseInt(e.toFixed(a).replace(".",""));return s%i/10**a}class Bt extends ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==O.number){const s=this._getOrReturnCtx(e);return T(s,{code:v.invalid_type,expected:O.number,received:s.parsedType}),V}let n;const a=new Te;for(const s of this._def.checks)s.kind==="int"?te.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:v.invalid_type,expected:"integer",received:"float",message:s.message}),a.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:v.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:v.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty()):s.kind==="multipleOf"?Sl(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),T(n,{code:v.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:v.not_finite,message:s.message}),a.dirty()):te.assertNever(s);return{status:a.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,N.toString(r))}gt(e,r){return this.setLimit("min",e,!1,N.toString(r))}lte(e,r){return this.setLimit("max",e,!0,N.toString(r))}lt(e,r){return this.setLimit("max",e,!1,N.toString(r))}setLimit(e,r,n,a){return new Bt({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:N.toString(a)}]})}_addCheck(e){return new Bt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:N.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:N.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&te.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}}Bt.create=t=>new Bt({checks:[],typeName:b.ZodNumber,coerce:t?.coerce||!1,...X(t)});class cr extends ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==O.bigint)return this._getInvalidInput(e);let n;const a=new Te;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:v.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:v.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),T(n,{code:v.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):te.assertNever(s);return{status:a.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return T(r,{code:v.invalid_type,expected:O.bigint,received:r.parsedType}),V}gte(e,r){return this.setLimit("min",e,!0,N.toString(r))}gt(e,r){return this.setLimit("min",e,!1,N.toString(r))}lte(e,r){return this.setLimit("max",e,!0,N.toString(r))}lt(e,r){return this.setLimit("max",e,!1,N.toString(r))}setLimit(e,r,n,a){return new cr({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:N.toString(a)}]})}_addCheck(e){return new cr({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}cr.create=t=>new cr({checks:[],typeName:b.ZodBigInt,coerce:t?.coerce??!1,...X(t)});class Ua extends ee{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==O.boolean){const n=this._getOrReturnCtx(e);return T(n,{code:v.invalid_type,expected:O.boolean,received:n.parsedType}),V}return ke(e.data)}}Ua.create=t=>new Ua({typeName:b.ZodBoolean,coerce:t?.coerce||!1,...X(t)});class Wr extends ee{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==O.date){const s=this._getOrReturnCtx(e);return T(s,{code:v.invalid_type,expected:O.date,received:s.parsedType}),V}if(Number.isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return T(s,{code:v.invalid_date}),V}const n=new Te;let a;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(a=this._getOrReturnCtx(e,a),T(a,{code:v.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(a=this._getOrReturnCtx(e,a),T(a,{code:v.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):te.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Wr({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:N.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:N.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}Wr.create=t=>new Wr({checks:[],coerce:t?.coerce||!1,typeName:b.ZodDate,...X(t)});class Ys extends ee{_parse(e){if(this._getType(e)!==O.symbol){const n=this._getOrReturnCtx(e);return T(n,{code:v.invalid_type,expected:O.symbol,received:n.parsedType}),V}return ke(e.data)}}Ys.create=t=>new Ys({typeName:b.ZodSymbol,...X(t)});class Fa extends ee{_parse(e){if(this._getType(e)!==O.undefined){const n=this._getOrReturnCtx(e);return T(n,{code:v.invalid_type,expected:O.undefined,received:n.parsedType}),V}return ke(e.data)}}Fa.create=t=>new Fa({typeName:b.ZodUndefined,...X(t)});class Xs extends ee{_parse(e){if(this._getType(e)!==O.null){const n=this._getOrReturnCtx(e);return T(n,{code:v.invalid_type,expected:O.null,received:n.parsedType}),V}return ke(e.data)}}Xs.create=t=>new Xs({typeName:b.ZodNull,...X(t)});class ur extends ee{constructor(){super(...arguments),this._any=!0}_parse(e){return ke(e.data)}}ur.create=t=>new ur({typeName:b.ZodAny,...X(t)});class Dt extends ee{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ke(e.data)}}Dt.create=t=>new Dt({typeName:b.ZodUnknown,...X(t)});class pt extends ee{_parse(e){const r=this._getOrReturnCtx(e);return T(r,{code:v.invalid_type,expected:O.never,received:r.parsedType}),V}}pt.create=t=>new pt({typeName:b.ZodNever,...X(t)});class Qs extends ee{_parse(e){if(this._getType(e)!==O.undefined){const n=this._getOrReturnCtx(e);return T(n,{code:v.invalid_type,expected:O.void,received:n.parsedType}),V}return ke(e.data)}}Qs.create=t=>new Qs({typeName:b.ZodVoid,...X(t)});class Ke extends ee{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),a=this._def;if(r.parsedType!==O.array)return T(r,{code:v.invalid_type,expected:O.array,received:r.parsedType}),V;if(a.exactLength!==null){const i=r.data.length>a.exactLength.value,o=r.data.length<a.exactLength.value;(i||o)&&(T(r,{code:i?v.too_big:v.too_small,minimum:o?a.exactLength.value:void 0,maximum:i?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),n.dirty())}if(a.minLength!==null&&r.data.length<a.minLength.value&&(T(r,{code:v.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),n.dirty()),a.maxLength!==null&&r.data.length>a.maxLength.value&&(T(r,{code:v.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,o)=>a.type._parseAsync(new Xe(r,i,r.path,o)))).then(i=>Te.mergeArray(n,i));const s=[...r.data].map((i,o)=>a.type._parseSync(new Xe(r,i,r.path,o)));return Te.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new Ke({...this._def,minLength:{value:e,message:N.toString(r)}})}max(e,r){return new Ke({...this._def,maxLength:{value:e,message:N.toString(r)}})}length(e,r){return new Ke({...this._def,exactLength:{value:e,message:N.toString(r)}})}nonempty(e){return this.min(1,e)}}Ke.create=(t,e)=>new Ke({type:t,minLength:null,maxLength:null,exactLength:null,typeName:b.ZodArray,...X(e)});function Pt(t){if(t instanceof le){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=ht.create(Pt(n))}return new le({...t._def,shape:()=>e})}else return t instanceof Ke?new Ke({...t._def,type:Pt(t.element)}):t instanceof ht?ht.create(Pt(t.unwrap())):t instanceof Gt?Gt.create(Pt(t.unwrap())):t instanceof st?st.create(t.items.map(e=>Pt(e))):t}class le extends ee{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=te.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==O.object){const u=this._getOrReturnCtx(e);return T(u,{code:v.invalid_type,expected:O.object,received:u.parsedType}),V}const{status:n,ctx:a}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof pt&&this._def.unknownKeys==="strip"))for(const u in a.data)i.includes(u)||o.push(u);const c=[];for(const u of i){const l=s[u],d=a.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Xe(a,d,a.path,u)),alwaysSet:u in a.data})}if(this._def.catchall instanceof pt){const u=this._def.unknownKeys;if(u==="passthrough")for(const l of o)c.push({key:{status:"valid",value:l},value:{status:"valid",value:a.data[l]}});else if(u==="strict")o.length>0&&(T(a,{code:v.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const l of o){const d=a.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Xe(a,d,a.path,l)),alwaysSet:l in a.data})}}return a.common.async?Promise.resolve().then(async()=>{const u=[];for(const l of c){const d=await l.key,f=await l.value;u.push({key:d,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>Te.mergeObjectSync(n,u)):Te.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return N.errToObj,new le({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{const a=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:N.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new le({...this._def,unknownKeys:"strip"})}passthrough(){return new le({...this._def,unknownKeys:"passthrough"})}extend(e){return new le({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new le({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:b.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new le({...this._def,catchall:e})}pick(e){const r={};for(const n of te.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new le({...this._def,shape:()=>r})}omit(e){const r={};for(const n of te.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new le({...this._def,shape:()=>r})}deepPartial(){return Pt(this)}partial(e){const r={};for(const n of te.objectKeys(this.shape)){const a=this.shape[n];e&&!e[n]?r[n]=a:r[n]=a.optional()}return new le({...this._def,shape:()=>r})}required(e){const r={};for(const n of te.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof ht;)s=s._def.innerType;r[n]=s}return new le({...this._def,shape:()=>r})}keyof(){return sc(te.objectKeys(this.shape))}}le.create=(t,e)=>new le({shape:()=>t,unknownKeys:"strip",catchall:pt.create(),typeName:b.ZodObject,...X(e)});le.strictCreate=(t,e)=>new le({shape:()=>t,unknownKeys:"strict",catchall:pt.create(),typeName:b.ZodObject,...X(e)});le.lazycreate=(t,e)=>new le({shape:t,unknownKeys:"strip",catchall:pt.create(),typeName:b.ZodObject,...X(e)});class Jr extends ee{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function a(s){for(const o of s)if(o.result.status==="valid")return o.result;for(const o of s)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;const i=s.map(o=>new je(o.ctx.common.issues));return T(r,{code:v.invalid_union,unionErrors:i}),V}if(r.common.async)return Promise.all(n.map(async s=>{const i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(a);{let s;const i=[];for(const c of n){const u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const o=i.map(c=>new je(c));return T(r,{code:v.invalid_union,unionErrors:o}),V}}get options(){return this._def.options}}Jr.create=(t,e)=>new Jr({options:t,typeName:b.ZodUnion,...X(e)});function Ba(t,e){const r=dt(t),n=dt(e);if(t===e)return{valid:!0,data:t};if(r===O.object&&n===O.object){const a=te.objectKeys(e),s=te.objectKeys(t).filter(o=>a.indexOf(o)!==-1),i={...t,...e};for(const o of s){const c=Ba(t[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(r===O.array&&n===O.array){if(t.length!==e.length)return{valid:!1};const a=[];for(let s=0;s<t.length;s++){const i=t[s],o=e[s],c=Ba(i,o);if(!c.valid)return{valid:!1};a.push(c.data)}return{valid:!0,data:a}}else return r===O.date&&n===O.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class Kr extends ee{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),a=(s,i)=>{if(Ws(s)||Ws(i))return V;const o=Ba(s.value,i.value);return o.valid?((Js(s)||Js(i))&&r.dirty(),{status:r.value,value:o.data}):(T(n,{code:v.invalid_intersection_types}),V)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>a(s,i)):a(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Kr.create=(t,e,r)=>new Kr({left:t,right:e,typeName:b.ZodIntersection,...X(r)});class st extends ee{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.array)return T(n,{code:v.invalid_type,expected:O.array,received:n.parsedType}),V;if(n.data.length<this._def.items.length)return T(n,{code:v.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),V;!this._def.rest&&n.data.length>this._def.items.length&&(T(n,{code:v.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...n.data].map((i,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new Xe(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Te.mergeArray(r,i)):Te.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new st({...this._def,rest:e})}}st.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new st({items:t,typeName:b.ZodTuple,rest:null,...X(e)})};class Yr extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.object)return T(n,{code:v.invalid_type,expected:O.object,received:n.parsedType}),V;const a=[],s=this._def.keyType,i=this._def.valueType;for(const o in n.data)a.push({key:s._parse(new Xe(n,o,n.path,o)),value:i._parse(new Xe(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?Te.mergeObjectAsync(r,a):Te.mergeObjectSync(r,a)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ee?new Yr({keyType:e,valueType:r,typeName:b.ZodRecord,...X(n)}):new Yr({keyType:rt.create(),valueType:e,typeName:b.ZodRecord,...X(r)})}}class ei extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.map)return T(n,{code:v.invalid_type,expected:O.map,received:n.parsedType}),V;const a=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([o,c],u)=>({key:a._parse(new Xe(n,o,n.path,[u,"key"])),value:s._parse(new Xe(n,c,n.path,[u,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of i){const u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return V;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(u.value,l.value)}return{status:r.value,value:o}})}else{const o=new Map;for(const c of i){const u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return V;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(u.value,l.value)}return{status:r.value,value:o}}}}ei.create=(t,e,r)=>new ei({valueType:e,keyType:t,typeName:b.ZodMap,...X(r)});class lr extends ee{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.set)return T(n,{code:v.invalid_type,expected:O.set,received:n.parsedType}),V;const a=this._def;a.minSize!==null&&n.data.size<a.minSize.value&&(T(n,{code:v.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),r.dirty()),a.maxSize!==null&&n.data.size>a.maxSize.value&&(T(n,{code:v.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),r.dirty());const s=this._def.valueType;function i(c){const u=new Set;for(const l of c){if(l.status==="aborted")return V;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}const o=[...n.data.values()].map((c,u)=>s._parse(new Xe(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,r){return new lr({...this._def,minSize:{value:e,message:N.toString(r)}})}max(e,r){return new lr({...this._def,maxSize:{value:e,message:N.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}lr.create=(t,e)=>new lr({valueType:t,minSize:null,maxSize:null,typeName:b.ZodSet,...X(e)});class ar extends ee{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==O.function)return T(r,{code:v.invalid_type,expected:O.function,received:r.parsedType}),V;function n(o,c){return Da({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ja(),or].filter(u=>!!u),issueData:{code:v.invalid_arguments,argumentsError:c}})}function a(o,c){return Da({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ja(),or].filter(u=>!!u),issueData:{code:v.invalid_return_type,returnTypeError:c}})}const s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof dr){const o=this;return ke(async function(...c){const u=new je([]),l=await o._def.args.parseAsync(c,s).catch(h=>{throw u.addIssue(n(c,h)),u}),d=await Reflect.apply(i,this,l);return await o._def.returns._def.type.parseAsync(d,s).catch(h=>{throw u.addIssue(a(d,h)),u})})}else{const o=this;return ke(function(...c){const u=o._def.args.safeParse(c,s);if(!u.success)throw new je([n(c,u.error)]);const l=Reflect.apply(i,this,u.data),d=o._def.returns.safeParse(l,s);if(!d.success)throw new je([a(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ar({...this._def,args:st.create(e).rest(Dt.create())})}returns(e){return new ar({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new ar({args:e||st.create([]).rest(Dt.create()),returns:r||Dt.create(),typeName:b.ZodFunction,...X(n)})}}class ti extends ee{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}ti.create=(t,e)=>new ti({getter:t,typeName:b.ZodLazy,...X(e)});class za extends ee{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return T(r,{received:r.data,code:v.invalid_literal,expected:this._def.value}),V}return{status:"valid",value:e.data}}get value(){return this._def.value}}za.create=(t,e)=>new za({value:t,typeName:b.ZodLiteral,...X(e)});function sc(t,e){return new zt({values:t,typeName:b.ZodEnum,...X(e)})}class zt extends ee{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{expected:te.joinValues(n),received:r.parsedType,code:v.invalid_type}),V}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{received:r.data,code:v.invalid_enum_value,options:n}),V}return ke(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return zt.create(e,{...this._def,...r})}exclude(e,r=this._def){return zt.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}zt.create=sc;class ri extends ee{_parse(e){const r=te.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==O.string&&n.parsedType!==O.number){const a=te.objectValues(r);return T(n,{expected:te.joinValues(a),received:n.parsedType,code:v.invalid_type}),V}if(this._cache||(this._cache=new Set(te.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const a=te.objectValues(r);return T(n,{received:n.data,code:v.invalid_enum_value,options:a}),V}return ke(e.data)}get enum(){return this._def.values}}ri.create=(t,e)=>new ri({values:t,typeName:b.ZodNativeEnum,...X(e)});class dr extends ee{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==O.promise&&r.common.async===!1)return T(r,{code:v.invalid_type,expected:O.promise,received:r.parsedType}),V;const n=r.parsedType===O.promise?r.data:Promise.resolve(r.data);return ke(n.then(a=>this._def.type.parseAsync(a,{path:r.path,errorMap:r.common.contextualErrorMap})))}}dr.create=(t,e)=>new dr({type:t,typeName:b.ZodPromise,...X(e)});class qt extends ee{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===b.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),a=this._def.effect||null,s={addIssue:i=>{T(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),a.type==="preprocess"){const i=a.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async o=>{if(r.value==="aborted")return V;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?V:c.status==="dirty"||r.value==="dirty"?er(c.value):c});{if(r.value==="aborted")return V;const o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?V:o.status==="dirty"||r.value==="dirty"?er(o.value):o}}if(a.type==="refinement"){const i=o=>{const c=a.refinement(o,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?V:(o.status==="dirty"&&r.dirty(),i(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?V:(o.status==="dirty"&&r.dirty(),i(o.value).then(()=>({status:r.value,value:o.value}))))}if(a.type==="transform")if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Ft(i))return V;const o=a.transform(i.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Ft(i)?Promise.resolve(a.transform(i.value,s)).then(o=>({status:r.value,value:o})):V);te.assertNever(a)}}qt.create=(t,e,r)=>new qt({schema:t,typeName:b.ZodEffects,effect:e,...X(r)});qt.createWithPreprocess=(t,e,r)=>new qt({schema:e,effect:{type:"preprocess",transform:t},typeName:b.ZodEffects,...X(r)});class ht extends ee{_parse(e){return this._getType(e)===O.undefined?ke(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ht.create=(t,e)=>new ht({innerType:t,typeName:b.ZodOptional,...X(e)});class Gt extends ee{_parse(e){return this._getType(e)===O.null?ke(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Gt.create=(t,e)=>new Gt({innerType:t,typeName:b.ZodNullable,...X(e)});class qa extends ee{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===O.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}qa.create=(t,e)=>new qa({innerType:t,typeName:b.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...X(e)});class Ga extends ee{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},a=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Vr(a)?a.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new je(n.common.issues)},input:n.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new je(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Ga.create=(t,e)=>new Ga({innerType:t,typeName:b.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...X(e)});class ni extends ee{_parse(e){if(this._getType(e)!==O.nan){const n=this._getOrReturnCtx(e);return T(n,{code:v.invalid_type,expected:O.nan,received:n.parsedType}),V}return{status:"valid",value:e.data}}}ni.create=t=>new ni({typeName:b.ZodNaN,...X(t)});class Tl extends ee{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class os extends ee{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?V:s.status==="dirty"?(r.dirty(),er(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const a=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?V:a.status==="dirty"?(r.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:n.path,parent:n})}}static create(e,r){return new os({in:e,out:r,typeName:b.ZodPipeline})}}class Ha extends ee{_parse(e){const r=this._def.innerType._parse(e),n=a=>(Ft(a)&&(a.value=Object.freeze(a.value)),a);return Vr(r)?r.then(a=>n(a)):n(r)}unwrap(){return this._def.innerType}}Ha.create=(t,e)=>new Ha({innerType:t,typeName:b.ZodReadonly,...X(e)});function ai(t,e){const r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function xl(t,e={},r){return t?ur.create().superRefine((n,a)=>{const s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){const o=ai(e,n),c=o.fatal??r??!0;a.addIssue({code:"custom",...o,fatal:c})}});if(!s){const i=ai(e,n),o=i.fatal??r??!0;a.addIssue({code:"custom",...i,fatal:o})}}):ur.create()}var b;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(b||(b={}));const gg=(t,e={message:`Input not instance of ${t.name}`})=>xl(r=>r instanceof t,e),Il=rt.create,_g=Bt.create,yg=Ua.create,vg=Fa.create,si=ur.create;Dt.create;pt.create;const wg=Ke.create,Al=le.create,bg=Jr.create;Kr.create;st.create;const Eg=Yr.create,Sg=ar.create,Tg=za.create,xg=zt.create,Ig=dr.create;ht.create;Gt.create;var Rl=Object.defineProperty,me=(t,e)=>{for(var r in e)Rl(t,r,{get:e[r],enumerable:!0})};function it(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}function cs(t){return it(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function us(t){return it(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function ic(t){return it(t)&&t.source_type==="text"&&"text"in t&&typeof t.text=="string"}function ls(t){return it(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}function oc(t){if(it(t)){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url}};if(t.source_type==="base64"){if(!t.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${t.mime_type};base64,${t.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function cc(t){const e=t.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${t}" - does not match type/subtype format.`);const r=e[0].trim(),n=e[1].trim();if(r===""||n==="")throw new Error(`Invalid mime type: "${t}" - type or subtype is empty.`);const a={};for(const s of t.split(";").slice(1)){const i=s.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${t}".`);const o=i[0].trim(),c=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${t}".`);a[o]=c}return{type:r,subtype:n,parameters:a}}function Xr({dataUrl:t,asTypedArray:e=!1}){const r=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let n;if(r){n=r[1].toLowerCase();const a=e?Uint8Array.from(atob(r[2]),s=>s.charCodeAt(0)):r[2];return{mime_type:n,data:a}}}function uc(t,e){if(t.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(t)}if(t.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(t)}if(t.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(t)}if(t.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(t)}throw new Error(`Unable to convert content block type '${t.type}' to provider-specific format: not recognized.`)}function ds(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}var Sn,ii;function Ol(){return ii||(ii=1,Sn=function(t,e){if(typeof t!="string")throw new TypeError("Expected a string");return e=typeof e>"u"?"_":e,t.replace(/([a-z\d])([A-Z])/g,"$1"+e+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+e+"$2").toLowerCase()}),Sn}var $l=Ol();const kl=wr($l);var Lr={exports:{}},oi;function Cl(){if(oi)return Lr.exports;oi=1;const t=/[\p{Lu}]/u,e=/[\p{Ll}]/u,r=/^[\p{Lu}](?![\p{Lu}])/gu,n=/([\p{Alpha}\p{N}_]|$)/u,a=/[_.\- ]+/,s=new RegExp("^"+a.source),i=new RegExp(a.source+n.source,"gu"),o=new RegExp("\\d+"+n.source,"gu"),c=(f,h,p)=>{let g=!1,m=!1,_=!1;for(let w=0;w<f.length;w++){const y=f[w];g&&t.test(y)?(f=f.slice(0,w)+"-"+f.slice(w),g=!1,_=m,m=!0,w++):m&&_&&e.test(y)?(f=f.slice(0,w-1)+"-"+f.slice(w-1),_=m,m=!1,g=!0):(g=h(y)===y&&p(y)!==y,_=m,m=p(y)===y&&h(y)!==y)}return f},u=(f,h)=>(r.lastIndex=0,f.replace(r,p=>h(p))),l=(f,h)=>(i.lastIndex=0,o.lastIndex=0,f.replace(i,(p,g)=>h(g)).replace(o,p=>h(p))),d=(f,h)=>{if(!(typeof f=="string"||Array.isArray(f)))throw new TypeError("Expected the input to be `string | string[]`");if(h={pascalCase:!1,preserveConsecutiveUppercase:!1,...h},Array.isArray(f)?f=f.map(_=>_.trim()).filter(_=>_.length).join("-"):f=f.trim(),f.length===0)return"";const p=h.locale===!1?_=>_.toLowerCase():_=>_.toLocaleLowerCase(h.locale),g=h.locale===!1?_=>_.toUpperCase():_=>_.toLocaleUpperCase(h.locale);return f.length===1?h.pascalCase?g(f):p(f):(f!==p(f)&&(f=c(f,p,g)),f=f.replace(s,""),h.preserveConsecutiveUppercase?f=u(f,p):f=p(f),h.pascalCase&&(f=g(f.charAt(0))+f.slice(1)),l(f,g))};return Lr.exports=d,Lr.exports.default=d,Lr.exports}var Nl=Cl();const Pl=wr(Nl);function Ll(t,e){return e?.[t]||kl(t)}function Ag(t,e){return e?.[t]||Pl(t)}function Ml(t,e,r){const n={};for(const a in t)Object.hasOwn(t,a)&&(n[e(a,r)]=t[a]);return n}var jl={};me(jl,{Serializable:()=>fr,get_lc_unique_name:()=>fs});function ci(t){return Array.isArray(t)?[...t]:{...t}}function Dl(t,e){const r=ci(t);for(const[n,a]of Object.entries(e)){const[s,...i]=n.split(".").reverse();let o=r;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=ci(o[c]),o=o[c]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[a]})}return r}function fs(t){const e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}var fr=class lc{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,fs(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...r){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof lc||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},r={},n=Object.keys(this.lc_kwargs).reduce((a,s)=>(a[s]=s in this?this[s]:this.lc_kwargs[s],a),{});for(let a=Object.getPrototypeOf(this);a;a=Object.getPrototypeOf(a))Object.assign(e,Reflect.get(a,"lc_aliases",this)),Object.assign(r,Reflect.get(a,"lc_secrets",this)),Object.assign(n,Reflect.get(a,"lc_attributes",this));return Object.keys(r).forEach(a=>{let s=this,i=n;const[o,...c]=a.split(".").reverse();for(const u of c.reverse()){if(!(u in s)||s[u]===void 0)return;(!(u in i)||i[u]===void 0)&&(typeof s[u]=="object"&&s[u]!=null?i[u]={}:Array.isArray(s[u])&&(i[u]=[])),s=s[u],i=i[u]}o in s&&s[o]!==void 0&&(i[o]=i[o]||s[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:Ml(Object.keys(r).length?Dl(n,r):n,Ll,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function D(t,e){return J(t)&&t.type===e}function J(t){return typeof t=="object"&&t!==null}function Ye(t){return Array.isArray(t)}function $(t){return typeof t=="string"}function ze(t){return typeof t=="number"}function hs(t){return t instanceof Uint8Array}function ui(t){try{return JSON.parse(t)}catch{return}}const hr=t=>t();function Ul(t){if(t.type==="char_location"&&$(t.document_title)&&ze(t.start_char_index)&&ze(t.end_char_index)&&$(t.cited_text)){const{document_title:e,start_char_index:r,end_char_index:n,cited_text:a,...s}=t;return{...s,type:"citation",source:"char",title:e??void 0,startIndex:r,endIndex:n,citedText:a}}if(t.type==="page_location"&&$(t.document_title)&&ze(t.start_page_number)&&ze(t.end_page_number)&&$(t.cited_text)){const{document_title:e,start_page_number:r,end_page_number:n,cited_text:a,...s}=t;return{...s,type:"citation",source:"page",title:e??void 0,startIndex:r,endIndex:n,citedText:a}}if(t.type==="content_block_location"&&$(t.document_title)&&ze(t.start_block_index)&&ze(t.end_block_index)&&$(t.cited_text)){const{document_title:e,start_block_index:r,end_block_index:n,cited_text:a,...s}=t;return{...s,type:"citation",source:"block",title:e??void 0,startIndex:r,endIndex:n,citedText:a}}if(t.type==="web_search_result_location"&&$(t.url)&&$(t.title)&&$(t.encrypted_index)&&$(t.cited_text)){const{url:e,title:r,encrypted_index:n,cited_text:a,...s}=t;return{...s,type:"citation",source:"url",url:e,title:r,startIndex:Number(n),endIndex:Number(n),citedText:a}}if(t.type==="search_result_location"&&$(t.source)&&$(t.title)&&ze(t.start_block_index)&&ze(t.end_block_index)&&$(t.cited_text)){const{source:e,title:r,start_block_index:n,end_block_index:a,cited_text:s,...i}=t;return{...i,type:"citation",source:"search",url:e,title:r??void 0,startIndex:n,endIndex:a,citedText:s}}}function dc(t){if(D(t,"document")&&J(t.source)&&"type"in t.source){if(t.source.type==="base64"&&$(t.source.media_type)&&$(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&$(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&$(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&$(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(D(t,"image")&&J(t.source)&&"type"in t.source){if(t.source.type==="base64"&&$(t.source.media_type)&&$(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&$(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&$(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}function Fl(t){function*e(){for(const r of t){const n=dc(r);n?yield n:yield r}}return Array.from(e())}function li(t){function*e(){const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r){if(D(n,"text")&&$(n.text)){const{text:a,citations:s,...i}=n;if(Ye(s)&&s.length){const o=s.reduce((c,u)=>{const l=Ul(u);return l?[...c,l]:c},[]);yield{...i,type:"text",text:a,annotations:o};continue}else{yield{...i,type:"text",text:a};continue}}else if(D(n,"thinking")&&$(n.thinking)){const{thinking:a,signature:s,...i}=n;yield{...i,type:"reasoning",reasoning:a,signature:s};continue}else if(D(n,"redacted_thinking")){yield{type:"non_standard",value:n};continue}else if(D(n,"tool_use")&&$(n.name)&&$(n.id)){yield{type:"tool_call",id:n.id,name:n.name,args:n.input};continue}else if(D(n,"input_json_delta")){if(zl(t)&&t.tool_call_chunks?.length){const a=t.tool_call_chunks[0];yield{type:"tool_call_chunk",id:a.id,name:a.name,args:a.args,index:a.index};continue}}else if(D(n,"server_tool_use")&&$(n.name)&&$(n.id)){const{name:a,id:s}=n;if(a==="web_search"){const i=hr(()=>{if(typeof n.input=="string")return n.input;if(J(n.input)&&$(n.input.query))return n.input.query;if($(n.partial_json)){const o=ui(n.partial_json);if(o?.query)return o.query}return""});yield{id:s,type:"server_tool_call",name:"web_search",args:{query:i}};continue}else if(n.name==="code_execution"){const i=hr(()=>{if(typeof n.input=="string")return n.input;if(J(n.input)&&$(n.input.code))return n.input.code;if($(n.partial_json)){const o=ui(n.partial_json);if(o?.code)return o.code}return""});yield{id:s,type:"server_tool_call",name:"code_execution",args:{code:i}};continue}}else if(D(n,"web_search_tool_result")&&$(n.tool_use_id)&&Ye(n.content)){const{content:a,tool_use_id:s}=n,i=a.reduce((o,c)=>D(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:s,status:"success",output:{urls:i}};continue}else if(D(n,"code_execution_tool_result")&&$(n.tool_use_id)&&J(n.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(D(n,"mcp_tool_use")){yield{id:n.id,type:"server_tool_call",name:"mcp_tool_use",args:n.input};continue}else if(D(n,"mcp_tool_result")&&$(n.tool_use_id)&&J(n.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(D(n,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:n.input};continue}else if(D(n,"search_result")){yield{id:n.id,type:"non_standard",value:n};continue}else if(D(n,"tool_result")){yield{id:n.id,type:"non_standard",value:n};continue}else{const a=dc(n);if(a){yield a;continue}}yield{type:"non_standard",value:n}}}return Array.from(e())}const Bl={translateContent:li,translateContentChunk:li};function zl(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}function ql(t){return cs(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:us(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:ls(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}function Gl(t){return t.map(ql)}function Hl(t){return!!(D(t,"image_url")&&J(t.image_url)||D(t,"input_audio")&&J(t.input_audio)||D(t,"file")&&J(t.file))}function Zl(t){if(D(t,"image_url")&&J(t.image_url)&&$(t.image_url.url)){const e=Xr({dataUrl:t.image_url.url});return e?{type:"image",mimeType:e.mime_type,data:e.data}:{type:"image",url:t.image_url.url}}else{if(D(t,"input_audio")&&J(t.input_audio)&&$(t.input_audio.data)&&$(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(D(t,"file")&&J(t.file)&&$(t.file.data)){const e=Xr({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if($(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}function Vl(t){const e=[];typeof t.content=="string"?e.push({type:"text",text:t.content}):e.push(...ps(t.content));for(const r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}function Wl(t){const e=[];typeof t.content=="string"?e.push({type:"text",text:t.content}):e.push(...ps(t.content));for(const r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}function ps(t){const e=[];for(const r of t)Hl(r)?e.push(Zl(r)):e.push(r);return e}function Jl(t){if(t.type==="url_citation"){const{url:e,title:r,start_index:n,end_index:a}=t;return{type:"citation",url:e,title:r,startIndex:n,endIndex:a}}if(t.type==="file_citation"){const{file_id:e,filename:r,index:n}=t;return{type:"citation",title:r,startIndex:n,endIndex:n,fileId:e}}return t}function fc(t){function*e(){J(t.additional_kwargs?.reasoning)&&Ye(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((a,s)=>J(s)&&$(s.text)?`${a}${s.text}`:a,"")});const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r)if(D(n,"text")){const{text:a,annotations:s,...i}=n;Array.isArray(s)?yield{...i,type:"text",text:String(a),annotations:s.map(Jl)}:yield{...i,type:"text",text:String(a)}}for(const n of t.tool_calls??[])yield{type:"tool_call",id:n.id,name:n.name,args:n.args};if(J(t.additional_kwargs)&&Ye(t.additional_kwargs.tool_outputs))for(const n of t.additional_kwargs.tool_outputs){if(D(n,"web_search_call")){yield{id:n.id,type:"server_tool_call",name:"web_search",args:{query:n.query}};continue}else if(D(n,"file_search_call")){yield{id:n.id,type:"server_tool_call",name:"file_search",args:{query:n.query}};continue}else if(D(n,"computer_call")){yield{type:"non_standard",value:n};continue}else if(D(n,"code_interpreter_call")){if($(n.code)&&(yield{id:n.id,type:"server_tool_call",name:"code_interpreter",args:{code:n.code}}),Ye(n.outputs)){const a=hr(()=>{if(n.status!=="in_progress"){if(n.status==="completed")return 0;if(n.status==="incomplete")return 127;if(n.status!=="interpreting"&&n.status==="failed")return 1}});for(const s of n.outputs)if(D(s,"logs")){yield{type:"server_tool_call_result",toolCallId:n.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:a??0,stderr:[0,void 0].includes(a)?void 0:String(s.logs),stdout:[0,void 0].includes(a)?String(s.logs):void 0}};continue}}continue}else if(D(n,"mcp_call")){yield{id:n.id,type:"server_tool_call",name:"mcp_call",args:n.input};continue}else if(D(n,"mcp_list_tools")){yield{id:n.id,type:"server_tool_call",name:"mcp_list_tools",args:n.input};continue}else if(D(n,"mcp_approval_request")){yield{type:"non_standard",value:n};continue}else if(D(n,"image_generation_call")){yield{type:"non_standard",value:n};continue}J(n)&&(yield{type:"non_standard",value:n})}}return Array.from(e())}function Kl(t){function*e(){yield*fc(t);for(const r of t.tool_call_chunks??[])yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args}}return Array.from(e())}const Yl={translateContent:t=>typeof t.content=="string"?Vl(t):fc(t),translateContentChunk:t=>typeof t.content=="string"?Wl(t):Kl(t)};function Xl(t,e="pretty"){return e==="pretty"?Ql(t):JSON.stringify(t)}function Ql(t){const e=[],r=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,n=Math.floor((80-r.length)/2),a="=".repeat(n),s=r.length%2===0?a:`${a}=`;if(e.push(`${a}${r}${s}`),t.type==="ai"){const i=t;if(i.tool_calls&&i.tool_calls.length>0){e.push("Tool Calls:");for(const o of i.tool_calls){e.push(` ${o.name} (${o.id})`),e.push(` Call ID: ${o.id}`),e.push(" Args:");for(const[c,u]of Object.entries(o.args))e.push(` ${c}: ${u}`)}}}if(t.type==="tool"){const i=t;i.name&&e.push(`Name: ${i.name}`)}return typeof t.content=="string"&&t.content.trim()&&(e.length>1&&e.push(""),e.push(t.content)),e.join(`
2
+ `)}const Tn=Symbol.for("langchain.message");function gt(t,e){return typeof t=="string"?t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.some(r=>it(r))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e]:Array.isArray(e)?Zt(t,e)??[...t,...e]:e===""?t:Array.isArray(t)&&t.some(r=>it(r))?[...t,{type:"file",source_type:"text",text:e}]:[...t,{type:"text",text:e}]}function ms(t,e){return t==="error"||e==="error"?"error":"success"}function ed(t,e){function r(n,a){if(typeof n!="object"||n===null||n===void 0)return n;if(a>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(i=>r(i,a+1));const s={};for(const i of Object.keys(n))s[i]=r(n[i],a+1);return s}return JSON.stringify(r(t,0),null,2)}var et=class extends fr{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[Tn]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(t){const e=typeof t=="string"||Array.isArray(t)?{content:t}:t;e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),this.name=e.name,e.content===void 0&&e.contentBlocks!==void 0?(this.content=e.contentBlocks,this.response_metadata={output_version:"v1",...e.response_metadata}):e.content!==void 0?(this.content=e.content??[],this.response_metadata=e.response_metadata):(this.content=[],this.response_metadata=e.response_metadata),this.additional_kwargs=e.additional_kwargs,this.id=e.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(t=>typeof t=="string"?t:t.type==="text"?t.text:"").join(""):""}get contentBlocks(){const t=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[Gl,ps,Fl].reduce((n,a)=>a(n),t)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(t){return typeof t=="object"&&t!==null&&Tn in t&&t[Tn]===!0&&ds(t)}_updateId(t){this.id=t,this.lc_kwargs.id=t}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](t){if(t===null)return this;const e=ed(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return Xl(this,t)}};function hc(t){return Array.isArray(t)&&t.every(e=>typeof e.index=="number")}function ve(t={},e={}){const r={...t};for(const[n,a]of Object.entries(e))if(r[n]==null)r[n]=a;else{if(a==null)continue;if(typeof r[n]!=typeof a||Array.isArray(r[n])!==Array.isArray(a))throw new Error(`field[${n}] already exists in the message chunk, but with a different type.`);if(typeof r[n]=="string"){if(n==="type")continue;["id","name","output_version","model_provider"].includes(n)?r[n]=a:r[n]+=a}else if(typeof r[n]=="object"&&!Array.isArray(r[n]))r[n]=ve(r[n],a);else if(Array.isArray(r[n]))r[n]=Zt(r[n],a);else{if(r[n]===a)continue;console.warn(`field[${n}] already exists in this message chunk and value has unsupported type.`)}}return r}function Zt(t,e){if(!(t===void 0&&e===void 0)){if(t===void 0||e===void 0)return t||e;{const r=[...t];for(const n of e)if(typeof n=="object"&&n!==null&&"index"in n&&typeof n.index=="number"){const a=r.findIndex(s=>{const i=typeof s=="object",o="index"in s&&s.index===n.index,c="id"in s&&"id"in n&&s?.id===n?.id,u=!("id"in s)||!s?.id||!("id"in n)||!n?.id;return i&&o&&(c||u)});a!==-1&&typeof r[a]=="object"&&r[a]!==null?r[a]=ve(r[a],n):r.push(n)}else{if(typeof n=="object"&&n!==null&&"text"in n&&n.text==="")continue;r.push(n)}return r}}}function gs(t,e){if(!t&&!e)throw new Error("Cannot merge two undefined objects.");if(!t||!e)return t||e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types.
5
3
  Left ${typeof t}
6
- Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return Vt(t,e);if(typeof t=="object"&&typeof e=="object")return ve(t,e);if(t===e)return t;throw new Error(`Can not merge objects of different types.
4
+ Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return Zt(t,e);if(typeof t=="object"&&typeof e=="object")return ve(t,e);if(t===e)return t;throw new Error(`Can not merge objects of different types.
7
5
  Left ${t}
8
- Right ${e}`)}var _t=class extends tt{static isInstance(t){return super.isInstance(t)&&"concat"in t&&typeof t.concat=="function"}};function _s(t){return typeof t.role=="string"}function fn(t){return typeof t?._getType=="function"}function vs(t){return fn(t)&&typeof t.concat=="function"}function ws(t,e){return ve(t??{},e??{})}function gc(t,e){const r={};return(t?.audio!==void 0||e?.audio!==void 0)&&(r.audio=(t?.audio??0)+(e?.audio??0)),(t?.image!==void 0||e?.image!==void 0)&&(r.image=(t?.image??0)+(e?.image??0)),(t?.video!==void 0||e?.video!==void 0)&&(r.video=(t?.video??0)+(e?.video??0)),(t?.document!==void 0||e?.document!==void 0)&&(r.document=(t?.document??0)+(e?.document??0)),(t?.text!==void 0||e?.text!==void 0)&&(r.text=(t?.text??0)+(e?.text??0)),r}function sd(t,e){const r={...gc(t,e)};return(t?.cache_read!==void 0||e?.cache_read!==void 0)&&(r.cache_read=(t?.cache_read??0)+(e?.cache_read??0)),(t?.cache_creation!==void 0||e?.cache_creation!==void 0)&&(r.cache_creation=(t?.cache_creation??0)+(e?.cache_creation??0)),r}function id(t,e){const r={...gc(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(r.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),r}function bs(t,e){return{input_tokens:(t?.input_tokens??0)+(e?.input_tokens??0),output_tokens:(t?.output_tokens??0)+(e?.output_tokens??0),total_tokens:(t?.total_tokens??0)+(e?.total_tokens??0),input_token_details:sd(t?.input_token_details,e?.input_token_details),output_token_details:id(t?.output_token_details,e?.output_token_details)}}var od={};me(od,{ToolMessage:()=>Rt,ToolMessageChunk:()=>Er,defaultToolCallParser:()=>hn,isDirectToolOutput:()=>Es,isToolMessage:()=>Ss,isToolMessageChunk:()=>Ts});function Es(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}var Rt=class extends tt{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}lc_direct_tool_output=!0;type="tool";status;tool_call_id;metadata;artifact;constructor(t,e,r){const n=typeof t=="string"||Array.isArray(t)?{content:t,name:r,tool_call_id:e}:t;super(n),this.tool_call_id=n.tool_call_id,this.artifact=n.artifact,this.status=n.status,this.metadata=n.metadata}static isInstance(t){return super.isInstance(t)&&t.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},Er=class extends _t{type="tool";tool_call_id;status;artifact;constructor(t){super(t),this.tool_call_id=t.tool_call_id,this.artifact=t.artifact,this.status=t.status}static lc_name(){return"ToolMessageChunk"}concat(t){const e=this.constructor;return new e({content:yt(this.content,t.content),additional_kwargs:ve(this.additional_kwargs,t.additional_kwargs),response_metadata:ve(this.response_metadata,t.response_metadata),artifact:ys(this.artifact,t.artifact),tool_call_id:this.tool_call_id,id:this.id??t.id,status:gs(this.status,t.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function hn(t){const e=[],r=[];for(const n of t)if(n.function){const a=n.function.name;try{const s=JSON.parse(n.function.arguments);e.push({name:a||"",args:s||{},id:n.id})}catch{r.push({name:a,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}function Ss(t){return typeof t=="object"&&t!==null&&"getType"in t&&typeof t.getType=="function"&&t.getType()==="tool"}function Ts(t){return t._getType()==="tool"}function Cg(t,e=yc){t=t.trim();const r=t.indexOf("```");if(r===-1)return e(t);let n=t.substring(r+3);n.startsWith(`json
6
+ Right ${e}`)}var _t=class extends et{static isInstance(t){return super.isInstance(t)&&"concat"in t&&typeof t.concat=="function"}};function _s(t){return typeof t.role=="string"}function dn(t){return typeof t?._getType=="function"}function ys(t){return dn(t)&&typeof t.concat=="function"}function vs(t,e){return ve(t??{},e??{})}function pc(t,e){const r={};return(t?.audio!==void 0||e?.audio!==void 0)&&(r.audio=(t?.audio??0)+(e?.audio??0)),(t?.image!==void 0||e?.image!==void 0)&&(r.image=(t?.image??0)+(e?.image??0)),(t?.video!==void 0||e?.video!==void 0)&&(r.video=(t?.video??0)+(e?.video??0)),(t?.document!==void 0||e?.document!==void 0)&&(r.document=(t?.document??0)+(e?.document??0)),(t?.text!==void 0||e?.text!==void 0)&&(r.text=(t?.text??0)+(e?.text??0)),r}function td(t,e){const r={...pc(t,e)};return(t?.cache_read!==void 0||e?.cache_read!==void 0)&&(r.cache_read=(t?.cache_read??0)+(e?.cache_read??0)),(t?.cache_creation!==void 0||e?.cache_creation!==void 0)&&(r.cache_creation=(t?.cache_creation??0)+(e?.cache_creation??0)),r}function rd(t,e){const r={...pc(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(r.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),r}function ws(t,e){return{input_tokens:(t?.input_tokens??0)+(e?.input_tokens??0),output_tokens:(t?.output_tokens??0)+(e?.output_tokens??0),total_tokens:(t?.total_tokens??0)+(e?.total_tokens??0),input_token_details:td(t?.input_token_details,e?.input_token_details),output_token_details:rd(t?.output_token_details,e?.output_token_details)}}var nd={};me(nd,{ToolMessage:()=>Rt,ToolMessageChunk:()=>br,defaultToolCallParser:()=>fn,isDirectToolOutput:()=>bs,isToolMessage:()=>Es,isToolMessageChunk:()=>Ss});function bs(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}var Rt=class extends et{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}lc_direct_tool_output=!0;type="tool";status;tool_call_id;metadata;artifact;constructor(t,e,r){const n=typeof t=="string"||Array.isArray(t)?{content:t,name:r,tool_call_id:e}:t;super(n),this.tool_call_id=n.tool_call_id,this.artifact=n.artifact,this.status=n.status,this.metadata=n.metadata}static isInstance(t){return super.isInstance(t)&&t.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},br=class extends _t{type="tool";tool_call_id;status;artifact;constructor(t){super(t),this.tool_call_id=t.tool_call_id,this.artifact=t.artifact,this.status=t.status}static lc_name(){return"ToolMessageChunk"}concat(t){const e=this.constructor;return new e({content:gt(this.content,t.content),additional_kwargs:ve(this.additional_kwargs,t.additional_kwargs),response_metadata:ve(this.response_metadata,t.response_metadata),artifact:gs(this.artifact,t.artifact),tool_call_id:this.tool_call_id,id:this.id??t.id,status:ms(this.status,t.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function fn(t){const e=[],r=[];for(const n of t)if(n.function){const a=n.function.name;try{const s=JSON.parse(n.function.arguments);e.push({name:a||"",args:s||{},id:n.id})}catch{r.push({name:a,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}function Es(t){return typeof t=="object"&&t!==null&&"getType"in t&&typeof t.getType=="function"&&t.getType()==="tool"}function Ss(t){return t._getType()==="tool"}function Rg(t,e=mc){t=t.trim();const r=t.indexOf("```");if(r===-1)return e(t);let n=t.substring(r+3);n.startsWith(`json
9
7
  `)?n=n.substring(5):n.startsWith("json")?n=n.substring(4):n.startsWith(`
10
- `)&&(n=n.substring(1));const a=n.indexOf("```");let s=n;return a!==-1&&(s=n.substring(0,a)),e(s.trim())}function yc(t){if(typeof t>"u")return null;try{return JSON.parse(t)}catch{}let e="";const r=[];let n=!1,a=!1;for(let s of t){if(n)s==='"'&&!a?n=!1:s===`
11
- `&&!a?s="\\n":s==="\\"?a=!a:a=!1;else if(s==='"')n=!0,a=!1;else if(s==="{")r.push("}");else if(s==="[")r.push("]");else if(s==="}"||s==="]")if(r&&r[r.length-1]===s)r.pop();else return null;e+=s}n&&(e+='"');for(let s=r.length-1;s>=0;s-=1)e+=r[s];try{return JSON.parse(e)}catch{return null}}function xs(t){switch(t){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function cd(t){if(W(t.document)&&W(t.document.source)){const e=W(t.document)&&k(t.document.format)?t.document.format:"",r=xs(e);if(W(t.document.source)){if(W(t.document.source.s3Location)&&k(t.document.source.s3Location.uri))return{type:"file",mimeType:r,fileId:t.document.source.s3Location.uri};if(ps(t.document.source.bytes))return{type:"file",mimeType:r,data:t.document.source.bytes};if(k(t.document.source.text))return{type:"file",mimeType:r,data:Buffer.from(t.document.source.text).toString("base64")};if(Xe(t.document.source.content)){const n=t.document.source.content.reduce((a,s)=>W(s)&&k(s.text)?a+s.text:a,"");return{type:"file",mimeType:r,data:n}}}}return{type:"non_standard",value:t}}function ud(t){if(D(t,"image")&&W(t.image)){const e=W(t.image)&&k(t.image.format)?t.image.format:"",r=xs(e);if(W(t.image.source)){if(W(t.image.source.s3Location)&&k(t.image.source.s3Location.uri))return{type:"image",mimeType:r,fileId:t.image.source.s3Location.uri};if(ps(t.image.source.bytes))return{type:"image",mimeType:r,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}function ld(t){if(D(t,"video")&&W(t.video)){const e=W(t.video)&&k(t.video.format)?t.video.format:"",r=xs(e);if(W(t.video.source)){if(W(t.video.source.s3Location)&&k(t.video.source.s3Location.uri))return{type:"video",mimeType:r,fileId:t.video.source.s3Location.uri};if(ps(t.video.source.bytes))return{type:"video",mimeType:r,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}function hi(t){function*e(){const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r){if(D(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(D(n,"citations_content")&&W(n.citationsContent)){const a=Xe(n.citationsContent.content)?n.citationsContent.content.reduce((i,o)=>W(o)&&k(o.text)?i+o.text:i,""):"",s=Xe(n.citationsContent.citations)?n.citationsContent.citations.reduce((i,o)=>{if(W(o)){const c=Xe(o.sourceContent)?o.sourceContent.reduce((l,d)=>W(d)&&k(d.text)?l+d.text:l,""):"",u=pr(()=>{if(W(o.location)){const l=o.location.documentChar||o.location.documentPage||o.location.documentChunk;if(W(l))return{source:qe(l.documentIndex)?l.documentIndex.toString():void 0,startIndex:qe(l.start)?l.start:void 0,endIndex:qe(l.end)?l.end:void 0}}return{}});i.push({type:"citation",citedText:c,...u})}return i},[]):[];yield{type:"text",text:a,annotations:s};continue}else if(D(n,"document")&&W(n.document)){yield cd(n);continue}else if(D(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(D(n,"image")&&W(n.image)){yield ud(n);continue}else if(D(n,"reasoning_content")&&k(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(D(n,"text")&&k(n.text)){yield{type:"text",text:n.text};continue}else if(D(n,"tool_result")){yield{type:"non_standard",value:n};continue}else{if(D(n,"tool_call"))continue;if(D(n,"video")&&W(n.video)){yield ld(n);continue}}yield{type:"non_standard",value:n}}}return Array.from(e())}const dd={translateContent:hi,translateContentChunk:hi};function pi(t){function*e(){const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r){if(D(n,"text")&&k(n.text)){yield{type:"text",text:n.text};continue}else if(D(n,"inlineData")&&W(n.inlineData)&&k(n.inlineData.mimeType)&&k(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(D(n,"functionCall")&&W(n.functionCall)&&k(n.functionCall.name)&&W(n.functionCall.args)){yield{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(D(n,"functionResponse")){yield{type:"non_standard",value:n};continue}else if(D(n,"fileData")&&W(n.fileData)&&k(n.fileData.mimeType)&&k(n.fileData.fileUri)){yield{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(D(n,"executableCode")){yield{type:"non_standard",value:n};continue}else if(D(n,"codeExecutionResult")){yield{type:"non_standard",value:n};continue}yield{type:"non_standard",value:n}}}return Array.from(e())}const fd={translateContent:pi,translateContentChunk:pi};function mi(t){function*e(){const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r){if(D(n,"reasoning")&&k(n.reasoning)){const a=pr(()=>{const s=r.indexOf(n);if(Xe(t.additional_kwargs?.signatures)&&s>=0)return t.additional_kwargs.signatures.at(s)});k(a)?yield{type:"reasoning",reasoning:n.reasoning,signature:a}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(D(n,"text")&&k(n.text)){yield{type:"text",text:n.text};continue}else if(D(n,"image_url")){if(k(n.image_url))if(n.image_url.startsWith("data:")){const a=/^data:([^;]+);base64,(.+)$/,s=n.image_url.match(a);s?yield{type:"image",data:s[2],mimeType:s[1]}:yield{type:"image",url:n.image_url}}else yield{type:"image",url:n.image_url};continue}else if(D(n,"media")&&k(n.mimeType)&&k(n.data)){yield{type:"file",mimeType:n.mimeType,data:n.data};continue}yield{type:"non_standard",value:n}}}return Array.from(e())}const hd={translateContent:mi,translateContentChunk:mi};globalThis.lc_block_translators_registry??=new Map([["anthropic",Hl],["bedrock-converse",dd],["google-genai",fd],["google-vertexai",hd],["openai",td]]);function _c(t){return globalThis.lc_block_translators_registry.get(t)}var It=class extends tt{type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(t){let e;if(typeof t=="string"||Array.isArray(t))e={content:t,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{e=t;const r=e.additional_kwargs?.tool_calls,n=e.tool_calls;r!=null&&r.length>0&&(n===void 0||n.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
8
+ `)&&(n=n.substring(1));const a=n.indexOf("```");let s=n;return a!==-1&&(s=n.substring(0,a)),e(s.trim())}function mc(t){if(typeof t>"u")return null;try{return JSON.parse(t)}catch{}let e="";const r=[];let n=!1,a=!1;for(let s of t){if(n)s==='"'&&!a?n=!1:s===`
9
+ `&&!a?s="\\n":s==="\\"?a=!a:a=!1;else if(s==='"')n=!0,a=!1;else if(s==="{")r.push("}");else if(s==="[")r.push("]");else if(s==="}"||s==="]")if(r&&r[r.length-1]===s)r.pop();else return null;e+=s}n&&(e+='"');for(let s=r.length-1;s>=0;s-=1)e+=r[s];try{return JSON.parse(e)}catch{return null}}function Ts(t){switch(t){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function ad(t){if(J(t.document)&&J(t.document.source)){const e=J(t.document)&&$(t.document.format)?t.document.format:"",r=Ts(e);if(J(t.document.source)){if(J(t.document.source.s3Location)&&$(t.document.source.s3Location.uri))return{type:"file",mimeType:r,fileId:t.document.source.s3Location.uri};if(hs(t.document.source.bytes))return{type:"file",mimeType:r,data:t.document.source.bytes};if($(t.document.source.text))return{type:"file",mimeType:r,data:Buffer.from(t.document.source.text).toString("base64")};if(Ye(t.document.source.content)){const n=t.document.source.content.reduce((a,s)=>J(s)&&$(s.text)?a+s.text:a,"");return{type:"file",mimeType:r,data:n}}}}return{type:"non_standard",value:t}}function sd(t){if(D(t,"image")&&J(t.image)){const e=J(t.image)&&$(t.image.format)?t.image.format:"",r=Ts(e);if(J(t.image.source)){if(J(t.image.source.s3Location)&&$(t.image.source.s3Location.uri))return{type:"image",mimeType:r,fileId:t.image.source.s3Location.uri};if(hs(t.image.source.bytes))return{type:"image",mimeType:r,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}function id(t){if(D(t,"video")&&J(t.video)){const e=J(t.video)&&$(t.video.format)?t.video.format:"",r=Ts(e);if(J(t.video.source)){if(J(t.video.source.s3Location)&&$(t.video.source.s3Location.uri))return{type:"video",mimeType:r,fileId:t.video.source.s3Location.uri};if(hs(t.video.source.bytes))return{type:"video",mimeType:r,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}function di(t){function*e(){const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r){if(D(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(D(n,"citations_content")&&J(n.citationsContent)){const a=Ye(n.citationsContent.content)?n.citationsContent.content.reduce((i,o)=>J(o)&&$(o.text)?i+o.text:i,""):"",s=Ye(n.citationsContent.citations)?n.citationsContent.citations.reduce((i,o)=>{if(J(o)){const c=Ye(o.sourceContent)?o.sourceContent.reduce((l,d)=>J(d)&&$(d.text)?l+d.text:l,""):"",u=hr(()=>{if(J(o.location)){const l=o.location.documentChar||o.location.documentPage||o.location.documentChunk;if(J(l))return{source:ze(l.documentIndex)?l.documentIndex.toString():void 0,startIndex:ze(l.start)?l.start:void 0,endIndex:ze(l.end)?l.end:void 0}}return{}});i.push({type:"citation",citedText:c,...u})}return i},[]):[];yield{type:"text",text:a,annotations:s};continue}else if(D(n,"document")&&J(n.document)){yield ad(n);continue}else if(D(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(D(n,"image")&&J(n.image)){yield sd(n);continue}else if(D(n,"reasoning_content")&&$(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(D(n,"text")&&$(n.text)){yield{type:"text",text:n.text};continue}else if(D(n,"tool_result")){yield{type:"non_standard",value:n};continue}else{if(D(n,"tool_call"))continue;if(D(n,"video")&&J(n.video)){yield id(n);continue}}yield{type:"non_standard",value:n}}}return Array.from(e())}const od={translateContent:di,translateContentChunk:di};function fi(t){function*e(){const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r){if(D(n,"text")&&$(n.text)){yield{type:"text",text:n.text};continue}else if(D(n,"inlineData")&&J(n.inlineData)&&$(n.inlineData.mimeType)&&$(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(D(n,"functionCall")&&J(n.functionCall)&&$(n.functionCall.name)&&J(n.functionCall.args)){yield{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(D(n,"functionResponse")){yield{type:"non_standard",value:n};continue}else if(D(n,"fileData")&&J(n.fileData)&&$(n.fileData.mimeType)&&$(n.fileData.fileUri)){yield{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(D(n,"executableCode")){yield{type:"non_standard",value:n};continue}else if(D(n,"codeExecutionResult")){yield{type:"non_standard",value:n};continue}yield{type:"non_standard",value:n}}}return Array.from(e())}const cd={translateContent:fi,translateContentChunk:fi};function hi(t){function*e(){const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r){if(D(n,"reasoning")&&$(n.reasoning)){const a=hr(()=>{const s=r.indexOf(n);if(Ye(t.additional_kwargs?.signatures)&&s>=0)return t.additional_kwargs.signatures.at(s)});$(a)?yield{type:"reasoning",reasoning:n.reasoning,signature:a}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(D(n,"text")&&$(n.text)){yield{type:"text",text:n.text};continue}else if(D(n,"image_url")){if($(n.image_url))if(n.image_url.startsWith("data:")){const a=/^data:([^;]+);base64,(.+)$/,s=n.image_url.match(a);s?yield{type:"image",data:s[2],mimeType:s[1]}:yield{type:"image",url:n.image_url}}else yield{type:"image",url:n.image_url};continue}else if(D(n,"media")&&$(n.mimeType)&&$(n.data)){yield{type:"file",mimeType:n.mimeType,data:n.data};continue}yield{type:"non_standard",value:n}}}return Array.from(e())}const ud={translateContent:hi,translateContentChunk:hi};globalThis.lc_block_translators_registry??=new Map([["anthropic",Bl],["bedrock-converse",od],["google-genai",cd],["google-vertexai",ud],["openai",Yl]]);function gc(t){return globalThis.lc_block_translators_registry.get(t)}var xt=class extends et{type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(t){let e;if(typeof t=="string"||Array.isArray(t))e={content:t,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{e=t;const r=e.additional_kwargs?.tool_calls,n=e.tool_calls;r!=null&&r.length>0&&(n===void 0||n.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
12
10
 
13
- Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(r!=null&&n===void 0){const[a,s]=hn(r);e.tool_calls=a??[],e.invalid_tool_calls=s??[]}else e.tool_calls=e.tool_calls??[],e.invalid_tool_calls=e.invalid_tool_calls??[]}catch{e.tool_calls=[],e.invalid_tool_calls=[]}if(e.response_metadata!==void 0&&"output_version"in e.response_metadata&&e.response_metadata.output_version==="v1"&&(e.contentBlocks=e.content,e.content=void 0),e.contentBlocks!==void 0){e.contentBlocks.push(...e.tool_calls.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args})));const a=e.contentBlocks.filter(s=>s.type==="tool_call").filter(s=>!e.tool_calls?.some(i=>i.id===s.id&&i.name===s.name));a.length>0&&(e.tool_calls=a.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args})))}}super(e),typeof e!="string"&&(this.tool_calls=e.tool_calls??this.tool_calls,this.invalid_tool_calls=e.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=e.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const e=_c(this.response_metadata.model_provider);if(e)return e.translateContent(this)}const t=super.contentBlocks;if(this.tool_calls){const e=this.tool_calls.filter(r=>!t.some(n=>n.id===r.id&&n.name===r.name));t.push(...e.map(r=>({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})))}return t}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}};function vc(t){return t._getType()==="ai"}function wc(t){return t._getType()==="ai"}var kt=class extends _t{type="ai";tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(t){let e;if(typeof t=="string"||Array.isArray(t))e={content:t,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(t.tool_call_chunks===void 0||t.tool_call_chunks.length===0)e={...t,tool_calls:t.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:t.usage_metadata!==void 0?t.usage_metadata:void 0};else{const n=(t.tool_call_chunks??[]).reduce((i,o)=>{const c=i.findIndex(([u])=>"id"in o&&o.id&&"index"in o&&o.index!==void 0?o.id===u.id&&o.index===u.index:"id"in o&&o.id?o.id===u.id:"index"in o&&o.index!==void 0?o.index===u.index:!1);return c!==-1?i[c].push(o):i.push([o]),i},[]),a=[],s=[];for(const i of n){let o=null;const c=i[0]?.name??"",u=i.map(f=>f.args||"").join(""),l=u.length?u:"{}",d=i[0]?.id;try{if(o=yc(l),!d||o===null||typeof o!="object"||Array.isArray(o))throw new Error("Malformed tool call chunk args.");a.push({name:c,args:o,id:d,type:"tool_call"})}catch{s.push({name:c,args:l,id:d,error:"Malformed args.",type:"invalid_tool_call"})}}e={...t,tool_calls:a,invalid_tool_calls:s,usage_metadata:t.usage_metadata!==void 0?t.usage_metadata:void 0}}super(e),this.tool_call_chunks=e.tool_call_chunks??this.tool_call_chunks,this.tool_calls=e.tool_calls??this.tool_calls,this.invalid_tool_calls=e.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=e.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const e=_c(this.response_metadata.model_provider);if(e)return e.translateContent(this)}const t=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){const e=this.content.filter(r=>r.type==="tool_call").map(r=>r.id);for(const r of this.tool_calls)r.id&&!e.includes(r.id)&&t.push({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})}return t}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(t){const e={content:yt(this.content,t.content),additional_kwargs:ve(this.additional_kwargs,t.additional_kwargs),response_metadata:ws(this.response_metadata,t.response_metadata),tool_call_chunks:[],id:this.id??t.id};if(this.tool_call_chunks!==void 0||t.tool_call_chunks!==void 0){const n=Vt(this.tool_call_chunks,t.tool_call_chunks);n!==void 0&&n.length>0&&(e.tool_call_chunks=n)}(this.usage_metadata!==void 0||t.usage_metadata!==void 0)&&(e.usage_metadata=bs(this.usage_metadata,t.usage_metadata));const r=this.constructor;return new r(e)}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}},Jt=class bc extends tt{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return bc}constructor(e,r){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:r}),super(e),this.role=e.role}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},Sr=class extends _t{static lc_name(){return"ChatMessageChunk"}type="generic";role;constructor(t,e){(typeof t=="string"||Array.isArray(t))&&(t={content:t,role:e}),super(t),this.role=t.role}concat(t){const e=this.constructor;return new e({content:yt(this.content,t.content),additional_kwargs:ve(this.additional_kwargs,t.additional_kwargs),response_metadata:ve(this.response_metadata,t.response_metadata),role:this.role,id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}};function Ec(t){return t._getType()==="generic"}function Sc(t){return t._getType()==="generic"}var Tr=class extends tt{static lc_name(){return"FunctionMessage"}type="function";name;constructor(t){super(t),this.name=t.name}},xr=class extends _t{static lc_name(){return"FunctionMessageChunk"}type="function";concat(t){const e=this.constructor;return new e({content:yt(this.content,t.content),additional_kwargs:ve(this.additional_kwargs,t.additional_kwargs),response_metadata:ve(this.response_metadata,t.response_metadata),name:this.name??"",id:this.id??t.id})}};function Tc(t){return t._getType()==="function"}function xc(t){return t._getType()==="function"}var $t=class extends tt{static lc_name(){return"HumanMessage"}type="human";constructor(t){super(t)}static isInstance(t){return super.isInstance(t)&&t.type==="human"}},Ir=class extends _t{static lc_name(){return"HumanMessageChunk"}type="human";constructor(t){super(t)}concat(t){const e=this.constructor;return new e({content:yt(this.content,t.content),additional_kwargs:ve(this.additional_kwargs,t.additional_kwargs),response_metadata:ve(this.response_metadata,t.response_metadata),id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="human"}};function Ic(t){return t.getType()==="human"}function Ac(t){return t.getType()==="human"}var ct=class extends tt{static lc_name(){return"SystemMessage"}type="system";constructor(t){super(t)}static isInstance(t){return super.isInstance(t)&&t.type==="system"}},At=class extends _t{static lc_name(){return"SystemMessageChunk"}type="system";constructor(t){super(t)}concat(t){const e=this.constructor;return new e({content:yt(this.content,t.content),additional_kwargs:ve(this.additional_kwargs,t.additional_kwargs),response_metadata:ve(this.response_metadata,t.response_metadata),id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="system"}};function Oc(t){return t._getType()==="system"}function Rc(t){return t._getType()==="system"}var mr=class extends tt{type="remove";id;constructor(t){super({...t,content:[]}),this.id=t.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(t){return super.isInstance(t)&&t.type==="remove"}};function pd(t,e){return t.lc_error_code=e,t.message=`${t.message}
11
+ Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(r!=null&&n===void 0){const[a,s]=fn(r);e.tool_calls=a??[],e.invalid_tool_calls=s??[]}else e.tool_calls=e.tool_calls??[],e.invalid_tool_calls=e.invalid_tool_calls??[]}catch{e.tool_calls=[],e.invalid_tool_calls=[]}if(e.response_metadata!==void 0&&"output_version"in e.response_metadata&&e.response_metadata.output_version==="v1"&&(e.contentBlocks=e.content,e.content=void 0),e.contentBlocks!==void 0){e.contentBlocks.push(...e.tool_calls.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args})));const a=e.contentBlocks.filter(s=>s.type==="tool_call").filter(s=>!e.tool_calls?.some(i=>i.id===s.id&&i.name===s.name));a.length>0&&(e.tool_calls=a.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args})))}}super(e),typeof e!="string"&&(this.tool_calls=e.tool_calls??this.tool_calls,this.invalid_tool_calls=e.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=e.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const e=gc(this.response_metadata.model_provider);if(e)return e.translateContent(this)}const t=super.contentBlocks;if(this.tool_calls){const e=this.tool_calls.filter(r=>!t.some(n=>n.id===r.id&&n.name===r.name));t.push(...e.map(r=>({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})))}return t}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}};function _c(t){return t._getType()==="ai"}function yc(t){return t._getType()==="ai"}var Ot=class extends _t{type="ai";tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(t){let e;if(typeof t=="string"||Array.isArray(t))e={content:t,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(t.tool_call_chunks===void 0||t.tool_call_chunks.length===0)e={...t,tool_calls:t.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:t.usage_metadata!==void 0?t.usage_metadata:void 0};else{const n=(t.tool_call_chunks??[]).reduce((i,o)=>{const c=i.findIndex(([u])=>"id"in o&&o.id&&"index"in o&&o.index!==void 0?o.id===u.id&&o.index===u.index:"id"in o&&o.id?o.id===u.id:"index"in o&&o.index!==void 0?o.index===u.index:!1);return c!==-1?i[c].push(o):i.push([o]),i},[]),a=[],s=[];for(const i of n){let o=null;const c=i[0]?.name??"",u=i.map(f=>f.args||"").join(""),l=u.length?u:"{}",d=i[0]?.id;try{if(o=mc(l),!d||o===null||typeof o!="object"||Array.isArray(o))throw new Error("Malformed tool call chunk args.");a.push({name:c,args:o,id:d,type:"tool_call"})}catch{s.push({name:c,args:l,id:d,error:"Malformed args.",type:"invalid_tool_call"})}}e={...t,tool_calls:a,invalid_tool_calls:s,usage_metadata:t.usage_metadata!==void 0?t.usage_metadata:void 0}}super(e),this.tool_call_chunks=e.tool_call_chunks??this.tool_call_chunks,this.tool_calls=e.tool_calls??this.tool_calls,this.invalid_tool_calls=e.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=e.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const e=gc(this.response_metadata.model_provider);if(e)return e.translateContent(this)}const t=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){const e=this.content.filter(r=>r.type==="tool_call").map(r=>r.id);for(const r of this.tool_calls)r.id&&!e.includes(r.id)&&t.push({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})}return t}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(t){const e={content:gt(this.content,t.content),additional_kwargs:ve(this.additional_kwargs,t.additional_kwargs),response_metadata:vs(this.response_metadata,t.response_metadata),tool_call_chunks:[],id:this.id??t.id};if(this.tool_call_chunks!==void 0||t.tool_call_chunks!==void 0){const n=Zt(this.tool_call_chunks,t.tool_call_chunks);n!==void 0&&n.length>0&&(e.tool_call_chunks=n)}(this.usage_metadata!==void 0||t.usage_metadata!==void 0)&&(e.usage_metadata=ws(this.usage_metadata,t.usage_metadata));const r=this.constructor;return new r(e)}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}},Vt=class vc extends et{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return vc}constructor(e,r){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:r}),super(e),this.role=e.role}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},Er=class extends _t{static lc_name(){return"ChatMessageChunk"}type="generic";role;constructor(t,e){(typeof t=="string"||Array.isArray(t))&&(t={content:t,role:e}),super(t),this.role=t.role}concat(t){const e=this.constructor;return new e({content:gt(this.content,t.content),additional_kwargs:ve(this.additional_kwargs,t.additional_kwargs),response_metadata:ve(this.response_metadata,t.response_metadata),role:this.role,id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}};function wc(t){return t._getType()==="generic"}function bc(t){return t._getType()==="generic"}var Sr=class extends et{static lc_name(){return"FunctionMessage"}type="function";name;constructor(t){super(t),this.name=t.name}},Tr=class extends _t{static lc_name(){return"FunctionMessageChunk"}type="function";concat(t){const e=this.constructor;return new e({content:gt(this.content,t.content),additional_kwargs:ve(this.additional_kwargs,t.additional_kwargs),response_metadata:ve(this.response_metadata,t.response_metadata),name:this.name??"",id:this.id??t.id})}};function Ec(t){return t._getType()==="function"}function Sc(t){return t._getType()==="function"}var $t=class extends et{static lc_name(){return"HumanMessage"}type="human";constructor(t){super(t)}static isInstance(t){return super.isInstance(t)&&t.type==="human"}},xr=class extends _t{static lc_name(){return"HumanMessageChunk"}type="human";constructor(t){super(t)}concat(t){const e=this.constructor;return new e({content:gt(this.content,t.content),additional_kwargs:ve(this.additional_kwargs,t.additional_kwargs),response_metadata:ve(this.response_metadata,t.response_metadata),id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="human"}};function Tc(t){return t.getType()==="human"}function xc(t){return t.getType()==="human"}var ot=class extends et{static lc_name(){return"SystemMessage"}type="system";constructor(t){super(t)}static isInstance(t){return super.isInstance(t)&&t.type==="system"}},It=class extends _t{static lc_name(){return"SystemMessageChunk"}type="system";constructor(t){super(t)}concat(t){const e=this.constructor;return new e({content:gt(this.content,t.content),additional_kwargs:ve(this.additional_kwargs,t.additional_kwargs),response_metadata:ve(this.response_metadata,t.response_metadata),id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="system"}};function Ic(t){return t._getType()==="system"}function Ac(t){return t._getType()==="system"}var pr=class extends et{type="remove";id;constructor(t){super({...t,content:[]}),this.id=t.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(t){return super.isInstance(t)&&t.type==="remove"}};function ld(t,e){return t.lc_error_code=e,t.message=`${t.message}
14
12
 
15
13
  Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
16
- `,t}function kc(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function Ng(t){return!!(t&&typeof t=="object"&&"toolCall"in t&&t.toolCall!=null&&typeof t.toolCall=="object"&&"id"in t.toolCall&&typeof t.toolCall.id=="string")}var md=class extends Error{output;constructor(t,e){super(t),this.output=e}};const $c=t=>t();function gd(t){return kc(t)?t:typeof t.id=="string"&&t.type==="function"&&typeof t.function=="object"&&t.function!==null&&"arguments"in t.function&&typeof t.function.arguments=="string"&&"name"in t.function&&typeof t.function.name=="string"?{id:t.id,args:JSON.parse(t.function.arguments),name:t.function.name,type:"tool_call"}:t}function yd(t){return typeof t=="object"&&t!=null&&t.lc===1&&Array.isArray(t.id)&&t.kwargs!=null&&typeof t.kwargs=="object"}function In(t){let e,r;if(yd(t)){const n=t.id.at(-1);n==="HumanMessage"||n==="HumanMessageChunk"?e="user":n==="AIMessage"||n==="AIMessageChunk"?e="assistant":n==="SystemMessage"||n==="SystemMessageChunk"?e="system":n==="FunctionMessage"||n==="FunctionMessageChunk"?e="function":n==="ToolMessage"||n==="ToolMessageChunk"?e="tool":e="unknown",r=t.kwargs}else{const{type:n,...a}=t;e=n,r=a}if(e==="human"||e==="user")return new $t(r);if(e==="ai"||e==="assistant"){const{tool_calls:n,...a}=r;if(!Array.isArray(n))return new It(r);const s=n.map(gd);return new It({...a,tool_calls:s})}else{if(e==="system")return new ct(r);if(e==="developer")return new ct({...r,additional_kwargs:{...r.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in r)return new Rt({...r,content:r.content,tool_call_id:r.tool_call_id,name:r.name});if(e==="remove"&&"id"in r&&typeof r.id=="string")return new mr({...r,id:r.id});throw pd(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
14
+ `,t}function Rc(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function Og(t){return!!(t&&typeof t=="object"&&"toolCall"in t&&t.toolCall!=null&&typeof t.toolCall=="object"&&"id"in t.toolCall&&typeof t.toolCall.id=="string")}var dd=class extends Error{output;constructor(t,e){super(t),this.output=e}};const Oc=t=>t();function fd(t){return Rc(t)?t:typeof t.id=="string"&&t.type==="function"&&typeof t.function=="object"&&t.function!==null&&"arguments"in t.function&&typeof t.function.arguments=="string"&&"name"in t.function&&typeof t.function.name=="string"?{id:t.id,args:JSON.parse(t.function.arguments),name:t.function.name,type:"tool_call"}:t}function hd(t){return typeof t=="object"&&t!=null&&t.lc===1&&Array.isArray(t.id)&&t.kwargs!=null&&typeof t.kwargs=="object"}function xn(t){let e,r;if(hd(t)){const n=t.id.at(-1);n==="HumanMessage"||n==="HumanMessageChunk"?e="user":n==="AIMessage"||n==="AIMessageChunk"?e="assistant":n==="SystemMessage"||n==="SystemMessageChunk"?e="system":n==="FunctionMessage"||n==="FunctionMessageChunk"?e="function":n==="ToolMessage"||n==="ToolMessageChunk"?e="tool":e="unknown",r=t.kwargs}else{const{type:n,...a}=t;e=n,r=a}if(e==="human"||e==="user")return new $t(r);if(e==="ai"||e==="assistant"){const{tool_calls:n,...a}=r;if(!Array.isArray(n))return new xt(r);const s=n.map(fd);return new xt({...a,tool_calls:s})}else{if(e==="system")return new ot(r);if(e==="developer")return new ot({...r,additional_kwargs:{...r.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in r)return new Rt({...r,content:r.content,tool_call_id:r.tool_call_id,name:r.name});if(e==="remove"&&"id"in r&&typeof r.id=="string")return new pr({...r,id:r.id});throw ld(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
17
15
 
18
- Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Cc(t){if(typeof t=="string")return new $t(t);if(fn(t))return t;if(Array.isArray(t)){const[e,r]=t;return In({type:e,content:r})}else if(_s(t)){const{role:e,...r}=t;return In({...r,type:e})}else return In(t)}function Is(t,e="Human",r="AI"){const n=[];for(const a of t){let s;if(a._getType()==="human")s=e;else if(a._getType()==="ai")s=r;else if(a._getType()==="system")s="System";else if(a._getType()==="tool")s="Tool";else if(a._getType()==="generic")s=a.role;else throw new Error(`Got unsupported message type: ${a._getType()}`);const i=a.name?`${a.name}, `:"",o=typeof a.content=="string"?a.content:JSON.stringify(a.content,null,2);n.push(`${s}: ${i}${o}`)}return n.join(`
19
- `)}function _d(t){if(t.data!==void 0)return t;{const e=t;return{type:e.type,data:{content:e.text,role:e.role,name:void 0,tool_call_id:void 0}}}}function As(t){const e=_d(t);switch(e.type){case"human":return new $t(e.data);case"ai":return new It(e.data);case"system":return new ct(e.data);case"function":if(e.data.name===void 0)throw new Error("Name must be defined for function messages");return new Tr(e.data);case"tool":if(e.data.tool_call_id===void 0)throw new Error("Tool call ID must be defined for tool messages");return new Rt(e.data);case"generic":if(e.data.role===void 0)throw new Error("Role must be defined for chat messages");return new Jt(e.data);default:throw new Error(`Got unexpected type: ${e.type}`)}}function Nc(t){return t.map(As)}function Pc(t){return t.map(e=>e.toDict())}function en(t){const e=t._getType();if(e==="human")return new Ir({...t});if(e==="ai"){let r={...t};return"tool_calls"in r&&(r={...r,tool_call_chunks:r.tool_calls?.map(n=>({...n,type:"tool_call_chunk",index:void 0,args:JSON.stringify(n.args)}))}),new kt({...r})}else{if(e==="system")return new At({...t});if(e==="function")return new xr({...t});if(Jt.isInstance(t))return new Sr({...t});throw new Error("Unknown message type.")}}const Mc=Symbol.for("ls:tracing_async_local_storage"),ir=Symbol.for("lc:context_variables"),vd=t=>{globalThis[Mc]=t},gr=()=>globalThis[Mc];var wd={},bd={};me(bd,{getEnv:()=>Fc,getEnvironmentVariable:()=>Et,getRuntimeEnvironment:()=>Bc,isBrowser:()=>Lc,isDeno:()=>pn,isJsDom:()=>Dc,isNode:()=>Uc,isWebWorker:()=>jc});const Lc=()=>typeof window<"u"&&typeof window.document<"u",jc=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Dc=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),pn=()=>typeof Deno<"u",Uc=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!pn(),Fc=()=>{let t;return Lc()?t="browser":Uc()?t="node":jc()?t="webworker":Dc()?t="jsdom":pn()?t="deno":t="other",t};let An;function Bc(){return An===void 0&&(An={library:"langchain-js",runtime:Fc()}),An}function Et(t){try{return typeof process<"u"?wd?.[t]:pn()?Deno?.env.get(t):void 0}catch{return}}const Ed=/^(?:[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 or(t){return typeof t=="string"&&Ed.test(t)}function Sd(t){if(!or(t))throw TypeError("Invalid UUID");var e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}var _e=[];for(var On=0;On<256;++On)_e.push((On+256).toString(16).slice(1));function zc(t,e=0){return(_e[t[e+0]]+_e[t[e+1]]+_e[t[e+2]]+_e[t[e+3]]+"-"+_e[t[e+4]]+_e[t[e+5]]+"-"+_e[t[e+6]]+_e[t[e+7]]+"-"+_e[t[e+8]]+_e[t[e+9]]+"-"+_e[t[e+10]]+_e[t[e+11]]+_e[t[e+12]]+_e[t[e+13]]+_e[t[e+14]]+_e[t[e+15]]).toLowerCase()}var jr,Td=new Uint8Array(16);function xd(){if(!jr&&(jr=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!jr))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return jr(Td)}function Id(t){t=unescape(encodeURIComponent(t));for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var Ad="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Od="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Rd(t,e,r){function n(a,s,i,o){var c;if(typeof a=="string"&&(a=Id(a)),typeof s=="string"&&(s=Sd(s)),((c=s)===null||c===void 0?void 0:c.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var u=new Uint8Array(16+a.length);if(u.set(s),u.set(a,s.length),u=r(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,i){o=o||0;for(var l=0;l<16;++l)i[o+l]=u[l];return i}return zc(u)}try{n.name=t}catch{}return n.DNS=Ad,n.URL=Od,n}var kd=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const gi={randomUUID:kd};function Te(t,e,r){if(gi.randomUUID&&!t)return gi.randomUUID();t=t||{};var n=t.random||(t.rng||xd)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,zc(n)}function $d(t,e,r,n){switch(t){case 0:return e&r^~e&n;case 1:return e^r^n;case 2:return e&r^e&n^r&n;case 3:return e^r^n}}function Rn(t,e){return t<<e|t>>>32-e}function Cd(t){var e=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof t=="string"){var n=unescape(encodeURIComponent(t));t=[];for(var a=0;a<n.length;++a)t.push(n.charCodeAt(a))}else Array.isArray(t)||(t=Array.prototype.slice.call(t));t.push(128);for(var s=t.length/4+2,i=Math.ceil(s/16),o=new Array(i),c=0;c<i;++c){for(var u=new Uint32Array(16),l=0;l<16;++l)u[l]=t[c*64+l*4]<<24|t[c*64+l*4+1]<<16|t[c*64+l*4+2]<<8|t[c*64+l*4+3];o[c]=u}o[i-1][14]=(t.length-1)*8/Math.pow(2,32),o[i-1][14]=Math.floor(o[i-1][14]),o[i-1][15]=(t.length-1)*8&4294967295;for(var d=0;d<i;++d){for(var f=new Uint32Array(80),h=0;h<16;++h)f[h]=o[d][h];for(var p=16;p<80;++p)f[p]=Rn(f[p-3]^f[p-8]^f[p-14]^f[p-16],1);for(var m=r[0],g=r[1],y=r[2],v=r[3],_=r[4],E=0;E<80;++E){var $=Math.floor(E/20),U=Rn(m,5)+$d($,g,y,v)+_+e[$]+f[E]>>>0;_=v,v=y,y=Rn(g,30)>>>0,g=m,m=U}r[0]=r[0]+m>>>0,r[1]=r[1]+g>>>0,r[2]=r[2]+y>>>0,r[3]=r[3]+v>>>0,r[4]=r[4]+_>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,r[0]&255,r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,r[1]&255,r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,r[2]&255,r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,r[3]&255,r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,r[4]&255]}var yi=Rd("v5",80,Cd),Nd={};me(Nd,{BaseCallbackHandler:()=>Ar,callbackHandlerPrefersStreaming:()=>Md,isBaseCallbackHandler:()=>qc});var Pd=class{};function Md(t){return"lc_prefer_streaming"in t&&t.lc_prefer_streaming}var Ar=class extends Pd{lc_serializable=!1;get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,hs(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Et("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(t){super(),this.lc_kwargs=t||{},t&&(this.ignoreLLM=t.ignoreLLM??this.ignoreLLM,this.ignoreChain=t.ignoreChain??this.ignoreChain,this.ignoreAgent=t.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=t.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=t.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=t.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(t._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return hr.prototype.toJSON.call(this)}toJSONNotImplemented(){return hr.prototype.toJSONNotImplemented.call(this)}static fromMethods(t){class e extends Ar{name=Te();constructor(){super(),Object.assign(this,t)}}return new e}};const qc=t=>{const e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},Ld="gen_ai.operation.name",jd="gen_ai.system",_i="gen_ai.request.model",Dd="gen_ai.response.model",vi="gen_ai.usage.input_tokens",wi="gen_ai.usage.output_tokens",bi="gen_ai.usage.total_tokens",Ud="gen_ai.request.max_tokens",Fd="gen_ai.request.temperature",Bd="gen_ai.request.top_p",zd="gen_ai.request.frequency_penalty",qd="gen_ai.request.presence_penalty",Gd="gen_ai.response.finish_reasons",Hd="gen_ai.prompt",Zd="gen_ai.completion",Vd="gen_ai.request.extra_query",Jd="gen_ai.request.extra_body",Wd="gen_ai.serialized.name",Kd="gen_ai.serialized.signature",Yd="gen_ai.serialized.doc",Xd="gen_ai.response.id",Qd="gen_ai.response.service_tier",ef="gen_ai.response.system_fingerprint",tf="gen_ai.usage.input_token_details",rf="gen_ai.usage.output_token_details",nf="langsmith.trace.session_id",af="langsmith.trace.session_name",sf="langsmith.span.kind",of="langsmith.trace.name",cf="langsmith.metadata",Ei="langsmith.span.tags",uf="langsmith.request.streaming",lf="langsmith.request.headers",df=(...t)=>fetch(...t),Gc=Symbol.for("ls:fetch_implementation"),ff=()=>{const t=globalThis[Gc];return t?typeof t=="function"&&"Headers"in t&&"Request"in t&&"Response"in t:!1},hf=t=>async(...e)=>{if(t||ke("DEBUG")==="true"){const[n,a]=e;console.log(`→ ${a?.method||"GET"} ${n}`)}const r=await(globalThis[Gc]??df)(...e);return(t||ke("DEBUG")==="true")&&console.log(`← ${r.status} ${r.statusText} ${r.url}`),r},Hc=()=>ke("PROJECT")??et("LANGCHAIN_SESSION")??"default",Zc="0.3.79";var Va={};let We;const pf=()=>typeof window<"u"&&typeof window.document<"u",mf=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",gf=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Vc=()=>typeof Deno<"u",yf=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Vc(),Jc=()=>We||(typeof Bun<"u"?We="bun":pf()?We="browser":yf()?We="node":mf()?We="webworker":gf()?We="jsdom":Vc()?We="deno":We="other",We);let kn;function Wc(){if(kn===void 0){const t=Jc(),e=vf();kn={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:Zc,...e}}return kn}function Kc(){const t=_f(),e={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[n,a]of Object.entries(t))typeof a=="string"&&!r.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?e.revision_id=a:e[n]=a);return e}function _f(){const t={};try{if(typeof process<"u"&&Va)for(const[e,r]of Object.entries(Va))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&r!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof r=="string"?t[e]=r.slice(0,2)+"*".repeat(r.length-4)+r.slice(-2):t[e]=r)}catch{}return t}function et(t){try{return typeof process<"u"?Va?.[t]:void 0}catch{return}}function ke(t){return et(`LANGSMITH_${t}`)||et(`LANGCHAIN_${t}`)}let $n;function vf(){if($n!==void 0)return $n;const t=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(const r of t){const n=et(r);n!==void 0&&(e[r]=n)}return $n=e,e}function Yc(){return et("OTEL_ENABLED")==="true"||ke("OTEL_ENABLED")==="true"}class wf{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...r){!this.hasWarned&&Yc()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let n;if(r.length===1&&typeof r[0]=="function"?n=r[0]:r.length===2&&typeof r[1]=="function"?n=r[1]:r.length===3&&typeof r[2]=="function"&&(n=r[2]),typeof n=="function")return n()}}class bf{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new wf})}getTracer(e,r){return this.mockTracer}getActiveSpan(){}setSpan(e,r){return e}getSpan(e){}setSpanContext(e,r){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}}class Ef{active(){return{}}with(e,r){return r()}}const Cn=Symbol.for("ls:otel_trace"),Nn=Symbol.for("ls:otel_context"),Si=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),Sf=new bf,Tf=new Ef;class xf{getTraceInstance(){return globalThis[Cn]??Sf}getContextInstance(){return globalThis[Nn]??Tf}initializeGlobalInstances(e){globalThis[Cn]===void 0&&(globalThis[Cn]=e.trace),globalThis[Nn]===void 0&&(globalThis[Nn]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[Si]=e}getDefaultOTLPTracerComponents(){return globalThis[Si]??void 0}}const Os=new xf;function Xc(){return Os.getTraceInstance()}function If(){return Os.getContextInstance()}function Af(){return Os.getDefaultOTLPTracerComponents()}const Of={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function Rf(t){return Of[t]||t}class kf{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,r){for(const n of e)try{if(!n.run)continue;if(n.operation==="post"){const a=this.createSpanForRun(n,n.run,r.get(n.id));a&&!n.run.end_time&&this.spans.set(n.id,a)}else this.updateSpanForRun(n,n.run)}catch(a){console.error(`Error processing operation ${n.id}:`,a)}}createSpanForRun(e,r,n){const a=n&&Xc().getSpan(n);if(a)try{return this.finishSpanSetup(a,r,e)}catch(s){console.error(`Failed to create span for run ${e.id}:`,s);return}}finishSpanSetup(e,r,n){return this.setSpanAttributes(e,r,n),r.error?(e.setStatus({code:2}),e.recordException(new Error(r.error))):e.setStatus({code:1}),r.end_time&&e.end(new Date(r.end_time)),e}updateSpanForRun(e,r){try{const n=this.spans.get(e.id);if(!n){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(n,r,e),r.error?(n.setStatus({code:2}),n.recordException(new Error(r.error))):n.setStatus({code:1});const a=r.end_time;a&&(n.end(new Date(a)),this.spans.delete(e.id))}catch(n){console.error(`Failed to update span for run ${e.id}:`,n)}}extractModelName(e){if(e.extra?.metadata){const r=e.extra.metadata;if(r.ls_model_name)return r.ls_model_name;if(r.invocation_params){const n=r.invocation_params;if(n.model)return n.model;if(n.model_name)return n.model_name}}}setSpanAttributes(e,r,n){if("run_type"in r&&r.run_type){e.setAttribute(sf,r.run_type);const o=Rf(r.run_type||"chain");e.setAttribute(Ld,o)}"name"in r&&r.name&&e.setAttribute(of,r.name),"session_id"in r&&r.session_id&&e.setAttribute(nf,r.session_id),"session_name"in r&&r.session_name&&e.setAttribute(af,r.session_name),this.setGenAiSystem(e,r);const a=this.extractModelName(r);a&&e.setAttribute(_i,a),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&e.setAttribute(vi,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&e.setAttribute(wi,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&e.setAttribute(bi,r.total_tokens),this.setInvocationParameters(e,r);const s=r.extra?.metadata||{};for(const[o,c]of Object.entries(s))c!=null&&e.setAttribute(`${cf}.${o}`,String(c));const i=r.tags;if(i&&Array.isArray(i)?e.setAttribute(Ei,i.join(", ")):i&&e.setAttribute(Ei,String(i)),"serialized"in r&&typeof r.serialized=="object"){const o=r.serialized;o.name&&e.setAttribute(Wd,String(o.name)),o.signature&&e.setAttribute(Kd,String(o.signature)),o.doc&&e.setAttribute(Yd,String(o.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,r){let n="langchain";const a=this.extractModelName(r);if(a){const s=a.toLowerCase();s.includes("anthropic")||s.startsWith("claude")?n="anthropic":s.includes("bedrock")?n="aws.bedrock":s.includes("azure")&&s.includes("openai")?n="az.ai.openai":s.includes("azure")&&s.includes("inference")?n="az.ai.inference":s.includes("cohere")?n="cohere":s.includes("deepseek")?n="deepseek":s.includes("gemini")?n="gemini":s.includes("groq")?n="groq":s.includes("watson")||s.includes("ibm")?n="ibm.watsonx.ai":s.includes("mistral")?n="mistral_ai":s.includes("gpt")||s.includes("openai")?n="openai":s.includes("perplexity")||s.includes("sonar")?n="perplexity":s.includes("vertex")?n="vertex_ai":(s.includes("xai")||s.includes("grok"))&&(n="xai")}e.setAttribute(jd,n)}setInvocationParameters(e,r){if(!r.extra?.metadata?.invocation_params)return;const n=r.extra.metadata.invocation_params;n.max_tokens!==void 0&&e.setAttribute(Ud,n.max_tokens),n.temperature!==void 0&&e.setAttribute(Fd,n.temperature),n.top_p!==void 0&&e.setAttribute(Bd,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(zd,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(qd,n.presence_penalty)}setIOAttributes(e,r){if(r.run.inputs)try{const n=r.run.inputs;typeof n=="object"&&n!==null&&(n.model&&Array.isArray(n.messages)&&e.setAttribute(_i,n.model),n.stream!==void 0&&e.setAttribute(uf,n.stream),n.extra_headers&&e.setAttribute(lf,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(Vd,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(Jd,JSON.stringify(n.extra_body))),e.setAttribute(Hd,JSON.stringify(n))}catch(n){console.debug(`Failed to process inputs for run ${r.id}`,n)}if(r.run.outputs)try{const n=r.run.outputs,a=this.getUnifiedRunTokens(n);if(a&&(e.setAttribute(vi,a[0]),e.setAttribute(wi,a[1]),e.setAttribute(bi,a[0]+a[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(Dd,String(n.model)),n.id&&e.setAttribute(Xd,n.id),n.choices&&Array.isArray(n.choices)){const s=n.choices.map(i=>i.finish_reason).filter(i=>i).map(String);s.length>0&&e.setAttribute(Gd,s.join(", "))}if(n.service_tier&&e.setAttribute(Qd,n.service_tier),n.system_fingerprint&&e.setAttribute(ef,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){const s=n.usage_metadata;s.input_token_details&&e.setAttribute(tf,JSON.stringify(s.input_token_details)),s.output_token_details&&e.setAttribute(rf,JSON.stringify(s.output_token_details))}}e.setAttribute(Zd,JSON.stringify(n))}catch(n){console.debug(`Failed to process outputs for run ${r.id}`,n)}}getUnifiedRunTokens(e){if(!e)return null;let r=this.extractUnifiedRunTokens(e.usage_metadata);if(r)return r;const n=Object.keys(e);for(const i of n){const o=e[i];if(!(!o||typeof o!="object")&&(r=this.extractUnifiedRunTokens(o.usage_metadata),r||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(r=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),r)))return r}const a=e.generations||[];if(!Array.isArray(a))return null;const s=Array.isArray(a[0])?a.flat():a;for(const i of s)if(typeof i=="object"&&i.message&&typeof i.message=="object"&&i.message.kwargs&&typeof i.message.kwargs=="object"&&(r=this.extractUnifiedRunTokens(i.message.kwargs.usage_metadata),r))return r;return null}extractUnifiedRunTokens(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}}var Qt={exports:{}},Pn={},Mn,Ti;function $f(){if(Ti)return Mn;Ti=1;function t(e,r){typeof r=="boolean"&&(r={forever:r}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=r||{},this._maxRetryTime=r&&r.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))}return Mn=t,t.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},t.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},t.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var r=new Date().getTime();if(e&&r-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1);else return!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)},n),this._options.unref&&this._timer.unref(),!0},t.prototype.attempt=function(e,r){this._fn=e,r&&(r.timeout&&(this._operationTimeout=r.timeout),r.cb&&(this._operationTimeoutCb=r.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},t.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},t.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},t.prototype.start=t.prototype.try,t.prototype.errors=function(){return this._errors},t.prototype.attempts=function(){return this._attempts},t.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},r=null,n=0,a=0;a<this._errors.length;a++){var s=this._errors[a],i=s.message,o=(e[i]||0)+1;e[i]=o,o>=n&&(r=s,n=o)}return r},Mn}var xi;function Cf(){return xi||(xi=1,(function(t){var e=$f();t.operation=function(r){var n=t.timeouts(r);return new e(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},t.timeouts=function(r){if(r instanceof Array)return[].concat(r);var n={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var a in r)n[a]=r[a];if(n.minTimeout>n.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var s=[],i=0;i<n.retries;i++)s.push(this.createTimeout(i,n));return r&&r.forever&&!s.length&&s.push(this.createTimeout(i,n)),s.sort(function(o,c){return o-c}),s},t.createTimeout=function(r,n){var a=n.randomize?Math.random()+1:1,s=Math.round(a*Math.max(n.minTimeout,1)*Math.pow(n.factor,r));return s=Math.min(s,n.maxTimeout),s},t.wrap=function(r,n,a){if(n instanceof Array&&(a=n,n=null),!a){a=[];for(var s in r)typeof r[s]=="function"&&a.push(s)}for(var i=0;i<a.length;i++){var o=a[i],c=r[o];r[o]=(function(l){var d=t.operation(n),f=Array.prototype.slice.call(arguments,1),h=f.pop();f.push(function(p){d.retry(p)||(p&&(arguments[0]=d.mainError()),h.apply(this,arguments))}),d.attempt(function(){l.apply(r,f)})}).bind(r,c),r[o].options=n}}})(Pn)),Pn}var Ln,Ii;function Nf(){return Ii||(Ii=1,Ln=Cf()),Ln}var Ai;function Pf(){if(Ai)return Qt.exports;Ai=1;const t=Nf(),e=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class r extends Error{constructor(o){super(),o instanceof Error?(this.originalError=o,{message:o}=o):(this.originalError=new Error(o),this.originalError.stack=this.stack),this.name="AbortError",this.message=o}}const n=(i,o,c)=>{const u=c.retries-(o-1);return i.attemptNumber=o,i.retriesLeft=u,i},a=i=>e.includes(i),s=(i,o)=>new Promise((c,u)=>{o={onFailedAttempt:()=>{},retries:10,...o};const l=t.operation(o);l.attempt(async d=>{try{c(await i(d))}catch(f){if(!(f instanceof Error)){u(new TypeError(`Non-error was thrown: "${f}". You should only throw errors.`));return}if(f instanceof r)l.stop(),u(f.originalError);else if(f instanceof TypeError&&!a(f.message))l.stop(),u(f);else{n(f,d,o);try{await o.onFailedAttempt(f)}catch(h){u(h);return}l.retry(f)||u(l.mainError())}}})});return Qt.exports=s,Qt.exports.default=s,Qt.exports.AbortError=r,Qt.exports}var Mf=Pf();const tn=br(Mf);var Dr={},jn={exports:{}},Oi;function Lf(){return Oi||(Oi=1,(function(t){var e=Object.prototype.hasOwnProperty,r="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1));function a(c,u,l){this.fn=c,this.context=u,this.once=l||!1}function s(c,u,l,d,f){if(typeof l!="function")throw new TypeError("The listener must be a function");var h=new a(l,d||c,f),p=r?r+u:u;return c._events[p]?c._events[p].fn?c._events[p]=[c._events[p],h]:c._events[p].push(h):(c._events[p]=h,c._eventsCount++),c}function i(c,u){--c._eventsCount===0?c._events=new n:delete c._events[u]}function o(){this._events=new n,this._eventsCount=0}o.prototype.eventNames=function(){var u=[],l,d;if(this._eventsCount===0)return u;for(d in l=this._events)e.call(l,d)&&u.push(r?d.slice(1):d);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(l)):u},o.prototype.listeners=function(u){var l=r?r+u:u,d=this._events[l];if(!d)return[];if(d.fn)return[d.fn];for(var f=0,h=d.length,p=new Array(h);f<h;f++)p[f]=d[f].fn;return p},o.prototype.listenerCount=function(u){var l=r?r+u:u,d=this._events[l];return d?d.fn?1:d.length:0},o.prototype.emit=function(u,l,d,f,h,p){var m=r?r+u:u;if(!this._events[m])return!1;var g=this._events[m],y=arguments.length,v,_;if(g.fn){switch(g.once&&this.removeListener(u,g.fn,void 0,!0),y){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,l),!0;case 3:return g.fn.call(g.context,l,d),!0;case 4:return g.fn.call(g.context,l,d,f),!0;case 5:return g.fn.call(g.context,l,d,f,h),!0;case 6:return g.fn.call(g.context,l,d,f,h,p),!0}for(_=1,v=new Array(y-1);_<y;_++)v[_-1]=arguments[_];g.fn.apply(g.context,v)}else{var E=g.length,$;for(_=0;_<E;_++)switch(g[_].once&&this.removeListener(u,g[_].fn,void 0,!0),y){case 1:g[_].fn.call(g[_].context);break;case 2:g[_].fn.call(g[_].context,l);break;case 3:g[_].fn.call(g[_].context,l,d);break;case 4:g[_].fn.call(g[_].context,l,d,f);break;default:if(!v)for($=1,v=new Array(y-1);$<y;$++)v[$-1]=arguments[$];g[_].fn.apply(g[_].context,v)}}return!0},o.prototype.on=function(u,l,d){return s(this,u,l,d,!1)},o.prototype.once=function(u,l,d){return s(this,u,l,d,!0)},o.prototype.removeListener=function(u,l,d,f){var h=r?r+u:u;if(!this._events[h])return this;if(!l)return i(this,h),this;var p=this._events[h];if(p.fn)p.fn===l&&(!f||p.once)&&(!d||p.context===d)&&i(this,h);else{for(var m=0,g=[],y=p.length;m<y;m++)(p[m].fn!==l||f&&!p[m].once||d&&p[m].context!==d)&&g.push(p[m]);g.length?this._events[h]=g.length===1?g[0]:g:i(this,h)}return this},o.prototype.removeAllListeners=function(u){var l;return u?(l=r?r+u:u,this._events[l]&&i(this,l)):(this._events=new n,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,t.exports=o})(jn)),jn.exports}var er={exports:{}},Dn,Ri;function jf(){return Ri||(Ri=1,Dn=(t,e)=>(e=e||(()=>{}),t.then(r=>new Promise(n=>{n(e())}).then(()=>r),r=>new Promise(n=>{n(e())}).then(()=>{throw r})))),Dn}var ki;function Df(){if(ki)return er.exports;ki=1;const t=jf();class e extends Error{constructor(a){super(a),this.name="TimeoutError"}}const r=(n,a,s)=>new Promise((i,o)=>{if(typeof a!="number"||a<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(a===1/0){i(n);return}const c=setTimeout(()=>{if(typeof s=="function"){try{i(s())}catch(d){o(d)}return}const u=typeof s=="string"?s:`Promise timed out after ${a} milliseconds`,l=s instanceof Error?s:new e(u);typeof n.cancel=="function"&&n.cancel(),o(l)},a);t(n.then(i,o),()=>{clearTimeout(c)})});return er.exports=r,er.exports.default=r,er.exports.TimeoutError=e,er.exports}var Ur={},Fr={},$i;function Uf(){if($i)return Fr;$i=1,Object.defineProperty(Fr,"__esModule",{value:!0});function t(e,r,n){let a=0,s=e.length;for(;s>0;){const i=s/2|0;let o=a+i;n(e[o],r)<=0?(a=++o,s-=i+1):s=i}return a}return Fr.default=t,Fr}var Ci;function Ff(){if(Ci)return Ur;Ci=1,Object.defineProperty(Ur,"__esModule",{value:!0});const t=Uf();class e{constructor(){this._queue=[]}enqueue(n,a){a=Object.assign({priority:0},a);const s={priority:a.priority,run:n};if(this.size&&this._queue[this.size-1].priority>=a.priority){this._queue.push(s);return}const i=t.default(this._queue,s,(o,c)=>c.priority-o.priority);this._queue.splice(i,0,s)}dequeue(){const n=this._queue.shift();return n?.run}filter(n){return this._queue.filter(a=>a.priority===n.priority).map(a=>a.run)}get size(){return this._queue.length}}return Ur.default=e,Ur}var Ni;function Bf(){if(Ni)return Dr;Ni=1,Object.defineProperty(Dr,"__esModule",{value:!0});const t=Lf(),e=Df(),r=Ff(),n=()=>{},a=new e.TimeoutError;class s extends t{constructor(o){var c,u,l,d;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=n,this._resolveIdle=n,o=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:r.default},o),!(typeof o.intervalCap=="number"&&o.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(u=(c=o.intervalCap)===null||c===void 0?void 0:c.toString())!==null&&u!==void 0?u:""}\` (${typeof o.intervalCap})`);if(o.interval===void 0||!(Number.isFinite(o.interval)&&o.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(d=(l=o.interval)===null||l===void 0?void 0:l.toString())!==null&&d!==void 0?d:""}\` (${typeof o.interval})`);this._carryoverConcurrencyCount=o.carryoverConcurrencyCount,this._isIntervalIgnored=o.intervalCap===1/0||o.interval===0,this._intervalCap=o.intervalCap,this._interval=o.interval,this._queue=new o.queueClass,this._queueClass=o.queueClass,this.concurrency=o.concurrency,this._timeout=o.timeout,this._throwOnTimeout=o.throwOnTimeout===!0,this._isPaused=o.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=n,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=n,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const o=Date.now();if(this._intervalId===void 0){const c=this._intervalEnd-o;if(c<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},c)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const o=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const c=this._queue.dequeue();return c?(this.emit("active"),c(),o&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(o){if(!(typeof o=="number"&&o>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${o}\` (${typeof o})`);this._concurrency=o,this._processQueue()}async add(o,c={}){return new Promise((u,l)=>{const d=async()=>{this._pendingCount++,this._intervalCount++;try{const f=this._timeout===void 0&&c.timeout===void 0?o():e.default(Promise.resolve(o()),c.timeout===void 0?this._timeout:c.timeout,()=>{(c.throwOnTimeout===void 0?this._throwOnTimeout:c.throwOnTimeout)&&l(a)});u(await f)}catch(f){l(f)}this._next()};this._queue.enqueue(d,c),this._tryToStartAnother(),this.emit("add")})}async addAll(o,c){return Promise.all(o.map(async u=>this.add(u,c)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(o=>{const c=this._resolveEmpty;this._resolveEmpty=()=>{c(),o()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(o=>{const c=this._resolveIdle;this._resolveIdle=()=>{c(),o()}})}get size(){return this._queue.size}sizeBy(o){return this._queue.filter(o).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(o){this._timeout=o}}return Dr.default=s,Dr}var zf=Bf();const at=br(zf),qf=[429,500,502,503,504];let Pi=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}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,"default"in at?this.queue=new at.default({concurrency:this.maxConcurrency}):this.queue=new at({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...r){const n=this.onFailedResponseHook;return this.queue.add(()=>tn(()=>e(...r).catch(a=>{throw a instanceof Error?a:new Error(a)}),{async onFailedAttempt(a){if(a.message.startsWith("Cancel")||a.message.startsWith("TimeoutError")||a.name==="TimeoutError"||a.message.startsWith("AbortError")||a?.code==="ECONNABORTED")throw a;const s=a?.response;if(n&&await n(s))return;const i=s?.status??a?.status;if(i&&!qf.includes(+i))throw a},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,r,...n){return e.signal?Promise.race([this.call(r,...n),new Promise((a,s)=>{e.signal?.addEventListener("abort",()=>{s(new Error("AbortError"))})})]):this.call(r,...n)}};function Mi(t){return typeof t?._getType=="function"}function Li(t){const e={type:t._getType(),data:{content:t.content}};return t?.additional_kwargs&&Object.keys(t.additional_kwargs).length>0&&(e.data.additional_kwargs={...t.additional_kwargs}),e}const Gf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function K(t,e){if(!Gf.test(t)){const r=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(r)}return t}const ji={};function Ja(t){ji[t]||(console.warn(t),ji[t]=!0)}var Br={exports:{}},Un,Di;function mn(){if(Di)return Un;Di=1;const t="2.0.0",e=256,r=Number.MAX_SAFE_INTEGER||9007199254740991,n=16,a=e-6;return Un={MAX_LENGTH:e,MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:a,MAX_SAFE_INTEGER:r,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:t,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},Un}var Fn,Ui;function gn(){if(Ui)return Fn;Ui=1;var t={};return Fn=typeof process=="object"&&t&&t.NODE_DEBUG&&/\bsemver\b/i.test(t.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{},Fn}var Fi;function Or(){return Fi||(Fi=1,(function(t,e){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:a}=mn(),s=gn();e=t.exports={};const i=e.re=[],o=e.safeRe=[],c=e.src=[],u=e.safeSrc=[],l=e.t={};let d=0;const f="[a-zA-Z0-9-]",h=[["\\s",1],["\\d",a],[f,n]],p=g=>{for(const[y,v]of h)g=g.split(`${y}*`).join(`${y}{0,${v}}`).split(`${y}+`).join(`${y}{1,${v}}`);return g},m=(g,y,v)=>{const _=p(y),E=d++;s(g,E,y),l[g]=E,c[E]=y,u[E]=_,i[E]=new RegExp(y,v?"g":void 0),o[E]=new RegExp(_,v?"g":void 0)};m("NUMERICIDENTIFIER","0|[1-9]\\d*"),m("NUMERICIDENTIFIERLOOSE","\\d+"),m("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${f}*`),m("MAINVERSION",`(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})`),m("MAINVERSIONLOOSE",`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASEIDENTIFIER",`(?:${c[l.NONNUMERICIDENTIFIER]}|${c[l.NUMERICIDENTIFIER]})`),m("PRERELEASEIDENTIFIERLOOSE",`(?:${c[l.NONNUMERICIDENTIFIER]}|${c[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASE",`(?:-(${c[l.PRERELEASEIDENTIFIER]}(?:\\.${c[l.PRERELEASEIDENTIFIER]})*))`),m("PRERELEASELOOSE",`(?:-?(${c[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[l.PRERELEASEIDENTIFIERLOOSE]})*))`),m("BUILDIDENTIFIER",`${f}+`),m("BUILD",`(?:\\+(${c[l.BUILDIDENTIFIER]}(?:\\.${c[l.BUILDIDENTIFIER]})*))`),m("FULLPLAIN",`v?${c[l.MAINVERSION]}${c[l.PRERELEASE]}?${c[l.BUILD]}?`),m("FULL",`^${c[l.FULLPLAIN]}$`),m("LOOSEPLAIN",`[v=\\s]*${c[l.MAINVERSIONLOOSE]}${c[l.PRERELEASELOOSE]}?${c[l.BUILD]}?`),m("LOOSE",`^${c[l.LOOSEPLAIN]}$`),m("GTLT","((?:<|>)?=?)"),m("XRANGEIDENTIFIERLOOSE",`${c[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),m("XRANGEIDENTIFIER",`${c[l.NUMERICIDENTIFIER]}|x|X|\\*`),m("XRANGEPLAIN",`[v=\\s]*(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:${c[l.PRERELEASE]})?${c[l.BUILD]}?)?)?`),m("XRANGEPLAINLOOSE",`[v=\\s]*(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:${c[l.PRERELEASELOOSE]})?${c[l.BUILD]}?)?)?`),m("XRANGE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAIN]}$`),m("XRANGELOOSE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAINLOOSE]}$`),m("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),m("COERCE",`${c[l.COERCEPLAIN]}(?:$|[^\\d])`),m("COERCEFULL",c[l.COERCEPLAIN]+`(?:${c[l.PRERELEASE]})?(?:${c[l.BUILD]})?(?:$|[^\\d])`),m("COERCERTL",c[l.COERCE],!0),m("COERCERTLFULL",c[l.COERCEFULL],!0),m("LONETILDE","(?:~>?)"),m("TILDETRIM",`(\\s*)${c[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",m("TILDE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAIN]}$`),m("TILDELOOSE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAINLOOSE]}$`),m("LONECARET","(?:\\^)"),m("CARETTRIM",`(\\s*)${c[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",m("CARET",`^${c[l.LONECARET]}${c[l.XRANGEPLAIN]}$`),m("CARETLOOSE",`^${c[l.LONECARET]}${c[l.XRANGEPLAINLOOSE]}$`),m("COMPARATORLOOSE",`^${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]})$|^$`),m("COMPARATOR",`^${c[l.GTLT]}\\s*(${c[l.FULLPLAIN]})$|^$`),m("COMPARATORTRIM",`(\\s*)${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]}|${c[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",m("HYPHENRANGE",`^\\s*(${c[l.XRANGEPLAIN]})\\s+-\\s+(${c[l.XRANGEPLAIN]})\\s*$`),m("HYPHENRANGELOOSE",`^\\s*(${c[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[l.XRANGEPLAINLOOSE]})\\s*$`),m("STAR","(<|>)?=?\\s*\\*"),m("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),m("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(Br,Br.exports)),Br.exports}var Bn,Bi;function Rs(){if(Bi)return Bn;Bi=1;const t=Object.freeze({loose:!0}),e=Object.freeze({});return Bn=n=>n?typeof n!="object"?t:n:e,Bn}var zn,zi;function Qc(){if(zi)return zn;zi=1;const t=/^[0-9]+$/,e=(n,a)=>{if(typeof n=="number"&&typeof a=="number")return n===a?0:n<a?-1:1;const s=t.test(n),i=t.test(a);return s&&i&&(n=+n,a=+a),n===a?0:s&&!i?-1:i&&!s?1:n<a?-1:1};return zn={compareIdentifiers:e,rcompareIdentifiers:(n,a)=>e(a,n)},zn}var qn,qi;function Ie(){if(qi)return qn;qi=1;const t=gn(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:r}=mn(),{safeRe:n,t:a}=Or(),s=Rs(),{compareIdentifiers:i}=Qc();class o{constructor(u,l){if(l=s(l),u instanceof o){if(u.loose===!!l.loose&&u.includePrerelease===!!l.includePrerelease)return u;u=u.version}else if(typeof u!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof u}".`);if(u.length>e)throw new TypeError(`version is longer than ${e} characters`);t("SemVer",u,l),this.options=l,this.loose=!!l.loose,this.includePrerelease=!!l.includePrerelease;const d=u.trim().match(l.loose?n[a.LOOSE]:n[a.FULL]);if(!d)throw new TypeError(`Invalid Version: ${u}`);if(this.raw=u,this.major=+d[1],this.minor=+d[2],this.patch=+d[3],this.major>r||this.major<0)throw new TypeError("Invalid major version");if(this.minor>r||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>r||this.patch<0)throw new TypeError("Invalid patch version");d[4]?this.prerelease=d[4].split(".").map(f=>{if(/^[0-9]+$/.test(f)){const h=+f;if(h>=0&&h<r)return h}return f}):this.prerelease=[],this.build=d[5]?d[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(u){if(t("SemVer.compare",this.version,this.options,u),!(u instanceof o)){if(typeof u=="string"&&u===this.version)return 0;u=new o(u,this.options)}return u.version===this.version?0:this.compareMain(u)||this.comparePre(u)}compareMain(u){return u instanceof o||(u=new o(u,this.options)),this.major<u.major?-1:this.major>u.major?1:this.minor<u.minor?-1:this.minor>u.minor?1:this.patch<u.patch?-1:this.patch>u.patch?1:0}comparePre(u){if(u instanceof o||(u=new o(u,this.options)),this.prerelease.length&&!u.prerelease.length)return-1;if(!this.prerelease.length&&u.prerelease.length)return 1;if(!this.prerelease.length&&!u.prerelease.length)return 0;let l=0;do{const d=this.prerelease[l],f=u.prerelease[l];if(t("prerelease compare",l,d,f),d===void 0&&f===void 0)return 0;if(f===void 0)return 1;if(d===void 0)return-1;if(d===f)continue;return i(d,f)}while(++l)}compareBuild(u){u instanceof o||(u=new o(u,this.options));let l=0;do{const d=this.build[l],f=u.build[l];if(t("build compare",l,d,f),d===void 0&&f===void 0)return 0;if(f===void 0)return 1;if(d===void 0)return-1;if(d===f)continue;return i(d,f)}while(++l)}inc(u,l,d){if(u.startsWith("pre")){if(!l&&d===!1)throw new Error("invalid increment argument: identifier is empty");if(l){const f=`-${l}`.match(this.options.loose?n[a.PRERELEASELOOSE]:n[a.PRERELEASE]);if(!f||f[1]!==l)throw new Error(`invalid identifier: ${l}`)}}switch(u){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",l,d);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",l,d);break;case"prepatch":this.prerelease.length=0,this.inc("patch",l,d),this.inc("pre",l,d);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",l,d),this.inc("pre",l,d);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const f=Number(d)?1:0;if(this.prerelease.length===0)this.prerelease=[f];else{let h=this.prerelease.length;for(;--h>=0;)typeof this.prerelease[h]=="number"&&(this.prerelease[h]++,h=-2);if(h===-1){if(l===this.prerelease.join(".")&&d===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(f)}}if(l){let h=[l,f];d===!1&&(h=[l]),i(this.prerelease[0],l)===0?isNaN(this.prerelease[1])&&(this.prerelease=h):this.prerelease=h}break}default:throw new Error(`invalid increment argument: ${u}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return qn=o,qn}var Gn,Gi;function Wt(){if(Gi)return Gn;Gi=1;const t=Ie();return Gn=(r,n,a=!1)=>{if(r instanceof t)return r;try{return new t(r,n)}catch(s){if(!a)return null;throw s}},Gn}var Hn,Hi;function Hf(){if(Hi)return Hn;Hi=1;const t=Wt();return Hn=(r,n)=>{const a=t(r,n);return a?a.version:null},Hn}var Zn,Zi;function Zf(){if(Zi)return Zn;Zi=1;const t=Wt();return Zn=(r,n)=>{const a=t(r.trim().replace(/^[=v]+/,""),n);return a?a.version:null},Zn}var Vn,Vi;function Vf(){if(Vi)return Vn;Vi=1;const t=Ie();return Vn=(r,n,a,s,i)=>{typeof a=="string"&&(i=s,s=a,a=void 0);try{return new t(r instanceof t?r.version:r,a).inc(n,s,i).version}catch{return null}},Vn}var Jn,Ji;function Jf(){if(Ji)return Jn;Ji=1;const t=Wt();return Jn=(r,n)=>{const a=t(r,null,!0),s=t(n,null,!0),i=a.compare(s);if(i===0)return null;const o=i>0,c=o?a:s,u=o?s:a,l=!!c.prerelease.length;if(!!u.prerelease.length&&!l){if(!u.patch&&!u.minor)return"major";if(u.compareMain(c)===0)return u.minor&&!u.patch?"minor":"patch"}const f=l?"pre":"";return a.major!==s.major?f+"major":a.minor!==s.minor?f+"minor":a.patch!==s.patch?f+"patch":"prerelease"},Jn}var Wn,Wi;function Wf(){if(Wi)return Wn;Wi=1;const t=Ie();return Wn=(r,n)=>new t(r,n).major,Wn}var Kn,Ki;function Kf(){if(Ki)return Kn;Ki=1;const t=Ie();return Kn=(r,n)=>new t(r,n).minor,Kn}var Yn,Yi;function Yf(){if(Yi)return Yn;Yi=1;const t=Ie();return Yn=(r,n)=>new t(r,n).patch,Yn}var Xn,Xi;function Xf(){if(Xi)return Xn;Xi=1;const t=Wt();return Xn=(r,n)=>{const a=t(r,n);return a&&a.prerelease.length?a.prerelease:null},Xn}var Qn,Qi;function Ze(){if(Qi)return Qn;Qi=1;const t=Ie();return Qn=(r,n,a)=>new t(r,a).compare(new t(n,a)),Qn}var ea,eo;function Qf(){if(eo)return ea;eo=1;const t=Ze();return ea=(r,n,a)=>t(n,r,a),ea}var ta,to;function eh(){if(to)return ta;to=1;const t=Ze();return ta=(r,n)=>t(r,n,!0),ta}var ra,ro;function ks(){if(ro)return ra;ro=1;const t=Ie();return ra=(r,n,a)=>{const s=new t(r,a),i=new t(n,a);return s.compare(i)||s.compareBuild(i)},ra}var na,no;function th(){if(no)return na;no=1;const t=ks();return na=(r,n)=>r.sort((a,s)=>t(a,s,n)),na}var aa,ao;function rh(){if(ao)return aa;ao=1;const t=ks();return aa=(r,n)=>r.sort((a,s)=>t(s,a,n)),aa}var sa,so;function yn(){if(so)return sa;so=1;const t=Ze();return sa=(r,n,a)=>t(r,n,a)>0,sa}var ia,io;function $s(){if(io)return ia;io=1;const t=Ze();return ia=(r,n,a)=>t(r,n,a)<0,ia}var oa,oo;function eu(){if(oo)return oa;oo=1;const t=Ze();return oa=(r,n,a)=>t(r,n,a)===0,oa}var ca,co;function tu(){if(co)return ca;co=1;const t=Ze();return ca=(r,n,a)=>t(r,n,a)!==0,ca}var ua,uo;function Cs(){if(uo)return ua;uo=1;const t=Ze();return ua=(r,n,a)=>t(r,n,a)>=0,ua}var la,lo;function Ns(){if(lo)return la;lo=1;const t=Ze();return la=(r,n,a)=>t(r,n,a)<=0,la}var da,fo;function ru(){if(fo)return da;fo=1;const t=eu(),e=tu(),r=yn(),n=Cs(),a=$s(),s=Ns();return da=(o,c,u,l)=>{switch(c){case"===":return typeof o=="object"&&(o=o.version),typeof u=="object"&&(u=u.version),o===u;case"!==":return typeof o=="object"&&(o=o.version),typeof u=="object"&&(u=u.version),o!==u;case"":case"=":case"==":return t(o,u,l);case"!=":return e(o,u,l);case">":return r(o,u,l);case">=":return n(o,u,l);case"<":return a(o,u,l);case"<=":return s(o,u,l);default:throw new TypeError(`Invalid operator: ${c}`)}},da}var fa,ho;function nh(){if(ho)return fa;ho=1;const t=Ie(),e=Wt(),{safeRe:r,t:n}=Or();return fa=(s,i)=>{if(s instanceof t)return s;if(typeof s=="number"&&(s=String(s)),typeof s!="string")return null;i=i||{};let o=null;if(!i.rtl)o=s.match(i.includePrerelease?r[n.COERCEFULL]:r[n.COERCE]);else{const h=i.includePrerelease?r[n.COERCERTLFULL]:r[n.COERCERTL];let p;for(;(p=h.exec(s))&&(!o||o.index+o[0].length!==s.length);)(!o||p.index+p[0].length!==o.index+o[0].length)&&(o=p),h.lastIndex=p.index+p[1].length+p[2].length;h.lastIndex=-1}if(o===null)return null;const c=o[2],u=o[3]||"0",l=o[4]||"0",d=i.includePrerelease&&o[5]?`-${o[5]}`:"",f=i.includePrerelease&&o[6]?`+${o[6]}`:"";return e(`${c}.${u}.${l}${d}${f}`,i)},fa}var ha,po;function ah(){if(po)return ha;po=1;class t{constructor(){this.max=1e3,this.map=new Map}get(r){const n=this.map.get(r);if(n!==void 0)return this.map.delete(r),this.map.set(r,n),n}delete(r){return this.map.delete(r)}set(r,n){if(!this.delete(r)&&n!==void 0){if(this.map.size>=this.max){const s=this.map.keys().next().value;this.delete(s)}this.map.set(r,n)}return this}}return ha=t,ha}var pa,mo;function Ve(){if(mo)return pa;mo=1;const t=/\s+/g;class e{constructor(S,F){if(F=a(F),S instanceof e)return S.loose===!!F.loose&&S.includePrerelease===!!F.includePrerelease?S:new e(S.raw,F);if(S instanceof s)return this.raw=S.value,this.set=[[S]],this.formatted=void 0,this;if(this.options=F,this.loose=!!F.loose,this.includePrerelease=!!F.includePrerelease,this.raw=S.trim().replace(t," "),this.set=this.raw.split("||").map(P=>this.parseRange(P.trim())).filter(P=>P.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const P=this.set[0];if(this.set=this.set.filter(B=>!m(B[0])),this.set.length===0)this.set=[P];else if(this.set.length>1){for(const B of this.set)if(B.length===1&&g(B[0])){this.set=[B];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let S=0;S<this.set.length;S++){S>0&&(this.formatted+="||");const F=this.set[S];for(let P=0;P<F.length;P++)P>0&&(this.formatted+=" "),this.formatted+=F[P].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(S){const P=((this.options.includePrerelease&&h)|(this.options.loose&&p))+":"+S,B=n.get(P);if(B)return B;const M=this.options.loose,H=M?c[u.HYPHENRANGELOOSE]:c[u.HYPHENRANGE];S=S.replace(H,Ue(this.options.includePrerelease)),i("hyphen replace",S),S=S.replace(c[u.COMPARATORTRIM],l),i("comparator trim",S),S=S.replace(c[u.TILDETRIM],d),i("tilde trim",S),S=S.replace(c[u.CARETTRIM],f),i("caret trim",S);let Q=S.split(" ").map(ne=>v(ne,this.options)).join(" ").split(/\s+/).map(ne=>Me(ne,this.options));M&&(Q=Q.filter(ne=>(i("loose invalid filter",ne,this.options),!!ne.match(c[u.COMPARATORLOOSE])))),i("range list",Q);const Y=new Map,se=Q.map(ne=>new s(ne,this.options));for(const ne of se){if(m(ne))return[ne];Y.set(ne.value,ne)}Y.size>1&&Y.has("")&&Y.delete("");const he=[...Y.values()];return n.set(P,he),he}intersects(S,F){if(!(S instanceof e))throw new TypeError("a Range is required");return this.set.some(P=>y(P,F)&&S.set.some(B=>y(B,F)&&P.every(M=>B.every(H=>M.intersects(H,F)))))}test(S){if(!S)return!1;if(typeof S=="string")try{S=new o(S,this.options)}catch{return!1}for(let F=0;F<this.set.length;F++)if(Pt(this.set[F],S,this.options))return!0;return!1}}pa=e;const r=ah(),n=new r,a=Rs(),s=_n(),i=gn(),o=Ie(),{safeRe:c,t:u,comparatorTrimReplace:l,tildeTrimReplace:d,caretTrimReplace:f}=Or(),{FLAG_INCLUDE_PRERELEASE:h,FLAG_LOOSE:p}=mn(),m=I=>I.value==="<0.0.0-0",g=I=>I.value==="",y=(I,S)=>{let F=!0;const P=I.slice();let B=P.pop();for(;F&&P.length;)F=P.every(M=>B.intersects(M,S)),B=P.pop();return F},v=(I,S)=>(I=I.replace(c[u.BUILD],""),i("comp",I,S),I=U(I,S),i("caret",I),I=E(I,S),i("tildes",I),I=O(I,S),i("xrange",I),I=ye(I,S),i("stars",I),I),_=I=>!I||I.toLowerCase()==="x"||I==="*",E=(I,S)=>I.trim().split(/\s+/).map(F=>$(F,S)).join(" "),$=(I,S)=>{const F=S.loose?c[u.TILDELOOSE]:c[u.TILDE];return I.replace(F,(P,B,M,H,Q)=>{i("tilde",I,P,B,M,H,Q);let Y;return _(B)?Y="":_(M)?Y=`>=${B}.0.0 <${+B+1}.0.0-0`:_(H)?Y=`>=${B}.${M}.0 <${B}.${+M+1}.0-0`:Q?(i("replaceTilde pr",Q),Y=`>=${B}.${M}.${H}-${Q} <${B}.${+M+1}.0-0`):Y=`>=${B}.${M}.${H} <${B}.${+M+1}.0-0`,i("tilde return",Y),Y})},U=(I,S)=>I.trim().split(/\s+/).map(F=>z(F,S)).join(" "),z=(I,S)=>{i("caret",I,S);const F=S.loose?c[u.CARETLOOSE]:c[u.CARET],P=S.includePrerelease?"-0":"";return I.replace(F,(B,M,H,Q,Y)=>{i("caret",I,B,M,H,Q,Y);let se;return _(M)?se="":_(H)?se=`>=${M}.0.0${P} <${+M+1}.0.0-0`:_(Q)?M==="0"?se=`>=${M}.${H}.0${P} <${M}.${+H+1}.0-0`:se=`>=${M}.${H}.0${P} <${+M+1}.0.0-0`:Y?(i("replaceCaret pr",Y),M==="0"?H==="0"?se=`>=${M}.${H}.${Q}-${Y} <${M}.${H}.${+Q+1}-0`:se=`>=${M}.${H}.${Q}-${Y} <${M}.${+H+1}.0-0`:se=`>=${M}.${H}.${Q}-${Y} <${+M+1}.0.0-0`):(i("no pr"),M==="0"?H==="0"?se=`>=${M}.${H}.${Q}${P} <${M}.${H}.${+Q+1}-0`:se=`>=${M}.${H}.${Q}${P} <${M}.${+H+1}.0-0`:se=`>=${M}.${H}.${Q} <${+M+1}.0.0-0`),i("caret return",se),se})},O=(I,S)=>(i("replaceXRanges",I,S),I.split(/\s+/).map(F=>oe(F,S)).join(" ")),oe=(I,S)=>{I=I.trim();const F=S.loose?c[u.XRANGELOOSE]:c[u.XRANGE];return I.replace(F,(P,B,M,H,Q,Y)=>{i("xRange",I,P,B,M,H,Q,Y);const se=_(M),he=se||_(H),ne=he||_(Q),Je=ne;return B==="="&&Je&&(B=""),Y=S.includePrerelease?"-0":"",se?B===">"||B==="<"?P="<0.0.0-0":P="*":B&&Je?(he&&(H=0),Q=0,B===">"?(B=">=",he?(M=+M+1,H=0,Q=0):(H=+H+1,Q=0)):B==="<="&&(B="<",he?M=+M+1:H=+H+1),B==="<"&&(Y="-0"),P=`${B+M}.${H}.${Q}${Y}`):he?P=`>=${M}.0.0${Y} <${+M+1}.0.0-0`:ne&&(P=`>=${M}.${H}.0${Y} <${M}.${+H+1}.0-0`),i("xRange return",P),P})},ye=(I,S)=>(i("replaceStars",I,S),I.trim().replace(c[u.STAR],"")),Me=(I,S)=>(i("replaceGTE0",I,S),I.trim().replace(c[S.includePrerelease?u.GTE0PRE:u.GTE0],"")),Ue=I=>(S,F,P,B,M,H,Q,Y,se,he,ne,Je)=>(_(P)?F="":_(B)?F=`>=${P}.0.0${I?"-0":""}`:_(M)?F=`>=${P}.${B}.0${I?"-0":""}`:H?F=`>=${F}`:F=`>=${F}${I?"-0":""}`,_(se)?Y="":_(he)?Y=`<${+se+1}.0.0-0`:_(ne)?Y=`<${se}.${+he+1}.0-0`:Je?Y=`<=${se}.${he}.${ne}-${Je}`:I?Y=`<${se}.${he}.${+ne+1}-0`:Y=`<=${Y}`,`${F} ${Y}`.trim()),Pt=(I,S,F)=>{for(let P=0;P<I.length;P++)if(!I[P].test(S))return!1;if(S.prerelease.length&&!F.includePrerelease){for(let P=0;P<I.length;P++)if(i(I[P].semver),I[P].semver!==s.ANY&&I[P].semver.prerelease.length>0){const B=I[P].semver;if(B.major===S.major&&B.minor===S.minor&&B.patch===S.patch)return!0}return!1}return!0};return pa}var ma,go;function _n(){if(go)return ma;go=1;const t=Symbol("SemVer ANY");class e{static get ANY(){return t}constructor(l,d){if(d=r(d),l instanceof e){if(l.loose===!!d.loose)return l;l=l.value}l=l.trim().split(/\s+/).join(" "),i("comparator",l,d),this.options=d,this.loose=!!d.loose,this.parse(l),this.semver===t?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(l){const d=this.options.loose?n[a.COMPARATORLOOSE]:n[a.COMPARATOR],f=l.match(d);if(!f)throw new TypeError(`Invalid comparator: ${l}`);this.operator=f[1]!==void 0?f[1]:"",this.operator==="="&&(this.operator=""),f[2]?this.semver=new o(f[2],this.options.loose):this.semver=t}toString(){return this.value}test(l){if(i("Comparator.test",l,this.options.loose),this.semver===t||l===t)return!0;if(typeof l=="string")try{l=new o(l,this.options)}catch{return!1}return s(l,this.operator,this.semver,this.options)}intersects(l,d){if(!(l instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(l.value,d).test(this.value):l.operator===""?l.value===""?!0:new c(this.value,d).test(l.semver):(d=r(d),d.includePrerelease&&(this.value==="<0.0.0-0"||l.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||l.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&l.operator.startsWith(">")||this.operator.startsWith("<")&&l.operator.startsWith("<")||this.semver.version===l.semver.version&&this.operator.includes("=")&&l.operator.includes("=")||s(this.semver,"<",l.semver,d)&&this.operator.startsWith(">")&&l.operator.startsWith("<")||s(this.semver,">",l.semver,d)&&this.operator.startsWith("<")&&l.operator.startsWith(">")))}}ma=e;const r=Rs(),{safeRe:n,t:a}=Or(),s=ru(),i=gn(),o=Ie(),c=Ve();return ma}var ga,yo;function vn(){if(yo)return ga;yo=1;const t=Ve();return ga=(r,n,a)=>{try{n=new t(n,a)}catch{return!1}return n.test(r)},ga}var ya,_o;function sh(){if(_o)return ya;_o=1;const t=Ve();return ya=(r,n)=>new t(r,n).set.map(a=>a.map(s=>s.value).join(" ").trim().split(" ")),ya}var _a,vo;function ih(){if(vo)return _a;vo=1;const t=Ie(),e=Ve();return _a=(n,a,s)=>{let i=null,o=null,c=null;try{c=new e(a,s)}catch{return null}return n.forEach(u=>{c.test(u)&&(!i||o.compare(u)===-1)&&(i=u,o=new t(i,s))}),i},_a}var va,wo;function oh(){if(wo)return va;wo=1;const t=Ie(),e=Ve();return va=(n,a,s)=>{let i=null,o=null,c=null;try{c=new e(a,s)}catch{return null}return n.forEach(u=>{c.test(u)&&(!i||o.compare(u)===1)&&(i=u,o=new t(i,s))}),i},va}var wa,bo;function ch(){if(bo)return wa;bo=1;const t=Ie(),e=Ve(),r=yn();return wa=(a,s)=>{a=new e(a,s);let i=new t("0.0.0");if(a.test(i)||(i=new t("0.0.0-0"),a.test(i)))return i;i=null;for(let o=0;o<a.set.length;++o){const c=a.set[o];let u=null;c.forEach(l=>{const d=new t(l.semver.version);switch(l.operator){case">":d.prerelease.length===0?d.patch++:d.prerelease.push(0),d.raw=d.format();case"":case">=":(!u||r(d,u))&&(u=d);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${l.operator}`)}}),u&&(!i||r(i,u))&&(i=u)}return i&&a.test(i)?i:null},wa}var ba,Eo;function uh(){if(Eo)return ba;Eo=1;const t=Ve();return ba=(r,n)=>{try{return new t(r,n).range||"*"}catch{return null}},ba}var Ea,So;function Ps(){if(So)return Ea;So=1;const t=Ie(),e=_n(),{ANY:r}=e,n=Ve(),a=vn(),s=yn(),i=$s(),o=Ns(),c=Cs();return Ea=(l,d,f,h)=>{l=new t(l,h),d=new n(d,h);let p,m,g,y,v;switch(f){case">":p=s,m=o,g=i,y=">",v=">=";break;case"<":p=i,m=c,g=s,y="<",v="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(a(l,d,h))return!1;for(let _=0;_<d.set.length;++_){const E=d.set[_];let $=null,U=null;if(E.forEach(z=>{z.semver===r&&(z=new e(">=0.0.0")),$=$||z,U=U||z,p(z.semver,$.semver,h)?$=z:g(z.semver,U.semver,h)&&(U=z)}),$.operator===y||$.operator===v||(!U.operator||U.operator===y)&&m(l,U.semver))return!1;if(U.operator===v&&g(l,U.semver))return!1}return!0},Ea}var Sa,To;function lh(){if(To)return Sa;To=1;const t=Ps();return Sa=(r,n,a)=>t(r,n,">",a),Sa}var Ta,xo;function dh(){if(xo)return Ta;xo=1;const t=Ps();return Ta=(r,n,a)=>t(r,n,"<",a),Ta}var xa,Io;function fh(){if(Io)return xa;Io=1;const t=Ve();return xa=(r,n,a)=>(r=new t(r,a),n=new t(n,a),r.intersects(n,a)),xa}var Ia,Ao;function hh(){if(Ao)return Ia;Ao=1;const t=vn(),e=Ze();return Ia=(r,n,a)=>{const s=[];let i=null,o=null;const c=r.sort((f,h)=>e(f,h,a));for(const f of c)t(f,n,a)?(o=f,i||(i=f)):(o&&s.push([i,o]),o=null,i=null);i&&s.push([i,null]);const u=[];for(const[f,h]of s)f===h?u.push(f):!h&&f===c[0]?u.push("*"):h?f===c[0]?u.push(`<=${h}`):u.push(`${f} - ${h}`):u.push(`>=${f}`);const l=u.join(" || "),d=typeof n.raw=="string"?n.raw:String(n);return l.length<d.length?l:n},Ia}var Aa,Oo;function ph(){if(Oo)return Aa;Oo=1;const t=Ve(),e=_n(),{ANY:r}=e,n=vn(),a=Ze(),s=(d,f,h={})=>{if(d===f)return!0;d=new t(d,h),f=new t(f,h);let p=!1;e:for(const m of d.set){for(const g of f.set){const y=c(m,g,h);if(p=p||y!==null,y)continue e}if(p)return!1}return!0},i=[new e(">=0.0.0-0")],o=[new e(">=0.0.0")],c=(d,f,h)=>{if(d===f)return!0;if(d.length===1&&d[0].semver===r){if(f.length===1&&f[0].semver===r)return!0;h.includePrerelease?d=i:d=o}if(f.length===1&&f[0].semver===r){if(h.includePrerelease)return!0;f=o}const p=new Set;let m,g;for(const O of d)O.operator===">"||O.operator===">="?m=u(m,O,h):O.operator==="<"||O.operator==="<="?g=l(g,O,h):p.add(O.semver);if(p.size>1)return null;let y;if(m&&g){if(y=a(m.semver,g.semver,h),y>0)return null;if(y===0&&(m.operator!==">="||g.operator!=="<="))return null}for(const O of p){if(m&&!n(O,String(m),h)||g&&!n(O,String(g),h))return null;for(const oe of f)if(!n(O,String(oe),h))return!1;return!0}let v,_,E,$,U=g&&!h.includePrerelease&&g.semver.prerelease.length?g.semver:!1,z=m&&!h.includePrerelease&&m.semver.prerelease.length?m.semver:!1;U&&U.prerelease.length===1&&g.operator==="<"&&U.prerelease[0]===0&&(U=!1);for(const O of f){if($=$||O.operator===">"||O.operator===">=",E=E||O.operator==="<"||O.operator==="<=",m){if(z&&O.semver.prerelease&&O.semver.prerelease.length&&O.semver.major===z.major&&O.semver.minor===z.minor&&O.semver.patch===z.patch&&(z=!1),O.operator===">"||O.operator===">="){if(v=u(m,O,h),v===O&&v!==m)return!1}else if(m.operator===">="&&!n(m.semver,String(O),h))return!1}if(g){if(U&&O.semver.prerelease&&O.semver.prerelease.length&&O.semver.major===U.major&&O.semver.minor===U.minor&&O.semver.patch===U.patch&&(U=!1),O.operator==="<"||O.operator==="<="){if(_=l(g,O,h),_===O&&_!==g)return!1}else if(g.operator==="<="&&!n(g.semver,String(O),h))return!1}if(!O.operator&&(g||m)&&y!==0)return!1}return!(m&&E&&!g&&y!==0||g&&$&&!m&&y!==0||z||U)},u=(d,f,h)=>{if(!d)return f;const p=a(d.semver,f.semver,h);return p>0?d:p<0||f.operator===">"&&d.operator===">="?f:d},l=(d,f,h)=>{if(!d)return f;const p=a(d.semver,f.semver,h);return p<0?d:p>0||f.operator==="<"&&d.operator==="<="?f:d};return Aa=s,Aa}var Oa,Ro;function mh(){if(Ro)return Oa;Ro=1;const t=Or(),e=mn(),r=Ie(),n=Qc(),a=Wt(),s=Hf(),i=Zf(),o=Vf(),c=Jf(),u=Wf(),l=Kf(),d=Yf(),f=Xf(),h=Ze(),p=Qf(),m=eh(),g=ks(),y=th(),v=rh(),_=yn(),E=$s(),$=eu(),U=tu(),z=Cs(),O=Ns(),oe=ru(),ye=nh(),Me=_n(),Ue=Ve(),Pt=vn(),I=sh(),S=ih(),F=oh(),P=ch(),B=uh(),M=Ps(),H=lh(),Q=dh(),Y=fh(),se=hh(),he=ph();return Oa={parse:a,valid:s,clean:i,inc:o,diff:c,major:u,minor:l,patch:d,prerelease:f,compare:h,rcompare:p,compareLoose:m,compareBuild:g,sort:y,rsort:v,gt:_,lt:E,eq:$,neq:U,gte:z,lte:O,cmp:oe,coerce:ye,Comparator:Me,Range:Ue,satisfies:Pt,toComparators:I,maxSatisfying:S,minSatisfying:F,minVersion:P,validRange:B,outside:M,gtr:H,ltr:Q,intersects:Y,simplifyRange:se,subset:he,SemVer:r,re:t.re,src:t.src,tokens:t.t,SEMVER_SPEC_VERSION:e.SEMVER_SPEC_VERSION,RELEASE_TYPES:e.RELEASE_TYPES,compareIdentifiers:n.compareIdentifiers,rcompareIdentifiers:n.rcompareIdentifiers},Oa}mh();function lt(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(`Invalid identifier format: ${t}`);const[e,r]=t.split(":"),n=r||"latest";if(e.includes("/")){const[a,s]=e.split("/",2);if(!a||!s)throw new Error(`Invalid identifier format: ${t}`);return[a,s,n]}else{if(!e)throw new Error(`Invalid identifier format: ${t}`);return["-",e,n]}}class gh extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}async function L(t,e,r){let n;if(t.ok){r&&(n=await t.text());return}if(t.status===403)try{(await t.json())?.error==="org_scoped_key_requires_workspace"&&(n="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{const o=new Error(`${t.status} ${t.statusText}`);throw o.status=t?.status,o}if(n===void 0)try{n=await t.text()}catch{n=""}const a=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${n}`;if(t.status===409)throw new gh(a);const s=new Error(a);throw s.status=t.status,s}const nu="ERR_CONFLICTING_ENDPOINTS";class yh extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:nu}),this.name="ConflictingEndpointsError"}}function _h(t){return typeof t=="object"&&t!==null&&t.code===nu}var ko="[...]",vh={result:"[Circular]"},rn=[],jt=[];const wh=new TextEncoder;function bh(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function zr(t){return wh.encode(t)}function au(t){if(t&&typeof t=="object"&&t!==null){if(t instanceof Map)return Object.fromEntries(t);if(t instanceof Set)return Array.from(t);if(t instanceof Date)return t.toISOString();if(t instanceof RegExp)return t.toString();if(t instanceof Error)return{name:t.name,message:t.message}}else if(typeof t=="bigint")return t.toString();return t}function Eh(t){return function(e,r){return au(r)}}function Le(t,e,r,n,a){try{const s=JSON.stringify(t,Eh(r),n);return zr(s)}catch(s){if(!s.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
20
- Context: ${e}`:""}`),zr("[Unserializable]");ke("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
21
- Context: ${e}`:""}`),typeof a>"u"&&(a=bh()),Wa(t,"",0,[],void 0,0,a);let i;try{jt.length===0?i=JSON.stringify(t,r,n):i=JSON.stringify(t,Sh(r),n)}catch{return zr("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;rn.length!==0;){const o=rn.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return zr(i)}}function Ra(t,e,r,n){var a=Object.getOwnPropertyDescriptor(n,r);a.get!==void 0?a.configurable?(Object.defineProperty(n,r,{value:t}),rn.push([n,r,e,a])):jt.push([e,r,t]):(n[r]=t,rn.push([n,r,e]))}function Wa(t,e,r,n,a,s,i){s+=1;var o;if(typeof t=="object"&&t!==null){for(o=0;o<n.length;o++)if(n[o]===t){Ra(vh,t,e,a);return}if(typeof i.depthLimit<"u"&&s>i.depthLimit){Ra(ko,t,e,a);return}if(typeof i.edgesLimit<"u"&&r+1>i.edgesLimit){Ra(ko,t,e,a);return}if(n.push(t),Array.isArray(t))for(o=0;o<t.length;o++)Wa(t[o],o,o,n,t,s,i);else{t=au(t);var c=Object.keys(t);for(o=0;o<c.length;o++){var u=c[o];Wa(t[u],u,o,n,t,s,i)}}n.pop()}}function Sh(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(jt.length>0)for(var n=0;n<jt.length;n++){var a=jt[n];if(a[1]===e&&a[0]===r){r=a[2],jt.splice(n,1);break}}return t.call(this,e,r)}}function $o(t,e){const r=Wc(),n=e??Kc(),a=t.extra??{},s=a.metadata;return t.extra={...a,runtime:{...r,...a?.runtime},metadata:{...n,...n.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??n.revision_id}:{},...s}},t}const Th=t=>{const e=t?.toString()??ke("TRACING_SAMPLING_RATE");if(e===void 0)return;const r=parseFloat(e);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},xh=t=>{const r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};async function Ih(t){const e=[];for await(const r of t)e.push(r);return e}function qr(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const Ah=async t=>{if(t?.status===429){const e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(r=>setTimeout(r,e)),!0}return!1};function Co(t){return typeof t=="number"?Number(t.toFixed(4)):t}class Oh{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 r;const n=new Promise(s=>{r=s}),a=Le(e.item,`Serializing run with id: ${e.item.id}`).length;return this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:r,itemPromise:n,size:a}),this.sizeBytes+=a,n}pop({upToSizeBytes:e,upToSize:r}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const n=[];let a=0;for(;a+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<r;){const s=this.items.shift();s&&(n.push(s),a+=s.size,this.sizeBytes-=s.size)}if(n.length===0&&this.items.length>0){const s=this.items.shift();n.push(s),a+=s.size,this.sizeBytes-=s.size}return[n.map(s=>({action:s.action,item:s.payload,otelContext:s.otelContext,apiKey:s.apiKey,apiUrl:s.apiUrl})),()=>n.forEach(s=>s.itemPromiseResolve())]}}const Rh=24*1024*1024,kh=1e4,$h=100,No="https://api.smith.langchain.com";class yr{get _fetch(){return this.fetchImplementation||hf(this.debug)}constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"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 Oh}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:et("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:et("LANGSMITH_DEBUG")==="true"});const r=yr.getDefaultClientConfig();if(this.tracingSampleRate=Th(e.tracingSamplingRate),this.apiUrl=qr(e.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=qr(e.apiKey??r.apiKey),this.webUrl=qr(e.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=qr(e.workspaceId??ke("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new Pi({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.batchIngestCaller=new Pi({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:Ah,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??r.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??r.hideOutputs,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,Yc()&&(this.langSmithToOTELTranslator=new kf),this.cachedLSEnvVarsForMetadata=Kc()}static getDefaultClientConfig(){const e=ke("API_KEY"),r=ke("ENDPOINT")??No,n=ke("HIDE_INPUTS")==="true",a=ke("HIDE_OUTPUTS")==="true";return{apiUrl:r,apiKey:e,webUrl:void 0,hideInputs:n,hideOutputs:a}}getHostUrl(){return this.webUrl?this.webUrl:xh(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/${Zc}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){const r={...e};return r.inputs!==void 0&&(r.inputs=await this.processInputs(r.inputs)),r.outputs!==void 0&&(r.outputs=await this.processOutputs(r.outputs)),r}async _getResponse(e,r){const n=r?.toString()??"",a=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{const i=await this._fetch(a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(i,`fetch ${e}`),i})}async _get(e,r){return(await this._getResponse(e,r)).json()}async*_getPaginated(e,r=new URLSearchParams,n){let a=Number(r.get("offset"))||0;const s=Number(r.get("limit"))||100;for(;;){r.set("offset",String(a)),r.set("limit",String(s));const i=`${this.apiUrl}${e}?${r}`,o=await this.caller.call(async()=>{const u=await this._fetch(i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(u,`fetch ${e}`),u}),c=n?n(await o.json()):await o.json();if(c.length===0||(yield c,c.length<s))break;a+=c.length}}async*_getCursorPaginatedList(e,r=null,n="POST",a="runs"){const s=r?{...r}:{};for(;;){const i=JSON.stringify(s),c=await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await L(l,`fetch ${e}`),l})).json();if(!c||!c[a])break;yield c[a];const u=c.cursors;if(!u||!u.next)break;s.cursor=u.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,r=!1){if(this.tracingSampleRate===void 0)return e;if(r){const n=[];for(const a of e)this.filteredPostUuids.has(a.trace_id)?a.id===a.trace_id&&this.filteredPostUuids.delete(a.trace_id):n.push(a);return n}else{const n=[];for(const a of e){const s=a.trace_id??a.id;this.filteredPostUuids.has(s)||(a.id===s?this._shouldSample()?n.push(a):this.filteredPostUuids.add(s):n.push(a))}return n}}async _getBatchSizeLimitBytes(){const e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e.batch_ingest_config?.size_limit_bytes??Rh}async _getBatchSizeLimit(){const e=await this._ensureServerInfo();return this.batchSizeLimit??e.batch_ingest_config?.size_limit??$h}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r}){const n=[];for(;this.autoBatchQueue.items.length>0;){const[a,s]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:r});if(!a.length){s();break}const i=a.reduce((u,l)=>{const d=l.apiUrl??this.apiUrl,f=l.apiKey??this.apiKey,p=l.apiKey===this.apiKey&&l.apiUrl===this.apiUrl?"default":`${d}|${f}`;return u[p]||(u[p]=[]),u[p].push(l),u},{}),o=[];for(const[u,l]of Object.entries(i)){const d=this._processBatch(l,{apiUrl:u==="default"?void 0:u.split("|")[0],apiKey:u==="default"?void 0:u.split("|")[1]});o.push(d)}const c=Promise.all(o).finally(s);n.push(c)}return Promise.all(n)}async _processBatch(e,r){if(e.length)try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{const n={runCreates:e.filter(s=>s.action==="create").map(s=>s.item),runUpdates:e.filter(s=>s.action==="update").map(s=>s.item)},a=await this._ensureServerInfo();if(a?.batch_ingest_config?.use_multipart_endpoint){const s=a?.instance_flags?.gzip_body_enabled;await this.multipartIngestRuns(n,{...r,useGzip:s})}else await this.batchIngestRuns(n,r)}}catch(n){console.error("Error exporting batch:",n)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){const r=new Map,n=[];for(const a of e)a.item.id&&a.otelContext&&(r.set(a.item.id,a.otelContext),a.action==="create"?n.push({operation:"post",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}):n.push({operation:"patch",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}));this.langSmithToOTELTranslator.exportBatch(n,r)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=$o(e.item,this.cachedLSEnvVarsForMetadata);const r=this.autoBatchQueue.push(e);if(this.manualFlushMode)return r;const n=await this._getBatchSizeLimitBytes(),a=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>a)&&this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:a}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:a})},this.autoBatchAggregationDelayMs)),r}async _getServerInfo(){const r=await(await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(kh),...this.fetchOptions});return await L(n,"get server info"),n})).json();return this.debug&&console.log(`
16
+ Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function $c(t){if(typeof t=="string")return new $t(t);if(dn(t))return t;if(Array.isArray(t)){const[e,r]=t;return xn({type:e,content:r})}else if(_s(t)){const{role:e,...r}=t;return xn({...r,type:e})}else return xn(t)}function xs(t,e="Human",r="AI"){const n=[];for(const a of t){let s;if(a._getType()==="human")s=e;else if(a._getType()==="ai")s=r;else if(a._getType()==="system")s="System";else if(a._getType()==="tool")s="Tool";else if(a._getType()==="generic")s=a.role;else throw new Error(`Got unsupported message type: ${a._getType()}`);const i=a.name?`${a.name}, `:"",o=typeof a.content=="string"?a.content:JSON.stringify(a.content,null,2);n.push(`${s}: ${i}${o}`)}return n.join(`
17
+ `)}function pd(t){if(t.data!==void 0)return t;{const e=t;return{type:e.type,data:{content:e.text,role:e.role,name:void 0,tool_call_id:void 0}}}}function Is(t){const e=pd(t);switch(e.type){case"human":return new $t(e.data);case"ai":return new xt(e.data);case"system":return new ot(e.data);case"function":if(e.data.name===void 0)throw new Error("Name must be defined for function messages");return new Sr(e.data);case"tool":if(e.data.tool_call_id===void 0)throw new Error("Tool call ID must be defined for tool messages");return new Rt(e.data);case"generic":if(e.data.role===void 0)throw new Error("Role must be defined for chat messages");return new Vt(e.data);default:throw new Error(`Got unexpected type: ${e.type}`)}}function kc(t){return t.map(Is)}function Cc(t){return t.map(e=>e.toDict())}function Qr(t){const e=t._getType();if(e==="human")return new xr({...t});if(e==="ai"){let r={...t};return"tool_calls"in r&&(r={...r,tool_call_chunks:r.tool_calls?.map(n=>({...n,type:"tool_call_chunk",index:void 0,args:JSON.stringify(n.args)}))}),new Ot({...r})}else{if(e==="system")return new It({...t});if(e==="function")return new Tr({...t});if(Vt.isInstance(t))return new Er({...t});throw new Error("Unknown message type.")}}const Nc=Symbol.for("ls:tracing_async_local_storage"),sr=Symbol.for("lc:context_variables"),md=t=>{globalThis[Nc]=t},mr=()=>globalThis[Nc];var gd={},_d={};me(_d,{getEnv:()=>Dc,getEnvironmentVariable:()=>bt,getRuntimeEnvironment:()=>Uc,isBrowser:()=>Pc,isDeno:()=>hn,isJsDom:()=>Mc,isNode:()=>jc,isWebWorker:()=>Lc});const Pc=()=>typeof window<"u"&&typeof window.document<"u",Lc=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Mc=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),hn=()=>typeof Deno<"u",jc=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!hn(),Dc=()=>{let t;return Pc()?t="browser":jc()?t="node":Lc()?t="webworker":Mc()?t="jsdom":hn()?t="deno":t="other",t};let In;function Uc(){return In===void 0&&(In={library:"langchain-js",runtime:Dc()}),In}function bt(t){try{return typeof process<"u"?gd?.[t]:hn()?Deno?.env.get(t):void 0}catch{return}}const yd=/^(?:[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 ir(t){return typeof t=="string"&&yd.test(t)}function vd(t){if(!ir(t))throw TypeError("Invalid UUID");var e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}var ye=[];for(var An=0;An<256;++An)ye.push((An+256).toString(16).slice(1));function Fc(t,e=0){return(ye[t[e+0]]+ye[t[e+1]]+ye[t[e+2]]+ye[t[e+3]]+"-"+ye[t[e+4]]+ye[t[e+5]]+"-"+ye[t[e+6]]+ye[t[e+7]]+"-"+ye[t[e+8]]+ye[t[e+9]]+"-"+ye[t[e+10]]+ye[t[e+11]]+ye[t[e+12]]+ye[t[e+13]]+ye[t[e+14]]+ye[t[e+15]]).toLowerCase()}var Mr,wd=new Uint8Array(16);function bd(){if(!Mr&&(Mr=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Mr))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Mr(wd)}function Ed(t){t=unescape(encodeURIComponent(t));for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var Sd="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Td="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function xd(t,e,r){function n(a,s,i,o){var c;if(typeof a=="string"&&(a=Ed(a)),typeof s=="string"&&(s=vd(s)),((c=s)===null||c===void 0?void 0:c.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var u=new Uint8Array(16+a.length);if(u.set(s),u.set(a,s.length),u=r(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,i){o=o||0;for(var l=0;l<16;++l)i[o+l]=u[l];return i}return Fc(u)}try{n.name=t}catch{}return n.DNS=Sd,n.URL=Td,n}var Id=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const pi={randomUUID:Id};function Se(t,e,r){if(pi.randomUUID&&!t)return pi.randomUUID();t=t||{};var n=t.random||(t.rng||bd)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,Fc(n)}function Ad(t,e,r,n){switch(t){case 0:return e&r^~e&n;case 1:return e^r^n;case 2:return e&r^e&n^r&n;case 3:return e^r^n}}function Rn(t,e){return t<<e|t>>>32-e}function Rd(t){var e=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof t=="string"){var n=unescape(encodeURIComponent(t));t=[];for(var a=0;a<n.length;++a)t.push(n.charCodeAt(a))}else Array.isArray(t)||(t=Array.prototype.slice.call(t));t.push(128);for(var s=t.length/4+2,i=Math.ceil(s/16),o=new Array(i),c=0;c<i;++c){for(var u=new Uint32Array(16),l=0;l<16;++l)u[l]=t[c*64+l*4]<<24|t[c*64+l*4+1]<<16|t[c*64+l*4+2]<<8|t[c*64+l*4+3];o[c]=u}o[i-1][14]=(t.length-1)*8/Math.pow(2,32),o[i-1][14]=Math.floor(o[i-1][14]),o[i-1][15]=(t.length-1)*8&4294967295;for(var d=0;d<i;++d){for(var f=new Uint32Array(80),h=0;h<16;++h)f[h]=o[d][h];for(var p=16;p<80;++p)f[p]=Rn(f[p-3]^f[p-8]^f[p-14]^f[p-16],1);for(var g=r[0],m=r[1],_=r[2],w=r[3],y=r[4],I=0;I<80;++I){var C=Math.floor(I/20),B=Rn(g,5)+Ad(C,m,_,w)+y+e[C]+f[I]>>>0;y=w,w=_,_=Rn(m,30)>>>0,m=g,g=B}r[0]=r[0]+g>>>0,r[1]=r[1]+m>>>0,r[2]=r[2]+_>>>0,r[3]=r[3]+w>>>0,r[4]=r[4]+y>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,r[0]&255,r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,r[1]&255,r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,r[2]&255,r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,r[3]&255,r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,r[4]&255]}var mi=xd("v5",80,Rd),Od={};me(Od,{BaseCallbackHandler:()=>Ir,callbackHandlerPrefersStreaming:()=>kd,isBaseCallbackHandler:()=>Bc});var $d=class{};function kd(t){return"lc_prefer_streaming"in t&&t.lc_prefer_streaming}var Ir=class extends $d{lc_serializable=!1;get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,fs(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=bt("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(t){super(),this.lc_kwargs=t||{},t&&(this.ignoreLLM=t.ignoreLLM??this.ignoreLLM,this.ignoreChain=t.ignoreChain??this.ignoreChain,this.ignoreAgent=t.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=t.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=t.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=t.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(t._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return fr.prototype.toJSON.call(this)}toJSONNotImplemented(){return fr.prototype.toJSONNotImplemented.call(this)}static fromMethods(t){class e extends Ir{name=Se();constructor(){super(),Object.assign(this,t)}}return new e}};const Bc=t=>{const e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},Cd="gen_ai.operation.name",Nd="gen_ai.system",gi="gen_ai.request.model",Pd="gen_ai.response.model",_i="gen_ai.usage.input_tokens",yi="gen_ai.usage.output_tokens",vi="gen_ai.usage.total_tokens",Ld="gen_ai.request.max_tokens",Md="gen_ai.request.temperature",jd="gen_ai.request.top_p",Dd="gen_ai.request.frequency_penalty",Ud="gen_ai.request.presence_penalty",Fd="gen_ai.response.finish_reasons",Bd="gen_ai.prompt",zd="gen_ai.completion",qd="gen_ai.request.extra_query",Gd="gen_ai.request.extra_body",Hd="gen_ai.serialized.name",Zd="gen_ai.serialized.signature",Vd="gen_ai.serialized.doc",Wd="gen_ai.response.id",Jd="gen_ai.response.service_tier",Kd="gen_ai.response.system_fingerprint",Yd="gen_ai.usage.input_token_details",Xd="gen_ai.usage.output_token_details",Qd="langsmith.trace.session_id",ef="langsmith.trace.session_name",tf="langsmith.span.kind",rf="langsmith.trace.name",nf="langsmith.metadata",wi="langsmith.span.tags",af="langsmith.request.streaming",sf="langsmith.request.headers",of=(...t)=>fetch(...t),zc=Symbol.for("ls:fetch_implementation"),cf=()=>{const t=globalThis[zc];return t?typeof t=="function"&&"Headers"in t&&"Request"in t&&"Response"in t:!1},uf=t=>async(...e)=>{if(t||Oe("DEBUG")==="true"){const[n,a]=e;console.log(`→ ${a?.method||"GET"} ${n}`)}const r=await(globalThis[zc]??of)(...e);return(t||Oe("DEBUG")==="true")&&console.log(`← ${r.status} ${r.statusText} ${r.url}`),r},qc=()=>Oe("PROJECT")??Qe("LANGCHAIN_SESSION")??"default",Gc="0.3.79";var Za={};let We;const lf=()=>typeof window<"u"&&typeof window.document<"u",df=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",ff=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Hc=()=>typeof Deno<"u",hf=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Hc(),Zc=()=>We||(typeof Bun<"u"?We="bun":lf()?We="browser":hf()?We="node":df()?We="webworker":ff()?We="jsdom":Hc()?We="deno":We="other",We);let On;function Vc(){if(On===void 0){const t=Zc(),e=mf();On={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:Gc,...e}}return On}function Wc(){const t=pf(),e={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[n,a]of Object.entries(t))typeof a=="string"&&!r.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?e.revision_id=a:e[n]=a);return e}function pf(){const t={};try{if(typeof process<"u"&&Za)for(const[e,r]of Object.entries(Za))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&r!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof r=="string"?t[e]=r.slice(0,2)+"*".repeat(r.length-4)+r.slice(-2):t[e]=r)}catch{}return t}function Qe(t){try{return typeof process<"u"?Za?.[t]:void 0}catch{return}}function Oe(t){return Qe(`LANGSMITH_${t}`)||Qe(`LANGCHAIN_${t}`)}let $n;function mf(){if($n!==void 0)return $n;const t=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(const r of t){const n=Qe(r);n!==void 0&&(e[r]=n)}return $n=e,e}function Jc(){return Qe("OTEL_ENABLED")==="true"||Oe("OTEL_ENABLED")==="true"}class gf{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...r){!this.hasWarned&&Jc()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let n;if(r.length===1&&typeof r[0]=="function"?n=r[0]:r.length===2&&typeof r[1]=="function"?n=r[1]:r.length===3&&typeof r[2]=="function"&&(n=r[2]),typeof n=="function")return n()}}class _f{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new gf})}getTracer(e,r){return this.mockTracer}getActiveSpan(){}setSpan(e,r){return e}getSpan(e){}setSpanContext(e,r){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}}class yf{active(){return{}}with(e,r){return r()}}const kn=Symbol.for("ls:otel_trace"),Cn=Symbol.for("ls:otel_context"),bi=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),vf=new _f,wf=new yf;class bf{getTraceInstance(){return globalThis[kn]??vf}getContextInstance(){return globalThis[Cn]??wf}initializeGlobalInstances(e){globalThis[kn]===void 0&&(globalThis[kn]=e.trace),globalThis[Cn]===void 0&&(globalThis[Cn]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[bi]=e}getDefaultOTLPTracerComponents(){return globalThis[bi]??void 0}}const As=new bf;function Kc(){return As.getTraceInstance()}function Ef(){return As.getContextInstance()}function Sf(){return As.getDefaultOTLPTracerComponents()}const Tf={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function xf(t){return Tf[t]||t}class If{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,r){for(const n of e)try{if(!n.run)continue;if(n.operation==="post"){const a=this.createSpanForRun(n,n.run,r.get(n.id));a&&!n.run.end_time&&this.spans.set(n.id,a)}else this.updateSpanForRun(n,n.run)}catch(a){console.error(`Error processing operation ${n.id}:`,a)}}createSpanForRun(e,r,n){const a=n&&Kc().getSpan(n);if(a)try{return this.finishSpanSetup(a,r,e)}catch(s){console.error(`Failed to create span for run ${e.id}:`,s);return}}finishSpanSetup(e,r,n){return this.setSpanAttributes(e,r,n),r.error?(e.setStatus({code:2}),e.recordException(new Error(r.error))):e.setStatus({code:1}),r.end_time&&e.end(new Date(r.end_time)),e}updateSpanForRun(e,r){try{const n=this.spans.get(e.id);if(!n){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(n,r,e),r.error?(n.setStatus({code:2}),n.recordException(new Error(r.error))):n.setStatus({code:1});const a=r.end_time;a&&(n.end(new Date(a)),this.spans.delete(e.id))}catch(n){console.error(`Failed to update span for run ${e.id}:`,n)}}extractModelName(e){if(e.extra?.metadata){const r=e.extra.metadata;if(r.ls_model_name)return r.ls_model_name;if(r.invocation_params){const n=r.invocation_params;if(n.model)return n.model;if(n.model_name)return n.model_name}}}setSpanAttributes(e,r,n){if("run_type"in r&&r.run_type){e.setAttribute(tf,r.run_type);const o=xf(r.run_type||"chain");e.setAttribute(Cd,o)}"name"in r&&r.name&&e.setAttribute(rf,r.name),"session_id"in r&&r.session_id&&e.setAttribute(Qd,r.session_id),"session_name"in r&&r.session_name&&e.setAttribute(ef,r.session_name),this.setGenAiSystem(e,r);const a=this.extractModelName(r);a&&e.setAttribute(gi,a),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&e.setAttribute(_i,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&e.setAttribute(yi,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&e.setAttribute(vi,r.total_tokens),this.setInvocationParameters(e,r);const s=r.extra?.metadata||{};for(const[o,c]of Object.entries(s))c!=null&&e.setAttribute(`${nf}.${o}`,String(c));const i=r.tags;if(i&&Array.isArray(i)?e.setAttribute(wi,i.join(", ")):i&&e.setAttribute(wi,String(i)),"serialized"in r&&typeof r.serialized=="object"){const o=r.serialized;o.name&&e.setAttribute(Hd,String(o.name)),o.signature&&e.setAttribute(Zd,String(o.signature)),o.doc&&e.setAttribute(Vd,String(o.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,r){let n="langchain";const a=this.extractModelName(r);if(a){const s=a.toLowerCase();s.includes("anthropic")||s.startsWith("claude")?n="anthropic":s.includes("bedrock")?n="aws.bedrock":s.includes("azure")&&s.includes("openai")?n="az.ai.openai":s.includes("azure")&&s.includes("inference")?n="az.ai.inference":s.includes("cohere")?n="cohere":s.includes("deepseek")?n="deepseek":s.includes("gemini")?n="gemini":s.includes("groq")?n="groq":s.includes("watson")||s.includes("ibm")?n="ibm.watsonx.ai":s.includes("mistral")?n="mistral_ai":s.includes("gpt")||s.includes("openai")?n="openai":s.includes("perplexity")||s.includes("sonar")?n="perplexity":s.includes("vertex")?n="vertex_ai":(s.includes("xai")||s.includes("grok"))&&(n="xai")}e.setAttribute(Nd,n)}setInvocationParameters(e,r){if(!r.extra?.metadata?.invocation_params)return;const n=r.extra.metadata.invocation_params;n.max_tokens!==void 0&&e.setAttribute(Ld,n.max_tokens),n.temperature!==void 0&&e.setAttribute(Md,n.temperature),n.top_p!==void 0&&e.setAttribute(jd,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(Dd,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(Ud,n.presence_penalty)}setIOAttributes(e,r){if(r.run.inputs)try{const n=r.run.inputs;typeof n=="object"&&n!==null&&(n.model&&Array.isArray(n.messages)&&e.setAttribute(gi,n.model),n.stream!==void 0&&e.setAttribute(af,n.stream),n.extra_headers&&e.setAttribute(sf,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(qd,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(Gd,JSON.stringify(n.extra_body))),e.setAttribute(Bd,JSON.stringify(n))}catch(n){console.debug(`Failed to process inputs for run ${r.id}`,n)}if(r.run.outputs)try{const n=r.run.outputs,a=this.getUnifiedRunTokens(n);if(a&&(e.setAttribute(_i,a[0]),e.setAttribute(yi,a[1]),e.setAttribute(vi,a[0]+a[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(Pd,String(n.model)),n.id&&e.setAttribute(Wd,n.id),n.choices&&Array.isArray(n.choices)){const s=n.choices.map(i=>i.finish_reason).filter(i=>i).map(String);s.length>0&&e.setAttribute(Fd,s.join(", "))}if(n.service_tier&&e.setAttribute(Jd,n.service_tier),n.system_fingerprint&&e.setAttribute(Kd,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){const s=n.usage_metadata;s.input_token_details&&e.setAttribute(Yd,JSON.stringify(s.input_token_details)),s.output_token_details&&e.setAttribute(Xd,JSON.stringify(s.output_token_details))}}e.setAttribute(zd,JSON.stringify(n))}catch(n){console.debug(`Failed to process outputs for run ${r.id}`,n)}}getUnifiedRunTokens(e){if(!e)return null;let r=this.extractUnifiedRunTokens(e.usage_metadata);if(r)return r;const n=Object.keys(e);for(const i of n){const o=e[i];if(!(!o||typeof o!="object")&&(r=this.extractUnifiedRunTokens(o.usage_metadata),r||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(r=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),r)))return r}const a=e.generations||[];if(!Array.isArray(a))return null;const s=Array.isArray(a[0])?a.flat():a;for(const i of s)if(typeof i=="object"&&i.message&&typeof i.message=="object"&&i.message.kwargs&&typeof i.message.kwargs=="object"&&(r=this.extractUnifiedRunTokens(i.message.kwargs.usage_metadata),r))return r;return null}extractUnifiedRunTokens(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}}var Xt={exports:{}},Nn={},Pn,Ei;function Af(){if(Ei)return Pn;Ei=1;function t(e,r){typeof r=="boolean"&&(r={forever:r}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=r||{},this._maxRetryTime=r&&r.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))}return Pn=t,t.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},t.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},t.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var r=new Date().getTime();if(e&&r-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1);else return!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)},n),this._options.unref&&this._timer.unref(),!0},t.prototype.attempt=function(e,r){this._fn=e,r&&(r.timeout&&(this._operationTimeout=r.timeout),r.cb&&(this._operationTimeoutCb=r.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},t.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},t.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},t.prototype.start=t.prototype.try,t.prototype.errors=function(){return this._errors},t.prototype.attempts=function(){return this._attempts},t.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},r=null,n=0,a=0;a<this._errors.length;a++){var s=this._errors[a],i=s.message,o=(e[i]||0)+1;e[i]=o,o>=n&&(r=s,n=o)}return r},Pn}var Si;function Rf(){return Si||(Si=1,(function(t){var e=Af();t.operation=function(r){var n=t.timeouts(r);return new e(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},t.timeouts=function(r){if(r instanceof Array)return[].concat(r);var n={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var a in r)n[a]=r[a];if(n.minTimeout>n.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var s=[],i=0;i<n.retries;i++)s.push(this.createTimeout(i,n));return r&&r.forever&&!s.length&&s.push(this.createTimeout(i,n)),s.sort(function(o,c){return o-c}),s},t.createTimeout=function(r,n){var a=n.randomize?Math.random()+1:1,s=Math.round(a*Math.max(n.minTimeout,1)*Math.pow(n.factor,r));return s=Math.min(s,n.maxTimeout),s},t.wrap=function(r,n,a){if(n instanceof Array&&(a=n,n=null),!a){a=[];for(var s in r)typeof r[s]=="function"&&a.push(s)}for(var i=0;i<a.length;i++){var o=a[i],c=r[o];r[o]=(function(l){var d=t.operation(n),f=Array.prototype.slice.call(arguments,1),h=f.pop();f.push(function(p){d.retry(p)||(p&&(arguments[0]=d.mainError()),h.apply(this,arguments))}),d.attempt(function(){l.apply(r,f)})}).bind(r,c),r[o].options=n}}})(Nn)),Nn}var Ln,Ti;function Of(){return Ti||(Ti=1,Ln=Rf()),Ln}var xi;function $f(){if(xi)return Xt.exports;xi=1;const t=Of(),e=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class r extends Error{constructor(o){super(),o instanceof Error?(this.originalError=o,{message:o}=o):(this.originalError=new Error(o),this.originalError.stack=this.stack),this.name="AbortError",this.message=o}}const n=(i,o,c)=>{const u=c.retries-(o-1);return i.attemptNumber=o,i.retriesLeft=u,i},a=i=>e.includes(i),s=(i,o)=>new Promise((c,u)=>{o={onFailedAttempt:()=>{},retries:10,...o};const l=t.operation(o);l.attempt(async d=>{try{c(await i(d))}catch(f){if(!(f instanceof Error)){u(new TypeError(`Non-error was thrown: "${f}". You should only throw errors.`));return}if(f instanceof r)l.stop(),u(f.originalError);else if(f instanceof TypeError&&!a(f.message))l.stop(),u(f);else{n(f,d,o);try{await o.onFailedAttempt(f)}catch(h){u(h);return}l.retry(f)||u(l.mainError())}}})});return Xt.exports=s,Xt.exports.default=s,Xt.exports.AbortError=r,Xt.exports}var kf=$f();const en=wr(kf);var jr={},Mn={exports:{}},Ii;function Cf(){return Ii||(Ii=1,(function(t){var e=Object.prototype.hasOwnProperty,r="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1));function a(c,u,l){this.fn=c,this.context=u,this.once=l||!1}function s(c,u,l,d,f){if(typeof l!="function")throw new TypeError("The listener must be a function");var h=new a(l,d||c,f),p=r?r+u:u;return c._events[p]?c._events[p].fn?c._events[p]=[c._events[p],h]:c._events[p].push(h):(c._events[p]=h,c._eventsCount++),c}function i(c,u){--c._eventsCount===0?c._events=new n:delete c._events[u]}function o(){this._events=new n,this._eventsCount=0}o.prototype.eventNames=function(){var u=[],l,d;if(this._eventsCount===0)return u;for(d in l=this._events)e.call(l,d)&&u.push(r?d.slice(1):d);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(l)):u},o.prototype.listeners=function(u){var l=r?r+u:u,d=this._events[l];if(!d)return[];if(d.fn)return[d.fn];for(var f=0,h=d.length,p=new Array(h);f<h;f++)p[f]=d[f].fn;return p},o.prototype.listenerCount=function(u){var l=r?r+u:u,d=this._events[l];return d?d.fn?1:d.length:0},o.prototype.emit=function(u,l,d,f,h,p){var g=r?r+u:u;if(!this._events[g])return!1;var m=this._events[g],_=arguments.length,w,y;if(m.fn){switch(m.once&&this.removeListener(u,m.fn,void 0,!0),_){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,l),!0;case 3:return m.fn.call(m.context,l,d),!0;case 4:return m.fn.call(m.context,l,d,f),!0;case 5:return m.fn.call(m.context,l,d,f,h),!0;case 6:return m.fn.call(m.context,l,d,f,h,p),!0}for(y=1,w=new Array(_-1);y<_;y++)w[y-1]=arguments[y];m.fn.apply(m.context,w)}else{var I=m.length,C;for(y=0;y<I;y++)switch(m[y].once&&this.removeListener(u,m[y].fn,void 0,!0),_){case 1:m[y].fn.call(m[y].context);break;case 2:m[y].fn.call(m[y].context,l);break;case 3:m[y].fn.call(m[y].context,l,d);break;case 4:m[y].fn.call(m[y].context,l,d,f);break;default:if(!w)for(C=1,w=new Array(_-1);C<_;C++)w[C-1]=arguments[C];m[y].fn.apply(m[y].context,w)}}return!0},o.prototype.on=function(u,l,d){return s(this,u,l,d,!1)},o.prototype.once=function(u,l,d){return s(this,u,l,d,!0)},o.prototype.removeListener=function(u,l,d,f){var h=r?r+u:u;if(!this._events[h])return this;if(!l)return i(this,h),this;var p=this._events[h];if(p.fn)p.fn===l&&(!f||p.once)&&(!d||p.context===d)&&i(this,h);else{for(var g=0,m=[],_=p.length;g<_;g++)(p[g].fn!==l||f&&!p[g].once||d&&p[g].context!==d)&&m.push(p[g]);m.length?this._events[h]=m.length===1?m[0]:m:i(this,h)}return this},o.prototype.removeAllListeners=function(u){var l;return u?(l=r?r+u:u,this._events[l]&&i(this,l)):(this._events=new n,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,t.exports=o})(Mn)),Mn.exports}var Qt={exports:{}},jn,Ai;function Nf(){return Ai||(Ai=1,jn=(t,e)=>(e=e||(()=>{}),t.then(r=>new Promise(n=>{n(e())}).then(()=>r),r=>new Promise(n=>{n(e())}).then(()=>{throw r})))),jn}var Ri;function Pf(){if(Ri)return Qt.exports;Ri=1;const t=Nf();class e extends Error{constructor(a){super(a),this.name="TimeoutError"}}const r=(n,a,s)=>new Promise((i,o)=>{if(typeof a!="number"||a<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(a===1/0){i(n);return}const c=setTimeout(()=>{if(typeof s=="function"){try{i(s())}catch(d){o(d)}return}const u=typeof s=="string"?s:`Promise timed out after ${a} milliseconds`,l=s instanceof Error?s:new e(u);typeof n.cancel=="function"&&n.cancel(),o(l)},a);t(n.then(i,o),()=>{clearTimeout(c)})});return Qt.exports=r,Qt.exports.default=r,Qt.exports.TimeoutError=e,Qt.exports}var Dr={},Ur={},Oi;function Lf(){if(Oi)return Ur;Oi=1,Object.defineProperty(Ur,"__esModule",{value:!0});function t(e,r,n){let a=0,s=e.length;for(;s>0;){const i=s/2|0;let o=a+i;n(e[o],r)<=0?(a=++o,s-=i+1):s=i}return a}return Ur.default=t,Ur}var $i;function Mf(){if($i)return Dr;$i=1,Object.defineProperty(Dr,"__esModule",{value:!0});const t=Lf();class e{constructor(){this._queue=[]}enqueue(n,a){a=Object.assign({priority:0},a);const s={priority:a.priority,run:n};if(this.size&&this._queue[this.size-1].priority>=a.priority){this._queue.push(s);return}const i=t.default(this._queue,s,(o,c)=>c.priority-o.priority);this._queue.splice(i,0,s)}dequeue(){const n=this._queue.shift();return n?.run}filter(n){return this._queue.filter(a=>a.priority===n.priority).map(a=>a.run)}get size(){return this._queue.length}}return Dr.default=e,Dr}var ki;function jf(){if(ki)return jr;ki=1,Object.defineProperty(jr,"__esModule",{value:!0});const t=Cf(),e=Pf(),r=Mf(),n=()=>{},a=new e.TimeoutError;class s extends t{constructor(o){var c,u,l,d;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=n,this._resolveIdle=n,o=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:r.default},o),!(typeof o.intervalCap=="number"&&o.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(u=(c=o.intervalCap)===null||c===void 0?void 0:c.toString())!==null&&u!==void 0?u:""}\` (${typeof o.intervalCap})`);if(o.interval===void 0||!(Number.isFinite(o.interval)&&o.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(d=(l=o.interval)===null||l===void 0?void 0:l.toString())!==null&&d!==void 0?d:""}\` (${typeof o.interval})`);this._carryoverConcurrencyCount=o.carryoverConcurrencyCount,this._isIntervalIgnored=o.intervalCap===1/0||o.interval===0,this._intervalCap=o.intervalCap,this._interval=o.interval,this._queue=new o.queueClass,this._queueClass=o.queueClass,this.concurrency=o.concurrency,this._timeout=o.timeout,this._throwOnTimeout=o.throwOnTimeout===!0,this._isPaused=o.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=n,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=n,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const o=Date.now();if(this._intervalId===void 0){const c=this._intervalEnd-o;if(c<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},c)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const o=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const c=this._queue.dequeue();return c?(this.emit("active"),c(),o&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(o){if(!(typeof o=="number"&&o>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${o}\` (${typeof o})`);this._concurrency=o,this._processQueue()}async add(o,c={}){return new Promise((u,l)=>{const d=async()=>{this._pendingCount++,this._intervalCount++;try{const f=this._timeout===void 0&&c.timeout===void 0?o():e.default(Promise.resolve(o()),c.timeout===void 0?this._timeout:c.timeout,()=>{(c.throwOnTimeout===void 0?this._throwOnTimeout:c.throwOnTimeout)&&l(a)});u(await f)}catch(f){l(f)}this._next()};this._queue.enqueue(d,c),this._tryToStartAnother(),this.emit("add")})}async addAll(o,c){return Promise.all(o.map(async u=>this.add(u,c)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(o=>{const c=this._resolveEmpty;this._resolveEmpty=()=>{c(),o()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(o=>{const c=this._resolveIdle;this._resolveIdle=()=>{c(),o()}})}get size(){return this._queue.size}sizeBy(o){return this._queue.filter(o).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(o){this._timeout=o}}return jr.default=s,jr}var Df=jf();const nt=wr(Df),Uf=[429,500,502,503,504];let Ci=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}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,"default"in nt?this.queue=new nt.default({concurrency:this.maxConcurrency}):this.queue=new nt({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...r){const n=this.onFailedResponseHook;return this.queue.add(()=>en(()=>e(...r).catch(a=>{throw a instanceof Error?a:new Error(a)}),{async onFailedAttempt(a){if(a.message.startsWith("Cancel")||a.message.startsWith("TimeoutError")||a.name==="TimeoutError"||a.message.startsWith("AbortError")||a?.code==="ECONNABORTED")throw a;const s=a?.response;if(n&&await n(s))return;const i=s?.status??a?.status;if(i&&!Uf.includes(+i))throw a},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,r,...n){return e.signal?Promise.race([this.call(r,...n),new Promise((a,s)=>{e.signal?.addEventListener("abort",()=>{s(new Error("AbortError"))})})]):this.call(r,...n)}};function Ni(t){return typeof t?._getType=="function"}function Pi(t){const e={type:t._getType(),data:{content:t.content}};return t?.additional_kwargs&&Object.keys(t.additional_kwargs).length>0&&(e.data.additional_kwargs={...t.additional_kwargs}),e}const Ff=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function K(t,e){if(!Ff.test(t)){const r=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(r)}return t}const Li={};function Va(t){Li[t]||(console.warn(t),Li[t]=!0)}var Fr={exports:{}},Dn,Mi;function pn(){if(Mi)return Dn;Mi=1;const t="2.0.0",e=256,r=Number.MAX_SAFE_INTEGER||9007199254740991,n=16,a=e-6;return Dn={MAX_LENGTH:e,MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:a,MAX_SAFE_INTEGER:r,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:t,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},Dn}var Un,ji;function mn(){if(ji)return Un;ji=1;var t={};return Un=typeof process=="object"&&t&&t.NODE_DEBUG&&/\bsemver\b/i.test(t.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{},Un}var Di;function Ar(){return Di||(Di=1,(function(t,e){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:a}=pn(),s=mn();e=t.exports={};const i=e.re=[],o=e.safeRe=[],c=e.src=[],u=e.safeSrc=[],l=e.t={};let d=0;const f="[a-zA-Z0-9-]",h=[["\\s",1],["\\d",a],[f,n]],p=m=>{for(const[_,w]of h)m=m.split(`${_}*`).join(`${_}{0,${w}}`).split(`${_}+`).join(`${_}{1,${w}}`);return m},g=(m,_,w)=>{const y=p(_),I=d++;s(m,I,_),l[m]=I,c[I]=_,u[I]=y,i[I]=new RegExp(_,w?"g":void 0),o[I]=new RegExp(y,w?"g":void 0)};g("NUMERICIDENTIFIER","0|[1-9]\\d*"),g("NUMERICIDENTIFIERLOOSE","\\d+"),g("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${f}*`),g("MAINVERSION",`(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})`),g("MAINVERSIONLOOSE",`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})`),g("PRERELEASEIDENTIFIER",`(?:${c[l.NONNUMERICIDENTIFIER]}|${c[l.NUMERICIDENTIFIER]})`),g("PRERELEASEIDENTIFIERLOOSE",`(?:${c[l.NONNUMERICIDENTIFIER]}|${c[l.NUMERICIDENTIFIERLOOSE]})`),g("PRERELEASE",`(?:-(${c[l.PRERELEASEIDENTIFIER]}(?:\\.${c[l.PRERELEASEIDENTIFIER]})*))`),g("PRERELEASELOOSE",`(?:-?(${c[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[l.PRERELEASEIDENTIFIERLOOSE]})*))`),g("BUILDIDENTIFIER",`${f}+`),g("BUILD",`(?:\\+(${c[l.BUILDIDENTIFIER]}(?:\\.${c[l.BUILDIDENTIFIER]})*))`),g("FULLPLAIN",`v?${c[l.MAINVERSION]}${c[l.PRERELEASE]}?${c[l.BUILD]}?`),g("FULL",`^${c[l.FULLPLAIN]}$`),g("LOOSEPLAIN",`[v=\\s]*${c[l.MAINVERSIONLOOSE]}${c[l.PRERELEASELOOSE]}?${c[l.BUILD]}?`),g("LOOSE",`^${c[l.LOOSEPLAIN]}$`),g("GTLT","((?:<|>)?=?)"),g("XRANGEIDENTIFIERLOOSE",`${c[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),g("XRANGEIDENTIFIER",`${c[l.NUMERICIDENTIFIER]}|x|X|\\*`),g("XRANGEPLAIN",`[v=\\s]*(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:${c[l.PRERELEASE]})?${c[l.BUILD]}?)?)?`),g("XRANGEPLAINLOOSE",`[v=\\s]*(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:${c[l.PRERELEASELOOSE]})?${c[l.BUILD]}?)?)?`),g("XRANGE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAIN]}$`),g("XRANGELOOSE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAINLOOSE]}$`),g("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),g("COERCE",`${c[l.COERCEPLAIN]}(?:$|[^\\d])`),g("COERCEFULL",c[l.COERCEPLAIN]+`(?:${c[l.PRERELEASE]})?(?:${c[l.BUILD]})?(?:$|[^\\d])`),g("COERCERTL",c[l.COERCE],!0),g("COERCERTLFULL",c[l.COERCEFULL],!0),g("LONETILDE","(?:~>?)"),g("TILDETRIM",`(\\s*)${c[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",g("TILDE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAIN]}$`),g("TILDELOOSE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAINLOOSE]}$`),g("LONECARET","(?:\\^)"),g("CARETTRIM",`(\\s*)${c[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",g("CARET",`^${c[l.LONECARET]}${c[l.XRANGEPLAIN]}$`),g("CARETLOOSE",`^${c[l.LONECARET]}${c[l.XRANGEPLAINLOOSE]}$`),g("COMPARATORLOOSE",`^${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]})$|^$`),g("COMPARATOR",`^${c[l.GTLT]}\\s*(${c[l.FULLPLAIN]})$|^$`),g("COMPARATORTRIM",`(\\s*)${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]}|${c[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",g("HYPHENRANGE",`^\\s*(${c[l.XRANGEPLAIN]})\\s+-\\s+(${c[l.XRANGEPLAIN]})\\s*$`),g("HYPHENRANGELOOSE",`^\\s*(${c[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[l.XRANGEPLAINLOOSE]})\\s*$`),g("STAR","(<|>)?=?\\s*\\*"),g("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),g("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(Fr,Fr.exports)),Fr.exports}var Fn,Ui;function Rs(){if(Ui)return Fn;Ui=1;const t=Object.freeze({loose:!0}),e=Object.freeze({});return Fn=n=>n?typeof n!="object"?t:n:e,Fn}var Bn,Fi;function Yc(){if(Fi)return Bn;Fi=1;const t=/^[0-9]+$/,e=(n,a)=>{if(typeof n=="number"&&typeof a=="number")return n===a?0:n<a?-1:1;const s=t.test(n),i=t.test(a);return s&&i&&(n=+n,a=+a),n===a?0:s&&!i?-1:i&&!s?1:n<a?-1:1};return Bn={compareIdentifiers:e,rcompareIdentifiers:(n,a)=>e(a,n)},Bn}var zn,Bi;function xe(){if(Bi)return zn;Bi=1;const t=mn(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:r}=pn(),{safeRe:n,t:a}=Ar(),s=Rs(),{compareIdentifiers:i}=Yc();class o{constructor(u,l){if(l=s(l),u instanceof o){if(u.loose===!!l.loose&&u.includePrerelease===!!l.includePrerelease)return u;u=u.version}else if(typeof u!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof u}".`);if(u.length>e)throw new TypeError(`version is longer than ${e} characters`);t("SemVer",u,l),this.options=l,this.loose=!!l.loose,this.includePrerelease=!!l.includePrerelease;const d=u.trim().match(l.loose?n[a.LOOSE]:n[a.FULL]);if(!d)throw new TypeError(`Invalid Version: ${u}`);if(this.raw=u,this.major=+d[1],this.minor=+d[2],this.patch=+d[3],this.major>r||this.major<0)throw new TypeError("Invalid major version");if(this.minor>r||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>r||this.patch<0)throw new TypeError("Invalid patch version");d[4]?this.prerelease=d[4].split(".").map(f=>{if(/^[0-9]+$/.test(f)){const h=+f;if(h>=0&&h<r)return h}return f}):this.prerelease=[],this.build=d[5]?d[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(u){if(t("SemVer.compare",this.version,this.options,u),!(u instanceof o)){if(typeof u=="string"&&u===this.version)return 0;u=new o(u,this.options)}return u.version===this.version?0:this.compareMain(u)||this.comparePre(u)}compareMain(u){return u instanceof o||(u=new o(u,this.options)),this.major<u.major?-1:this.major>u.major?1:this.minor<u.minor?-1:this.minor>u.minor?1:this.patch<u.patch?-1:this.patch>u.patch?1:0}comparePre(u){if(u instanceof o||(u=new o(u,this.options)),this.prerelease.length&&!u.prerelease.length)return-1;if(!this.prerelease.length&&u.prerelease.length)return 1;if(!this.prerelease.length&&!u.prerelease.length)return 0;let l=0;do{const d=this.prerelease[l],f=u.prerelease[l];if(t("prerelease compare",l,d,f),d===void 0&&f===void 0)return 0;if(f===void 0)return 1;if(d===void 0)return-1;if(d===f)continue;return i(d,f)}while(++l)}compareBuild(u){u instanceof o||(u=new o(u,this.options));let l=0;do{const d=this.build[l],f=u.build[l];if(t("build compare",l,d,f),d===void 0&&f===void 0)return 0;if(f===void 0)return 1;if(d===void 0)return-1;if(d===f)continue;return i(d,f)}while(++l)}inc(u,l,d){if(u.startsWith("pre")){if(!l&&d===!1)throw new Error("invalid increment argument: identifier is empty");if(l){const f=`-${l}`.match(this.options.loose?n[a.PRERELEASELOOSE]:n[a.PRERELEASE]);if(!f||f[1]!==l)throw new Error(`invalid identifier: ${l}`)}}switch(u){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",l,d);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",l,d);break;case"prepatch":this.prerelease.length=0,this.inc("patch",l,d),this.inc("pre",l,d);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",l,d),this.inc("pre",l,d);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const f=Number(d)?1:0;if(this.prerelease.length===0)this.prerelease=[f];else{let h=this.prerelease.length;for(;--h>=0;)typeof this.prerelease[h]=="number"&&(this.prerelease[h]++,h=-2);if(h===-1){if(l===this.prerelease.join(".")&&d===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(f)}}if(l){let h=[l,f];d===!1&&(h=[l]),i(this.prerelease[0],l)===0?isNaN(this.prerelease[1])&&(this.prerelease=h):this.prerelease=h}break}default:throw new Error(`invalid increment argument: ${u}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return zn=o,zn}var qn,zi;function Wt(){if(zi)return qn;zi=1;const t=xe();return qn=(r,n,a=!1)=>{if(r instanceof t)return r;try{return new t(r,n)}catch(s){if(!a)return null;throw s}},qn}var Gn,qi;function Bf(){if(qi)return Gn;qi=1;const t=Wt();return Gn=(r,n)=>{const a=t(r,n);return a?a.version:null},Gn}var Hn,Gi;function zf(){if(Gi)return Hn;Gi=1;const t=Wt();return Hn=(r,n)=>{const a=t(r.trim().replace(/^[=v]+/,""),n);return a?a.version:null},Hn}var Zn,Hi;function qf(){if(Hi)return Zn;Hi=1;const t=xe();return Zn=(r,n,a,s,i)=>{typeof a=="string"&&(i=s,s=a,a=void 0);try{return new t(r instanceof t?r.version:r,a).inc(n,s,i).version}catch{return null}},Zn}var Vn,Zi;function Gf(){if(Zi)return Vn;Zi=1;const t=Wt();return Vn=(r,n)=>{const a=t(r,null,!0),s=t(n,null,!0),i=a.compare(s);if(i===0)return null;const o=i>0,c=o?a:s,u=o?s:a,l=!!c.prerelease.length;if(!!u.prerelease.length&&!l){if(!u.patch&&!u.minor)return"major";if(u.compareMain(c)===0)return u.minor&&!u.patch?"minor":"patch"}const f=l?"pre":"";return a.major!==s.major?f+"major":a.minor!==s.minor?f+"minor":a.patch!==s.patch?f+"patch":"prerelease"},Vn}var Wn,Vi;function Hf(){if(Vi)return Wn;Vi=1;const t=xe();return Wn=(r,n)=>new t(r,n).major,Wn}var Jn,Wi;function Zf(){if(Wi)return Jn;Wi=1;const t=xe();return Jn=(r,n)=>new t(r,n).minor,Jn}var Kn,Ji;function Vf(){if(Ji)return Kn;Ji=1;const t=xe();return Kn=(r,n)=>new t(r,n).patch,Kn}var Yn,Ki;function Wf(){if(Ki)return Yn;Ki=1;const t=Wt();return Yn=(r,n)=>{const a=t(r,n);return a&&a.prerelease.length?a.prerelease:null},Yn}var Xn,Yi;function He(){if(Yi)return Xn;Yi=1;const t=xe();return Xn=(r,n,a)=>new t(r,a).compare(new t(n,a)),Xn}var Qn,Xi;function Jf(){if(Xi)return Qn;Xi=1;const t=He();return Qn=(r,n,a)=>t(n,r,a),Qn}var ea,Qi;function Kf(){if(Qi)return ea;Qi=1;const t=He();return ea=(r,n)=>t(r,n,!0),ea}var ta,eo;function Os(){if(eo)return ta;eo=1;const t=xe();return ta=(r,n,a)=>{const s=new t(r,a),i=new t(n,a);return s.compare(i)||s.compareBuild(i)},ta}var ra,to;function Yf(){if(to)return ra;to=1;const t=Os();return ra=(r,n)=>r.sort((a,s)=>t(a,s,n)),ra}var na,ro;function Xf(){if(ro)return na;ro=1;const t=Os();return na=(r,n)=>r.sort((a,s)=>t(s,a,n)),na}var aa,no;function gn(){if(no)return aa;no=1;const t=He();return aa=(r,n,a)=>t(r,n,a)>0,aa}var sa,ao;function $s(){if(ao)return sa;ao=1;const t=He();return sa=(r,n,a)=>t(r,n,a)<0,sa}var ia,so;function Xc(){if(so)return ia;so=1;const t=He();return ia=(r,n,a)=>t(r,n,a)===0,ia}var oa,io;function Qc(){if(io)return oa;io=1;const t=He();return oa=(r,n,a)=>t(r,n,a)!==0,oa}var ca,oo;function ks(){if(oo)return ca;oo=1;const t=He();return ca=(r,n,a)=>t(r,n,a)>=0,ca}var ua,co;function Cs(){if(co)return ua;co=1;const t=He();return ua=(r,n,a)=>t(r,n,a)<=0,ua}var la,uo;function eu(){if(uo)return la;uo=1;const t=Xc(),e=Qc(),r=gn(),n=ks(),a=$s(),s=Cs();return la=(o,c,u,l)=>{switch(c){case"===":return typeof o=="object"&&(o=o.version),typeof u=="object"&&(u=u.version),o===u;case"!==":return typeof o=="object"&&(o=o.version),typeof u=="object"&&(u=u.version),o!==u;case"":case"=":case"==":return t(o,u,l);case"!=":return e(o,u,l);case">":return r(o,u,l);case">=":return n(o,u,l);case"<":return a(o,u,l);case"<=":return s(o,u,l);default:throw new TypeError(`Invalid operator: ${c}`)}},la}var da,lo;function Qf(){if(lo)return da;lo=1;const t=xe(),e=Wt(),{safeRe:r,t:n}=Ar();return da=(s,i)=>{if(s instanceof t)return s;if(typeof s=="number"&&(s=String(s)),typeof s!="string")return null;i=i||{};let o=null;if(!i.rtl)o=s.match(i.includePrerelease?r[n.COERCEFULL]:r[n.COERCE]);else{const h=i.includePrerelease?r[n.COERCERTLFULL]:r[n.COERCERTL];let p;for(;(p=h.exec(s))&&(!o||o.index+o[0].length!==s.length);)(!o||p.index+p[0].length!==o.index+o[0].length)&&(o=p),h.lastIndex=p.index+p[1].length+p[2].length;h.lastIndex=-1}if(o===null)return null;const c=o[2],u=o[3]||"0",l=o[4]||"0",d=i.includePrerelease&&o[5]?`-${o[5]}`:"",f=i.includePrerelease&&o[6]?`+${o[6]}`:"";return e(`${c}.${u}.${l}${d}${f}`,i)},da}var fa,fo;function eh(){if(fo)return fa;fo=1;class t{constructor(){this.max=1e3,this.map=new Map}get(r){const n=this.map.get(r);if(n!==void 0)return this.map.delete(r),this.map.set(r,n),n}delete(r){return this.map.delete(r)}set(r,n){if(!this.delete(r)&&n!==void 0){if(this.map.size>=this.max){const s=this.map.keys().next().value;this.delete(s)}this.map.set(r,n)}return this}}return fa=t,fa}var ha,ho;function Ze(){if(ho)return ha;ho=1;const t=/\s+/g;class e{constructor(E,U){if(U=a(U),E instanceof e)return E.loose===!!U.loose&&E.includePrerelease===!!U.includePrerelease?E:new e(E.raw,U);if(E instanceof s)return this.raw=E.value,this.set=[[E]],this.formatted=void 0,this;if(this.options=U,this.loose=!!U.loose,this.includePrerelease=!!U.includePrerelease,this.raw=E.trim().replace(t," "),this.set=this.raw.split("||").map(P=>this.parseRange(P.trim())).filter(P=>P.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const P=this.set[0];if(this.set=this.set.filter(F=>!g(F[0])),this.set.length===0)this.set=[P];else if(this.set.length>1){for(const F of this.set)if(F.length===1&&m(F[0])){this.set=[F];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let E=0;E<this.set.length;E++){E>0&&(this.formatted+="||");const U=this.set[E];for(let P=0;P<U.length;P++)P>0&&(this.formatted+=" "),this.formatted+=U[P].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(E){const P=((this.options.includePrerelease&&h)|(this.options.loose&&p))+":"+E,F=n.get(P);if(F)return F;const L=this.options.loose,H=L?c[u.HYPHENRANGELOOSE]:c[u.HYPHENRANGE];E=E.replace(H,De(this.options.includePrerelease)),i("hyphen replace",E),E=E.replace(c[u.COMPARATORTRIM],l),i("comparator trim",E),E=E.replace(c[u.TILDETRIM],d),i("tilde trim",E),E=E.replace(c[u.CARETTRIM],f),i("caret trim",E);let Q=E.split(" ").map(ne=>w(ne,this.options)).join(" ").split(/\s+/).map(ne=>Ne(ne,this.options));L&&(Q=Q.filter(ne=>(i("loose invalid filter",ne,this.options),!!ne.match(c[u.COMPARATORLOOSE])))),i("range list",Q);const Y=new Map,se=Q.map(ne=>new s(ne,this.options));for(const ne of se){if(g(ne))return[ne];Y.set(ne.value,ne)}Y.size>1&&Y.has("")&&Y.delete("");const he=[...Y.values()];return n.set(P,he),he}intersects(E,U){if(!(E instanceof e))throw new TypeError("a Range is required");return this.set.some(P=>_(P,U)&&E.set.some(F=>_(F,U)&&P.every(L=>F.every(H=>L.intersects(H,U)))))}test(E){if(!E)return!1;if(typeof E=="string")try{E=new o(E,this.options)}catch{return!1}for(let U=0;U<this.set.length;U++)if(Nt(this.set[U],E,this.options))return!0;return!1}}ha=e;const r=eh(),n=new r,a=Rs(),s=_n(),i=mn(),o=xe(),{safeRe:c,t:u,comparatorTrimReplace:l,tildeTrimReplace:d,caretTrimReplace:f}=Ar(),{FLAG_INCLUDE_PRERELEASE:h,FLAG_LOOSE:p}=pn(),g=x=>x.value==="<0.0.0-0",m=x=>x.value==="",_=(x,E)=>{let U=!0;const P=x.slice();let F=P.pop();for(;U&&P.length;)U=P.every(L=>F.intersects(L,E)),F=P.pop();return U},w=(x,E)=>(x=x.replace(c[u.BUILD],""),i("comp",x,E),x=B(x,E),i("caret",x),x=I(x,E),i("tildes",x),x=R(x,E),i("xrange",x),x=_e(x,E),i("stars",x),x),y=x=>!x||x.toLowerCase()==="x"||x==="*",I=(x,E)=>x.trim().split(/\s+/).map(U=>C(U,E)).join(" "),C=(x,E)=>{const U=E.loose?c[u.TILDELOOSE]:c[u.TILDE];return x.replace(U,(P,F,L,H,Q)=>{i("tilde",x,P,F,L,H,Q);let Y;return y(F)?Y="":y(L)?Y=`>=${F}.0.0 <${+F+1}.0.0-0`:y(H)?Y=`>=${F}.${L}.0 <${F}.${+L+1}.0-0`:Q?(i("replaceTilde pr",Q),Y=`>=${F}.${L}.${H}-${Q} <${F}.${+L+1}.0-0`):Y=`>=${F}.${L}.${H} <${F}.${+L+1}.0-0`,i("tilde return",Y),Y})},B=(x,E)=>x.trim().split(/\s+/).map(U=>z(U,E)).join(" "),z=(x,E)=>{i("caret",x,E);const U=E.loose?c[u.CARETLOOSE]:c[u.CARET],P=E.includePrerelease?"-0":"";return x.replace(U,(F,L,H,Q,Y)=>{i("caret",x,F,L,H,Q,Y);let se;return y(L)?se="":y(H)?se=`>=${L}.0.0${P} <${+L+1}.0.0-0`:y(Q)?L==="0"?se=`>=${L}.${H}.0${P} <${L}.${+H+1}.0-0`:se=`>=${L}.${H}.0${P} <${+L+1}.0.0-0`:Y?(i("replaceCaret pr",Y),L==="0"?H==="0"?se=`>=${L}.${H}.${Q}-${Y} <${L}.${H}.${+Q+1}-0`:se=`>=${L}.${H}.${Q}-${Y} <${L}.${+H+1}.0-0`:se=`>=${L}.${H}.${Q}-${Y} <${+L+1}.0.0-0`):(i("no pr"),L==="0"?H==="0"?se=`>=${L}.${H}.${Q}${P} <${L}.${H}.${+Q+1}-0`:se=`>=${L}.${H}.${Q}${P} <${L}.${+H+1}.0-0`:se=`>=${L}.${H}.${Q} <${+L+1}.0.0-0`),i("caret return",se),se})},R=(x,E)=>(i("replaceXRanges",x,E),x.split(/\s+/).map(U=>oe(U,E)).join(" ")),oe=(x,E)=>{x=x.trim();const U=E.loose?c[u.XRANGELOOSE]:c[u.XRANGE];return x.replace(U,(P,F,L,H,Q,Y)=>{i("xRange",x,P,F,L,H,Q,Y);const se=y(L),he=se||y(H),ne=he||y(Q),Ve=ne;return F==="="&&Ve&&(F=""),Y=E.includePrerelease?"-0":"",se?F===">"||F==="<"?P="<0.0.0-0":P="*":F&&Ve?(he&&(H=0),Q=0,F===">"?(F=">=",he?(L=+L+1,H=0,Q=0):(H=+H+1,Q=0)):F==="<="&&(F="<",he?L=+L+1:H=+H+1),F==="<"&&(Y="-0"),P=`${F+L}.${H}.${Q}${Y}`):he?P=`>=${L}.0.0${Y} <${+L+1}.0.0-0`:ne&&(P=`>=${L}.${H}.0${Y} <${L}.${+H+1}.0-0`),i("xRange return",P),P})},_e=(x,E)=>(i("replaceStars",x,E),x.trim().replace(c[u.STAR],"")),Ne=(x,E)=>(i("replaceGTE0",x,E),x.trim().replace(c[E.includePrerelease?u.GTE0PRE:u.GTE0],"")),De=x=>(E,U,P,F,L,H,Q,Y,se,he,ne,Ve)=>(y(P)?U="":y(F)?U=`>=${P}.0.0${x?"-0":""}`:y(L)?U=`>=${P}.${F}.0${x?"-0":""}`:H?U=`>=${U}`:U=`>=${U}${x?"-0":""}`,y(se)?Y="":y(he)?Y=`<${+se+1}.0.0-0`:y(ne)?Y=`<${se}.${+he+1}.0-0`:Ve?Y=`<=${se}.${he}.${ne}-${Ve}`:x?Y=`<${se}.${he}.${+ne+1}-0`:Y=`<=${Y}`,`${U} ${Y}`.trim()),Nt=(x,E,U)=>{for(let P=0;P<x.length;P++)if(!x[P].test(E))return!1;if(E.prerelease.length&&!U.includePrerelease){for(let P=0;P<x.length;P++)if(i(x[P].semver),x[P].semver!==s.ANY&&x[P].semver.prerelease.length>0){const F=x[P].semver;if(F.major===E.major&&F.minor===E.minor&&F.patch===E.patch)return!0}return!1}return!0};return ha}var pa,po;function _n(){if(po)return pa;po=1;const t=Symbol("SemVer ANY");class e{static get ANY(){return t}constructor(l,d){if(d=r(d),l instanceof e){if(l.loose===!!d.loose)return l;l=l.value}l=l.trim().split(/\s+/).join(" "),i("comparator",l,d),this.options=d,this.loose=!!d.loose,this.parse(l),this.semver===t?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(l){const d=this.options.loose?n[a.COMPARATORLOOSE]:n[a.COMPARATOR],f=l.match(d);if(!f)throw new TypeError(`Invalid comparator: ${l}`);this.operator=f[1]!==void 0?f[1]:"",this.operator==="="&&(this.operator=""),f[2]?this.semver=new o(f[2],this.options.loose):this.semver=t}toString(){return this.value}test(l){if(i("Comparator.test",l,this.options.loose),this.semver===t||l===t)return!0;if(typeof l=="string")try{l=new o(l,this.options)}catch{return!1}return s(l,this.operator,this.semver,this.options)}intersects(l,d){if(!(l instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(l.value,d).test(this.value):l.operator===""?l.value===""?!0:new c(this.value,d).test(l.semver):(d=r(d),d.includePrerelease&&(this.value==="<0.0.0-0"||l.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||l.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&l.operator.startsWith(">")||this.operator.startsWith("<")&&l.operator.startsWith("<")||this.semver.version===l.semver.version&&this.operator.includes("=")&&l.operator.includes("=")||s(this.semver,"<",l.semver,d)&&this.operator.startsWith(">")&&l.operator.startsWith("<")||s(this.semver,">",l.semver,d)&&this.operator.startsWith("<")&&l.operator.startsWith(">")))}}pa=e;const r=Rs(),{safeRe:n,t:a}=Ar(),s=eu(),i=mn(),o=xe(),c=Ze();return pa}var ma,mo;function yn(){if(mo)return ma;mo=1;const t=Ze();return ma=(r,n,a)=>{try{n=new t(n,a)}catch{return!1}return n.test(r)},ma}var ga,go;function th(){if(go)return ga;go=1;const t=Ze();return ga=(r,n)=>new t(r,n).set.map(a=>a.map(s=>s.value).join(" ").trim().split(" ")),ga}var _a,_o;function rh(){if(_o)return _a;_o=1;const t=xe(),e=Ze();return _a=(n,a,s)=>{let i=null,o=null,c=null;try{c=new e(a,s)}catch{return null}return n.forEach(u=>{c.test(u)&&(!i||o.compare(u)===-1)&&(i=u,o=new t(i,s))}),i},_a}var ya,yo;function nh(){if(yo)return ya;yo=1;const t=xe(),e=Ze();return ya=(n,a,s)=>{let i=null,o=null,c=null;try{c=new e(a,s)}catch{return null}return n.forEach(u=>{c.test(u)&&(!i||o.compare(u)===1)&&(i=u,o=new t(i,s))}),i},ya}var va,vo;function ah(){if(vo)return va;vo=1;const t=xe(),e=Ze(),r=gn();return va=(a,s)=>{a=new e(a,s);let i=new t("0.0.0");if(a.test(i)||(i=new t("0.0.0-0"),a.test(i)))return i;i=null;for(let o=0;o<a.set.length;++o){const c=a.set[o];let u=null;c.forEach(l=>{const d=new t(l.semver.version);switch(l.operator){case">":d.prerelease.length===0?d.patch++:d.prerelease.push(0),d.raw=d.format();case"":case">=":(!u||r(d,u))&&(u=d);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${l.operator}`)}}),u&&(!i||r(i,u))&&(i=u)}return i&&a.test(i)?i:null},va}var wa,wo;function sh(){if(wo)return wa;wo=1;const t=Ze();return wa=(r,n)=>{try{return new t(r,n).range||"*"}catch{return null}},wa}var ba,bo;function Ns(){if(bo)return ba;bo=1;const t=xe(),e=_n(),{ANY:r}=e,n=Ze(),a=yn(),s=gn(),i=$s(),o=Cs(),c=ks();return ba=(l,d,f,h)=>{l=new t(l,h),d=new n(d,h);let p,g,m,_,w;switch(f){case">":p=s,g=o,m=i,_=">",w=">=";break;case"<":p=i,g=c,m=s,_="<",w="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(a(l,d,h))return!1;for(let y=0;y<d.set.length;++y){const I=d.set[y];let C=null,B=null;if(I.forEach(z=>{z.semver===r&&(z=new e(">=0.0.0")),C=C||z,B=B||z,p(z.semver,C.semver,h)?C=z:m(z.semver,B.semver,h)&&(B=z)}),C.operator===_||C.operator===w||(!B.operator||B.operator===_)&&g(l,B.semver))return!1;if(B.operator===w&&m(l,B.semver))return!1}return!0},ba}var Ea,Eo;function ih(){if(Eo)return Ea;Eo=1;const t=Ns();return Ea=(r,n,a)=>t(r,n,">",a),Ea}var Sa,So;function oh(){if(So)return Sa;So=1;const t=Ns();return Sa=(r,n,a)=>t(r,n,"<",a),Sa}var Ta,To;function ch(){if(To)return Ta;To=1;const t=Ze();return Ta=(r,n,a)=>(r=new t(r,a),n=new t(n,a),r.intersects(n,a)),Ta}var xa,xo;function uh(){if(xo)return xa;xo=1;const t=yn(),e=He();return xa=(r,n,a)=>{const s=[];let i=null,o=null;const c=r.sort((f,h)=>e(f,h,a));for(const f of c)t(f,n,a)?(o=f,i||(i=f)):(o&&s.push([i,o]),o=null,i=null);i&&s.push([i,null]);const u=[];for(const[f,h]of s)f===h?u.push(f):!h&&f===c[0]?u.push("*"):h?f===c[0]?u.push(`<=${h}`):u.push(`${f} - ${h}`):u.push(`>=${f}`);const l=u.join(" || "),d=typeof n.raw=="string"?n.raw:String(n);return l.length<d.length?l:n},xa}var Ia,Io;function lh(){if(Io)return Ia;Io=1;const t=Ze(),e=_n(),{ANY:r}=e,n=yn(),a=He(),s=(d,f,h={})=>{if(d===f)return!0;d=new t(d,h),f=new t(f,h);let p=!1;e:for(const g of d.set){for(const m of f.set){const _=c(g,m,h);if(p=p||_!==null,_)continue e}if(p)return!1}return!0},i=[new e(">=0.0.0-0")],o=[new e(">=0.0.0")],c=(d,f,h)=>{if(d===f)return!0;if(d.length===1&&d[0].semver===r){if(f.length===1&&f[0].semver===r)return!0;h.includePrerelease?d=i:d=o}if(f.length===1&&f[0].semver===r){if(h.includePrerelease)return!0;f=o}const p=new Set;let g,m;for(const R of d)R.operator===">"||R.operator===">="?g=u(g,R,h):R.operator==="<"||R.operator==="<="?m=l(m,R,h):p.add(R.semver);if(p.size>1)return null;let _;if(g&&m){if(_=a(g.semver,m.semver,h),_>0)return null;if(_===0&&(g.operator!==">="||m.operator!=="<="))return null}for(const R of p){if(g&&!n(R,String(g),h)||m&&!n(R,String(m),h))return null;for(const oe of f)if(!n(R,String(oe),h))return!1;return!0}let w,y,I,C,B=m&&!h.includePrerelease&&m.semver.prerelease.length?m.semver:!1,z=g&&!h.includePrerelease&&g.semver.prerelease.length?g.semver:!1;B&&B.prerelease.length===1&&m.operator==="<"&&B.prerelease[0]===0&&(B=!1);for(const R of f){if(C=C||R.operator===">"||R.operator===">=",I=I||R.operator==="<"||R.operator==="<=",g){if(z&&R.semver.prerelease&&R.semver.prerelease.length&&R.semver.major===z.major&&R.semver.minor===z.minor&&R.semver.patch===z.patch&&(z=!1),R.operator===">"||R.operator===">="){if(w=u(g,R,h),w===R&&w!==g)return!1}else if(g.operator===">="&&!n(g.semver,String(R),h))return!1}if(m){if(B&&R.semver.prerelease&&R.semver.prerelease.length&&R.semver.major===B.major&&R.semver.minor===B.minor&&R.semver.patch===B.patch&&(B=!1),R.operator==="<"||R.operator==="<="){if(y=l(m,R,h),y===R&&y!==m)return!1}else if(m.operator==="<="&&!n(m.semver,String(R),h))return!1}if(!R.operator&&(m||g)&&_!==0)return!1}return!(g&&I&&!m&&_!==0||m&&C&&!g&&_!==0||z||B)},u=(d,f,h)=>{if(!d)return f;const p=a(d.semver,f.semver,h);return p>0?d:p<0||f.operator===">"&&d.operator===">="?f:d},l=(d,f,h)=>{if(!d)return f;const p=a(d.semver,f.semver,h);return p<0?d:p>0||f.operator==="<"&&d.operator==="<="?f:d};return Ia=s,Ia}var Aa,Ao;function dh(){if(Ao)return Aa;Ao=1;const t=Ar(),e=pn(),r=xe(),n=Yc(),a=Wt(),s=Bf(),i=zf(),o=qf(),c=Gf(),u=Hf(),l=Zf(),d=Vf(),f=Wf(),h=He(),p=Jf(),g=Kf(),m=Os(),_=Yf(),w=Xf(),y=gn(),I=$s(),C=Xc(),B=Qc(),z=ks(),R=Cs(),oe=eu(),_e=Qf(),Ne=_n(),De=Ze(),Nt=yn(),x=th(),E=rh(),U=nh(),P=ah(),F=sh(),L=Ns(),H=ih(),Q=oh(),Y=ch(),se=uh(),he=lh();return Aa={parse:a,valid:s,clean:i,inc:o,diff:c,major:u,minor:l,patch:d,prerelease:f,compare:h,rcompare:p,compareLoose:g,compareBuild:m,sort:_,rsort:w,gt:y,lt:I,eq:C,neq:B,gte:z,lte:R,cmp:oe,coerce:_e,Comparator:Ne,Range:De,satisfies:Nt,toComparators:x,maxSatisfying:E,minSatisfying:U,minVersion:P,validRange:F,outside:L,gtr:H,ltr:Q,intersects:Y,simplifyRange:se,subset:he,SemVer:r,re:t.re,src:t.src,tokens:t.t,SEMVER_SPEC_VERSION:e.SEMVER_SPEC_VERSION,RELEASE_TYPES:e.RELEASE_TYPES,compareIdentifiers:n.compareIdentifiers,rcompareIdentifiers:n.rcompareIdentifiers},Aa}dh();function ut(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(`Invalid identifier format: ${t}`);const[e,r]=t.split(":"),n=r||"latest";if(e.includes("/")){const[a,s]=e.split("/",2);if(!a||!s)throw new Error(`Invalid identifier format: ${t}`);return[a,s,n]}else{if(!e)throw new Error(`Invalid identifier format: ${t}`);return["-",e,n]}}class fh extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}async function M(t,e,r){let n;if(t.ok){r&&(n=await t.text());return}if(t.status===403)try{(await t.json())?.error==="org_scoped_key_requires_workspace"&&(n="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{const o=new Error(`${t.status} ${t.statusText}`);throw o.status=t?.status,o}if(n===void 0)try{n=await t.text()}catch{n=""}const a=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${n}`;if(t.status===409)throw new fh(a);const s=new Error(a);throw s.status=t.status,s}const tu="ERR_CONFLICTING_ENDPOINTS";class hh extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:tu}),this.name="ConflictingEndpointsError"}}function ph(t){return typeof t=="object"&&t!==null&&t.code===tu}var Ro="[...]",mh={result:"[Circular]"},tn=[],Mt=[];const gh=new TextEncoder;function _h(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Br(t){return gh.encode(t)}function ru(t){if(t&&typeof t=="object"&&t!==null){if(t instanceof Map)return Object.fromEntries(t);if(t instanceof Set)return Array.from(t);if(t instanceof Date)return t.toISOString();if(t instanceof RegExp)return t.toString();if(t instanceof Error)return{name:t.name,message:t.message}}else if(typeof t=="bigint")return t.toString();return t}function yh(t){return function(e,r){return ru(r)}}function Pe(t,e,r,n,a){try{const s=JSON.stringify(t,yh(r),n);return Br(s)}catch(s){if(!s.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
18
+ Context: ${e}`:""}`),Br("[Unserializable]");Oe("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
19
+ Context: ${e}`:""}`),typeof a>"u"&&(a=_h()),Wa(t,"",0,[],void 0,0,a);let i;try{Mt.length===0?i=JSON.stringify(t,r,n):i=JSON.stringify(t,vh(r),n)}catch{return Br("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;tn.length!==0;){const o=tn.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return Br(i)}}function Ra(t,e,r,n){var a=Object.getOwnPropertyDescriptor(n,r);a.get!==void 0?a.configurable?(Object.defineProperty(n,r,{value:t}),tn.push([n,r,e,a])):Mt.push([e,r,t]):(n[r]=t,tn.push([n,r,e]))}function Wa(t,e,r,n,a,s,i){s+=1;var o;if(typeof t=="object"&&t!==null){for(o=0;o<n.length;o++)if(n[o]===t){Ra(mh,t,e,a);return}if(typeof i.depthLimit<"u"&&s>i.depthLimit){Ra(Ro,t,e,a);return}if(typeof i.edgesLimit<"u"&&r+1>i.edgesLimit){Ra(Ro,t,e,a);return}if(n.push(t),Array.isArray(t))for(o=0;o<t.length;o++)Wa(t[o],o,o,n,t,s,i);else{t=ru(t);var c=Object.keys(t);for(o=0;o<c.length;o++){var u=c[o];Wa(t[u],u,o,n,t,s,i)}}n.pop()}}function vh(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(Mt.length>0)for(var n=0;n<Mt.length;n++){var a=Mt[n];if(a[1]===e&&a[0]===r){r=a[2],Mt.splice(n,1);break}}return t.call(this,e,r)}}function Oo(t,e){const r=Vc(),n=e??Wc(),a=t.extra??{},s=a.metadata;return t.extra={...a,runtime:{...r,...a?.runtime},metadata:{...n,...n.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??n.revision_id}:{},...s}},t}const wh=t=>{const e=t?.toString()??Oe("TRACING_SAMPLING_RATE");if(e===void 0)return;const r=parseFloat(e);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},bh=t=>{const r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};async function Eh(t){const e=[];for await(const r of t)e.push(r);return e}function zr(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const Sh=async t=>{if(t?.status===429){const e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(r=>setTimeout(r,e)),!0}return!1};function $o(t){return typeof t=="number"?Number(t.toFixed(4)):t}class Th{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 r;const n=new Promise(s=>{r=s}),a=Pe(e.item,`Serializing run with id: ${e.item.id}`).length;return this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:r,itemPromise:n,size:a}),this.sizeBytes+=a,n}pop({upToSizeBytes:e,upToSize:r}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const n=[];let a=0;for(;a+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<r;){const s=this.items.shift();s&&(n.push(s),a+=s.size,this.sizeBytes-=s.size)}if(n.length===0&&this.items.length>0){const s=this.items.shift();n.push(s),a+=s.size,this.sizeBytes-=s.size}return[n.map(s=>({action:s.action,item:s.payload,otelContext:s.otelContext,apiKey:s.apiKey,apiUrl:s.apiUrl})),()=>n.forEach(s=>s.itemPromiseResolve())]}}const xh=24*1024*1024,Ih=1e4,Ah=100,ko="https://api.smith.langchain.com";class gr{get _fetch(){return this.fetchImplementation||uf(this.debug)}constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"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 Th}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:Qe("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:Qe("LANGSMITH_DEBUG")==="true"});const r=gr.getDefaultClientConfig();if(this.tracingSampleRate=wh(e.tracingSamplingRate),this.apiUrl=zr(e.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=zr(e.apiKey??r.apiKey),this.webUrl=zr(e.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=zr(e.workspaceId??Oe("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new Ci({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.batchIngestCaller=new Ci({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:Sh,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??r.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??r.hideOutputs,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,Jc()&&(this.langSmithToOTELTranslator=new If),this.cachedLSEnvVarsForMetadata=Wc()}static getDefaultClientConfig(){const e=Oe("API_KEY"),r=Oe("ENDPOINT")??ko,n=Oe("HIDE_INPUTS")==="true",a=Oe("HIDE_OUTPUTS")==="true";return{apiUrl:r,apiKey:e,webUrl:void 0,hideInputs:n,hideOutputs:a}}getHostUrl(){return this.webUrl?this.webUrl:bh(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/${Gc}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){const r={...e};return r.inputs!==void 0&&(r.inputs=await this.processInputs(r.inputs)),r.outputs!==void 0&&(r.outputs=await this.processOutputs(r.outputs)),r}async _getResponse(e,r){const n=r?.toString()??"",a=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{const i=await this._fetch(a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(i,`fetch ${e}`),i})}async _get(e,r){return(await this._getResponse(e,r)).json()}async*_getPaginated(e,r=new URLSearchParams,n){let a=Number(r.get("offset"))||0;const s=Number(r.get("limit"))||100;for(;;){r.set("offset",String(a)),r.set("limit",String(s));const i=`${this.apiUrl}${e}?${r}`,o=await this.caller.call(async()=>{const u=await this._fetch(i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(u,`fetch ${e}`),u}),c=n?n(await o.json()):await o.json();if(c.length===0||(yield c,c.length<s))break;a+=c.length}}async*_getCursorPaginatedList(e,r=null,n="POST",a="runs"){const s=r?{...r}:{};for(;;){const i=JSON.stringify(s),c=await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await M(l,`fetch ${e}`),l})).json();if(!c||!c[a])break;yield c[a];const u=c.cursors;if(!u||!u.next)break;s.cursor=u.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,r=!1){if(this.tracingSampleRate===void 0)return e;if(r){const n=[];for(const a of e)this.filteredPostUuids.has(a.trace_id)?a.id===a.trace_id&&this.filteredPostUuids.delete(a.trace_id):n.push(a);return n}else{const n=[];for(const a of e){const s=a.trace_id??a.id;this.filteredPostUuids.has(s)||(a.id===s?this._shouldSample()?n.push(a):this.filteredPostUuids.add(s):n.push(a))}return n}}async _getBatchSizeLimitBytes(){const e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e.batch_ingest_config?.size_limit_bytes??xh}async _getBatchSizeLimit(){const e=await this._ensureServerInfo();return this.batchSizeLimit??e.batch_ingest_config?.size_limit??Ah}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r}){const n=[];for(;this.autoBatchQueue.items.length>0;){const[a,s]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:r});if(!a.length){s();break}const i=a.reduce((u,l)=>{const d=l.apiUrl??this.apiUrl,f=l.apiKey??this.apiKey,p=l.apiKey===this.apiKey&&l.apiUrl===this.apiUrl?"default":`${d}|${f}`;return u[p]||(u[p]=[]),u[p].push(l),u},{}),o=[];for(const[u,l]of Object.entries(i)){const d=this._processBatch(l,{apiUrl:u==="default"?void 0:u.split("|")[0],apiKey:u==="default"?void 0:u.split("|")[1]});o.push(d)}const c=Promise.all(o).finally(s);n.push(c)}return Promise.all(n)}async _processBatch(e,r){if(e.length)try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{const n={runCreates:e.filter(s=>s.action==="create").map(s=>s.item),runUpdates:e.filter(s=>s.action==="update").map(s=>s.item)},a=await this._ensureServerInfo();if(a?.batch_ingest_config?.use_multipart_endpoint){const s=a?.instance_flags?.gzip_body_enabled;await this.multipartIngestRuns(n,{...r,useGzip:s})}else await this.batchIngestRuns(n,r)}}catch(n){console.error("Error exporting batch:",n)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){const r=new Map,n=[];for(const a of e)a.item.id&&a.otelContext&&(r.set(a.item.id,a.otelContext),a.action==="create"?n.push({operation:"post",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}):n.push({operation:"patch",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}));this.langSmithToOTELTranslator.exportBatch(n,r)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=Oo(e.item,this.cachedLSEnvVarsForMetadata);const r=this.autoBatchQueue.push(e);if(this.manualFlushMode)return r;const n=await this._getBatchSizeLimitBytes(),a=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>a)&&this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:a}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:a})},this.autoBatchAggregationDelayMs)),r}async _getServerInfo(){const r=await(await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(Ih),...this.fetchOptions});return await M(n,"get server info"),n})).json();return this.debug&&console.log(`
22
20
  === LangSmith Server Configuration ===
23
21
  `+JSON.stringify(r,null,2)+`
24
- `),r}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){const e=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r})}_cloneCurrentOTELContext(){const e=Xc(),r=If();if(this.langSmithToOTELTranslator!==void 0){const n=e.getActiveSpan();if(n)return e.setSpan(r.active(),n)}}async createRun(e,r){if(!this._filterForSampling([e]).length)return;const n={...this.headers,"Content-Type":"application/json"},a=e.project_name;delete e.project_name;const s=await this.prepareRunCreateOrUpdateInputs({session_name:a,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){const c=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:s,otelContext:c,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}const i=$o(s,this.cachedLSEnvVarsForMetadata);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(n["x-tenant-id"]=r.workspaceId);const o=Le(i,`Creating run with id: ${i.id}`);await this.caller.call(async()=>{const c=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await L(c,"create run",!0),c})}async batchIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let a=await Promise.all(e?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]),s=await Promise.all(r?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]);if(a.length>0&&s.length>0){const c=a.reduce((l,d)=>(d.id&&(l[d.id]=d),l),{}),u=[];for(const l of s)l.id!==void 0&&c[l.id]?c[l.id]={...c[l.id],...l}:u.push(l);a=Object.values(c),s=u}const i={post:a,patch:s};if(!i.post.length&&!i.patch.length)return;const o={post:[],patch:[]};for(const c of["post","patch"]){const u=c,l=i[u].reverse();let d=l.pop();for(;d!==void 0;)o[u].push(d),d=l.pop()}if(o.post.length>0||o.patch.length>0){const c=o.post.map(u=>u.id).concat(o.patch.map(u=>u.id)).join(",");await this._postBatchIngestRuns(Le(o,`Ingesting runs with ids: ${c}`),n)}}async _postBatchIngestRuns(e,r){const n={...this.headers,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),await this.batchIngestCaller.call(async()=>{const a=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await L(a,"batch create run",!0),a})}async multipartIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;const a={};let s=[];for(const d of e??[]){const f=await this.prepareRunCreateOrUpdateInputs(d);f.id!==void 0&&f.attachments!==void 0&&(a[f.id]=f.attachments),delete f.attachments,s.push(f)}let i=[];for(const d of r??[])i.push(await this.prepareRunCreateOrUpdateInputs(d));if(s.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(i.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(s.length>0&&i.length>0){const d=s.reduce((h,p)=>(p.id&&(h[p.id]=p),h),{}),f=[];for(const h of i)h.id!==void 0&&d[h.id]?d[h.id]={...d[h.id],...h}:f.push(h);s=Object.values(d),i=f}if(s.length===0&&i.length===0)return;const u=[],l=[];for(const[d,f]of[["post",s],["patch",i]])for(const h of f){const{inputs:p,outputs:m,events:g,extra:y,error:v,serialized:_,attachments:E,...$}=h,U={inputs:p,outputs:m,events:g,extra:y,error:v,serialized:_},z=Le($,`Serializing for multipart ingestion of run with id: ${$.id}`);l.push({name:`${d}.${$.id}`,payload:new Blob([z],{type:`application/json; length=${z.length}`})});for(const[O,oe]of Object.entries(U)){if(oe===void 0)continue;const ye=Le(oe,`Serializing ${O} for multipart ingestion of run with id: ${$.id}`);l.push({name:`${d}.${$.id}.${O}`,payload:new Blob([ye],{type:`application/json; length=${ye.length}`})})}if($.id!==void 0){const O=a[$.id];if(O){delete a[$.id];for(const[oe,ye]of Object.entries(O)){let Me,Ue;if(Array.isArray(ye)?[Me,Ue]=ye:(Me=ye.mimeType,Ue=ye.data),oe.includes(".")){console.warn(`Skipping attachment '${oe}' for run ${$.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${$.id}.${oe}`,payload:new Blob([Ue],{type:`${Me}; length=${Ue.byteLength}`})})}}}u.push(`trace=${$.trace_id},id=${$.id}`)}await this._sendMultipartRequest(l,u.join("; "),n)}async _createNodeFetchBody(e,r){const n=[];for(const i of e)n.push(new Blob([`--${r}\r
22
+ `),r}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){const e=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r})}_cloneCurrentOTELContext(){const e=Kc(),r=Ef();if(this.langSmithToOTELTranslator!==void 0){const n=e.getActiveSpan();if(n)return e.setSpan(r.active(),n)}}async createRun(e,r){if(!this._filterForSampling([e]).length)return;const n={...this.headers,"Content-Type":"application/json"},a=e.project_name;delete e.project_name;const s=await this.prepareRunCreateOrUpdateInputs({session_name:a,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){const c=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:s,otelContext:c,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}const i=Oo(s,this.cachedLSEnvVarsForMetadata);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(n["x-tenant-id"]=r.workspaceId);const o=Pe(i,`Creating run with id: ${i.id}`);await this.caller.call(async()=>{const c=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await M(c,"create run",!0),c})}async batchIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let a=await Promise.all(e?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]),s=await Promise.all(r?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]);if(a.length>0&&s.length>0){const c=a.reduce((l,d)=>(d.id&&(l[d.id]=d),l),{}),u=[];for(const l of s)l.id!==void 0&&c[l.id]?c[l.id]={...c[l.id],...l}:u.push(l);a=Object.values(c),s=u}const i={post:a,patch:s};if(!i.post.length&&!i.patch.length)return;const o={post:[],patch:[]};for(const c of["post","patch"]){const u=c,l=i[u].reverse();let d=l.pop();for(;d!==void 0;)o[u].push(d),d=l.pop()}if(o.post.length>0||o.patch.length>0){const c=o.post.map(u=>u.id).concat(o.patch.map(u=>u.id)).join(",");await this._postBatchIngestRuns(Pe(o,`Ingesting runs with ids: ${c}`),n)}}async _postBatchIngestRuns(e,r){const n={...this.headers,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),await this.batchIngestCaller.call(async()=>{const a=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await M(a,"batch create run",!0),a})}async multipartIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;const a={};let s=[];for(const d of e??[]){const f=await this.prepareRunCreateOrUpdateInputs(d);f.id!==void 0&&f.attachments!==void 0&&(a[f.id]=f.attachments),delete f.attachments,s.push(f)}let i=[];for(const d of r??[])i.push(await this.prepareRunCreateOrUpdateInputs(d));if(s.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(i.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(s.length>0&&i.length>0){const d=s.reduce((h,p)=>(p.id&&(h[p.id]=p),h),{}),f=[];for(const h of i)h.id!==void 0&&d[h.id]?d[h.id]={...d[h.id],...h}:f.push(h);s=Object.values(d),i=f}if(s.length===0&&i.length===0)return;const u=[],l=[];for(const[d,f]of[["post",s],["patch",i]])for(const h of f){const{inputs:p,outputs:g,events:m,extra:_,error:w,serialized:y,attachments:I,...C}=h,B={inputs:p,outputs:g,events:m,extra:_,error:w,serialized:y},z=Pe(C,`Serializing for multipart ingestion of run with id: ${C.id}`);l.push({name:`${d}.${C.id}`,payload:new Blob([z],{type:`application/json; length=${z.length}`})});for(const[R,oe]of Object.entries(B)){if(oe===void 0)continue;const _e=Pe(oe,`Serializing ${R} for multipart ingestion of run with id: ${C.id}`);l.push({name:`${d}.${C.id}.${R}`,payload:new Blob([_e],{type:`application/json; length=${_e.length}`})})}if(C.id!==void 0){const R=a[C.id];if(R){delete a[C.id];for(const[oe,_e]of Object.entries(R)){let Ne,De;if(Array.isArray(_e)?[Ne,De]=_e:(Ne=_e.mimeType,De=_e.data),oe.includes(".")){console.warn(`Skipping attachment '${oe}' for run ${C.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${C.id}.${oe}`,payload:new Blob([De],{type:`${Ne}; length=${De.byteLength}`})})}}}u.push(`trace=${C.trace_id},id=${C.id}`)}await this._sendMultipartRequest(l,u.join("; "),n)}async _createNodeFetchBody(e,r){const n=[];for(const i of e)n.push(new Blob([`--${r}\r
25
23
  `])),n.push(new Blob([`Content-Disposition: form-data; name="${i.name}"\r
26
24
  `,`Content-Type: ${i.payload.type}\r
27
25
  \r
@@ -33,50 +31,50 @@ Context: ${e}`:""}`),typeof a>"u"&&(a=bh()),Wa(t,"",0,[],void 0,0,a);let i;try{j
33
31
  \r
34
32
  `);const u=o.payload.stream().getReader();try{let l;for(;!(l=await u.read()).done;)s.enqueue(l.value)}finally{u.releaseLock()}await i(`\r
35
33
  `)}await i(`--${r}--\r
36
- `),s.close()}})}async _sendMultipartRequest(e,r,n){const a="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),s=ff(),i=()=>this._createNodeFetchBody(e,a),o=()=>this._createMultipartStream(e,a),c=async u=>this.batchIngestCaller.call(async()=>{const l=await u(),d={...this.headers,"Content-Type":`multipart/form-data; boundary=${a}`};n?.apiKey!==void 0&&(d["x-api-key"]=n.apiKey);let f=l;n?.useGzip&&typeof l=="object"&&"pipeThrough"in l&&(f=l.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");const h=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:f,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(h,"Failed to send multipart request",!0),h});try{let u,l=!1;!s&&!this.multipartStreamingDisabled&&Jc()!=="bun"?(l=!0,u=await c(o)):u=await c(i),(!this.multipartStreamingDisabled||l)&&u.status===422&&(n?.apiUrl??this.apiUrl)!==No&&(console.warn(`Streaming multipart upload to ${n?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${r}".`),this.multipartStreamingDisabled=!0,u=await c(i))}catch(u){console.warn(`${u.message.trim()}
34
+ `),s.close()}})}async _sendMultipartRequest(e,r,n){const a="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),s=cf(),i=()=>this._createNodeFetchBody(e,a),o=()=>this._createMultipartStream(e,a),c=async u=>this.batchIngestCaller.call(async()=>{const l=await u(),d={...this.headers,"Content-Type":`multipart/form-data; boundary=${a}`};n?.apiKey!==void 0&&(d["x-api-key"]=n.apiKey);let f=l;n?.useGzip&&typeof l=="object"&&"pipeThrough"in l&&(f=l.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");const h=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:f,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(h,"Failed to send multipart request",!0),h});try{let u,l=!1;!s&&!this.multipartStreamingDisabled&&Zc()!=="bun"?(l=!0,u=await c(o)):u=await c(i),(!this.multipartStreamingDisabled||l)&&u.status===422&&(n?.apiUrl??this.apiUrl)!==ko&&(console.warn(`Streaming multipart upload to ${n?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${r}".`),this.multipartStreamingDisabled=!0,u=await c(i))}catch(u){console.warn(`${u.message.trim()}
37
35
 
38
- Context: ${r}`)}}async updateRun(e,r,n){K(e),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs));const a={...r,id:e};if(!this._filterForSampling([a],!0).length)return;if(this.autoBatchTracing&&a.trace_id!==void 0&&a.dotted_order!==void 0){const o=this._cloneCurrentOTELContext();if(r.end_time!==void 0&&a.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:a,otelContext:o,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:a,otelContext:o,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}const s={...this.headers,"Content-Type":"application/json"};n?.apiKey!==void 0&&(s["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(s["x-tenant-id"]=n.workspaceId);const i=Le(r,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{const o=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:s,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await L(o,"update run",!0),o})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){K(e);let n=await this._get(`/runs/${e}`);return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:r,projectOpts:n}){if(r!==void 0){let a;r.session_id?a=r.session_id:n?.projectName?a=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?a=n?.projectId:a=(await this.readProject({projectName:ke("PROJECT")||"default"})).id;const s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${a}/r/${r.id}?poll=true`}else if(e!==void 0){const a=await this.readRun(e);if(!a.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${a.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){const r=await Ih(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},a={};r.sort((s,i)=>(s?.dotted_order??"").localeCompare(i?.dotted_order??""));for(const s of r){if(s.parent_run_id===null||s.parent_run_id===void 0)throw new Error(`Child run ${s.id} has no parent`);s.dotted_order?.startsWith(e.dotted_order??"")&&s.id!==e.id&&(s.parent_run_id in n||(n[s.parent_run_id]=[]),n[s.parent_run_id].push(s),a[s.id]=s)}e.child_runs=n[e.id]||[];for(const s in n)s!==e.id&&(a[s].child_runs=n[s]);return e}async*listRuns(e){const{projectId:r,projectName:n,parentRunId:a,traceId:s,referenceExampleId:i,startTime:o,executionOrder:c,isRoot:u,runType:l,error:d,id:f,query:h,filter:p,traceFilter:m,treeFilter:g,limit:y,select:v,order:_}=e;let E=[];if(r&&(E=Array.isArray(r)?r:[r]),n){const O=Array.isArray(n)?n:[n],oe=await Promise.all(O.map(ye=>this.readProject({projectName:ye}).then(Me=>Me.id)));E.push(...oe)}const $=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],U={session:E.length?E:null,run_type:l,reference_example:i,query:h,filter:p,trace_filter:m,tree_filter:g,execution_order:c,parent_run:a,start_time:o?o.toISOString():null,error:d,id:f,limit:y,trace:s,select:v||$,is_root:u,order:_};U.select.includes("child_run_ids")&&Ja("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let z=0;for await(const O of this._getCursorPaginatedList("/runs/query",U))if(y){if(z>=y)break;if(O.length+z>y){yield*O.slice(0,y-z);break}z+=O.length,yield*O}else yield*O}async*listGroupRuns(e){const{projectId:r,projectName:n,groupBy:a,filter:s,startTime:i,endTime:o,limit:c,offset:u}=e,d={session_id:r||(await this.readProject({projectName:n})).id,group_by:a,filter:s,start_time:i?i.toISOString():null,end_time:o?o.toISOString():null,limit:Number(c)||100};let f=Number(u)||0;const h="/runs/group",p=`${this.apiUrl}${h}`;for(;;){const m={...d,offset:f},g=Object.fromEntries(Object.entries(m).filter(([U,z])=>z!==void 0)),y=JSON.stringify(g),_=await(await this.caller.call(async()=>{const U=await this._fetch(p,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:y});return await L(U,`Failed to fetch ${h}`),U})).json(),{groups:E,total:$}=_;if(E.length===0)break;for(const U of E)yield U;if(f+=E.length,f>=$)break}}async getRunStats({id:e,trace:r,parentRun:n,runType:a,projectNames:s,projectIds:i,referenceExampleIds:o,startTime:c,endTime:u,error:l,query:d,filter:f,traceFilter:h,treeFilter:p,isRoot:m,dataSourceType:g}){let y=i||[];s&&(y=[...i||[],...await Promise.all(s.map(z=>this.readProject({projectName:z}).then(O=>O.id)))]);const _=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:a,session:y,reference_example:o,start_time:c,end_time:u,error:l,query:d,filter:f,trace_filter:h,tree_filter:p,is_root:m,data_source_type:g}).filter(([z,O])=>O!==void 0)),E=JSON.stringify(_);return await(await this.caller.call(async()=>{const z=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:E});return await L(z,"get run stats"),z})).json()}async shareRun(e,{shareId:r}={}){const n={run_id:e,share_token:r||Te()};K(e);const a=JSON.stringify(n),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await L(o,"share run"),o})).json();if(i===null||!("share_token"in i))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(e){K(e),await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(r,"unshare run",!0),r})}async readRunSharedLink(e){K(e);const n=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(a,"read run shared link"),a})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:r}={}){const n=new URLSearchParams({share_token:e});if(r!==void 0)for(const i of r)n.append("id",i);return K(e),await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/public/${e}/runs${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(i,"list shared runs"),i})).json()}async readDatasetSharedSchema(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id),K(e);const a=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(s,"read dataset shared schema"),s})).json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async shareDataset(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id);const n={dataset_id:e};K(e);const a=JSON.stringify(n),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await L(o,"share dataset"),o})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){K(e),await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(r,"unshare dataset",!0),r})}async readSharedDataset(e){return K(e),await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(a,"read shared dataset"),a})).json()}async listSharedExamples(e,r){const n={};r?.exampleIds&&(n.id=r.exampleIds);const a=new URLSearchParams;Object.entries(n).forEach(([o,c])=>{Array.isArray(c)?c.forEach(u=>a.append(o,u)):a.append(o,c)});const s=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/public/${e}/examples?${a.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(o,"list shared examples"),o}),i=await s.json();if(!s.ok)throw"detail"in i?new Error(`Failed to list shared examples.
36
+ Context: ${r}`)}}async updateRun(e,r,n){K(e),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs));const a={...r,id:e};if(!this._filterForSampling([a],!0).length)return;if(this.autoBatchTracing&&a.trace_id!==void 0&&a.dotted_order!==void 0){const o=this._cloneCurrentOTELContext();if(r.end_time!==void 0&&a.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:a,otelContext:o,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:a,otelContext:o,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}const s={...this.headers,"Content-Type":"application/json"};n?.apiKey!==void 0&&(s["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(s["x-tenant-id"]=n.workspaceId);const i=Pe(r,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{const o=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:s,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await M(o,"update run",!0),o})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){K(e);let n=await this._get(`/runs/${e}`);return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:r,projectOpts:n}){if(r!==void 0){let a;r.session_id?a=r.session_id:n?.projectName?a=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?a=n?.projectId:a=(await this.readProject({projectName:Oe("PROJECT")||"default"})).id;const s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${a}/r/${r.id}?poll=true`}else if(e!==void 0){const a=await this.readRun(e);if(!a.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${a.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){const r=await Eh(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},a={};r.sort((s,i)=>(s?.dotted_order??"").localeCompare(i?.dotted_order??""));for(const s of r){if(s.parent_run_id===null||s.parent_run_id===void 0)throw new Error(`Child run ${s.id} has no parent`);s.dotted_order?.startsWith(e.dotted_order??"")&&s.id!==e.id&&(s.parent_run_id in n||(n[s.parent_run_id]=[]),n[s.parent_run_id].push(s),a[s.id]=s)}e.child_runs=n[e.id]||[];for(const s in n)s!==e.id&&(a[s].child_runs=n[s]);return e}async*listRuns(e){const{projectId:r,projectName:n,parentRunId:a,traceId:s,referenceExampleId:i,startTime:o,executionOrder:c,isRoot:u,runType:l,error:d,id:f,query:h,filter:p,traceFilter:g,treeFilter:m,limit:_,select:w,order:y}=e;let I=[];if(r&&(I=Array.isArray(r)?r:[r]),n){const R=Array.isArray(n)?n:[n],oe=await Promise.all(R.map(_e=>this.readProject({projectName:_e}).then(Ne=>Ne.id)));I.push(...oe)}const C=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],B={session:I.length?I:null,run_type:l,reference_example:i,query:h,filter:p,trace_filter:g,tree_filter:m,execution_order:c,parent_run:a,start_time:o?o.toISOString():null,error:d,id:f,limit:_,trace:s,select:w||C,is_root:u,order:y};B.select.includes("child_run_ids")&&Va("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let z=0;for await(const R of this._getCursorPaginatedList("/runs/query",B))if(_){if(z>=_)break;if(R.length+z>_){yield*R.slice(0,_-z);break}z+=R.length,yield*R}else yield*R}async*listGroupRuns(e){const{projectId:r,projectName:n,groupBy:a,filter:s,startTime:i,endTime:o,limit:c,offset:u}=e,d={session_id:r||(await this.readProject({projectName:n})).id,group_by:a,filter:s,start_time:i?i.toISOString():null,end_time:o?o.toISOString():null,limit:Number(c)||100};let f=Number(u)||0;const h="/runs/group",p=`${this.apiUrl}${h}`;for(;;){const g={...d,offset:f},m=Object.fromEntries(Object.entries(g).filter(([B,z])=>z!==void 0)),_=JSON.stringify(m),y=await(await this.caller.call(async()=>{const B=await this._fetch(p,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:_});return await M(B,`Failed to fetch ${h}`),B})).json(),{groups:I,total:C}=y;if(I.length===0)break;for(const B of I)yield B;if(f+=I.length,f>=C)break}}async getRunStats({id:e,trace:r,parentRun:n,runType:a,projectNames:s,projectIds:i,referenceExampleIds:o,startTime:c,endTime:u,error:l,query:d,filter:f,traceFilter:h,treeFilter:p,isRoot:g,dataSourceType:m}){let _=i||[];s&&(_=[...i||[],...await Promise.all(s.map(z=>this.readProject({projectName:z}).then(R=>R.id)))]);const y=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:a,session:_,reference_example:o,start_time:c,end_time:u,error:l,query:d,filter:f,trace_filter:h,tree_filter:p,is_root:g,data_source_type:m}).filter(([z,R])=>R!==void 0)),I=JSON.stringify(y);return await(await this.caller.call(async()=>{const z=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:I});return await M(z,"get run stats"),z})).json()}async shareRun(e,{shareId:r}={}){const n={run_id:e,share_token:r||Se()};K(e);const a=JSON.stringify(n),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await M(o,"share run"),o})).json();if(i===null||!("share_token"in i))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(e){K(e),await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(r,"unshare run",!0),r})}async readRunSharedLink(e){K(e);const n=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(a,"read run shared link"),a})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:r}={}){const n=new URLSearchParams({share_token:e});if(r!==void 0)for(const i of r)n.append("id",i);return K(e),await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/public/${e}/runs${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(i,"list shared runs"),i})).json()}async readDatasetSharedSchema(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id),K(e);const a=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(s,"read dataset shared schema"),s})).json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async shareDataset(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id);const n={dataset_id:e};K(e);const a=JSON.stringify(n),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await M(o,"share dataset"),o})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){K(e),await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(r,"unshare dataset",!0),r})}async readSharedDataset(e){return K(e),await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(a,"read shared dataset"),a})).json()}async listSharedExamples(e,r){const n={};r?.exampleIds&&(n.id=r.exampleIds);const a=new URLSearchParams;Object.entries(n).forEach(([o,c])=>{Array.isArray(c)?c.forEach(u=>a.append(o,u)):a.append(o,c)});const s=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/public/${e}/examples?${a.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(o,"list shared examples"),o}),i=await s.json();if(!s.ok)throw"detail"in i?new Error(`Failed to list shared examples.
39
37
  Status: ${s.status}
40
38
  Message: ${Array.isArray(i.detail)?i.detail.join(`
41
- `):"Unspecified error"}`):new Error(`Failed to list shared examples: ${s.status} ${s.statusText}`);return i.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:r=null,metadata:n=null,upsert:a=!1,projectExtra:s=null,referenceDatasetId:i=null}){const o=a?"?upsert=true":"",c=`${this.apiUrl}/sessions${o}`,u=s||{};n&&(u.metadata=n);const l={name:e,extra:u,description:r};i!==null&&(l.reference_dataset_id=i);const d=JSON.stringify(l);return await(await this.caller.call(async()=>{const p=await this._fetch(c,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});return await L(p,"create project"),p})).json()}async updateProject(e,{name:r=null,description:n=null,metadata:a=null,projectExtra:s=null,endTime:i=null}){const o=`${this.apiUrl}/sessions/${e}`;let c=s;a&&(c={...c||{},metadata:a});const u=JSON.stringify({name:r,extra:c,description:n,end_time:i?new Date(i).toISOString():null});return await(await this.caller.call(async()=>{const f=await this._fetch(o,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await L(f,"update project"),f})).json()}async hasProject({projectId:e,projectName:r}){let n="/sessions";const a=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)K(e),n+=`/${e}`;else if(r!==void 0)a.append("name",r);else throw new Error("Must provide projectName or projectId");const s=await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${n}?${a}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(i,"has project"),i});try{const i=await s.json();return s.ok?Array.isArray(i)?i.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:r,includeStats:n}){let a="/sessions";const s=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)K(e),a+=`/${e}`;else if(r!==void 0)s.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&s.append("include_stats",n.toString());const i=await this._get(a,s);let o;if(Array.isArray(i)){if(i.length===0)throw new Error(`Project[id=${e}, name=${r}] not found`);o=i[0]}else o=i;return o}async getProjectUrl({projectId:e,projectName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");const n=await this.readProject({projectId:e,projectName:r}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");const n=await this.readDataset({datasetId:e,datasetName:r}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;const e=new URLSearchParams({limit:"1"});for await(const r of this._getPaginated("/sessions",e))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:r,nameContains:n,referenceDatasetId:a,referenceDatasetName:s,includeStats:i,datasetVersion:o,referenceFree:c,metadata:u}={}){const l=new URLSearchParams;if(e!==void 0)for(const d of e)l.append("id",d);if(r!==void 0&&l.append("name",r),n!==void 0&&l.append("name_contains",n),a!==void 0)l.append("reference_dataset",a);else if(s!==void 0){const d=await this.readDataset({datasetName:s});l.append("reference_dataset",d.id)}i!==void 0&&l.append("include_stats",i.toString()),o!==void 0&&l.append("dataset_version",o),c!==void 0&&l.append("reference_free",c.toString()),u!==void 0&&l.append("metadata",JSON.stringify(u));for await(const d of this._getPaginated("/sessions",l))yield*d}async deleteProject({projectId:e,projectName:r}){let n;if(e===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?n=(await this.readProject({projectName:r})).id:n=e,K(n),await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(a,`delete session ${n} (${r})`,!0),a})}async uploadCsv({csvFile:e,fileName:r,inputKeys:n,outputKeys:a,description:s,dataType:i,name:o}){const c=`${this.apiUrl}/datasets/upload`,u=new FormData;return u.append("file",e,r),n.forEach(f=>{u.append("input_keys",f)}),a.forEach(f=>{u.append("output_keys",f)}),s&&u.append("description",s),i&&u.append("data_type",i),o&&u.append("name",o),await(await this.caller.call(async()=>{const f=await this._fetch(c,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await L(f,"upload CSV"),f})).json()}async createDataset(e,{description:r,dataType:n,inputsSchema:a,outputsSchema:s,metadata:i}={}){const o={name:e,description:r,extra:i?{metadata:i}:void 0};n&&(o.data_type=n),a&&(o.inputs_schema_definition=a),s&&(o.outputs_schema_definition=s);const c=JSON.stringify(o);return await(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await L(d,"create dataset"),d})).json()}async readDataset({datasetId:e,datasetName:r}){let n="/datasets";const a=new URLSearchParams({limit:"1"});if(e&&r)throw new Error("Must provide either datasetName or datasetId, not both");if(e)K(e),n+=`/${e}`;else if(r)a.append("name",r);else throw new Error("Must provide datasetName or datasetId");const s=await this._get(n,a);let i;if(Array.isArray(s)){if(s.length===0)throw new Error(`Dataset[id=${e}, name=${r}] not found`);i=s[0]}else i=s;return i}async hasDataset({datasetId:e,datasetName:r}){try{return await this.readDataset({datasetId:e,datasetName:r}),!0}catch(n){if(n instanceof Error&&n.message.toLocaleLowerCase().includes("not found"))return!1;throw n}}async diffDatasetVersions({datasetId:e,datasetName:r,fromVersion:n,toVersion:a}){let s=e;if(s===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:r})).id);const i=new URLSearchParams({from_version:typeof n=="string"?n:n.toISOString(),to_version:typeof a=="string"?a:a.toISOString()});return await this._get(`/datasets/${s}/versions/diff`,i)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:r}){const n="/datasets";if(e===void 0)if(r!==void 0)e=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${n}/${e}/openai_ft`)).text()).trim().split(`
42
- `).map(o=>JSON.parse(o))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:n,datasetName:a,datasetNameContains:s,metadata:i}={}){const o="/datasets",c=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(n!==void 0)for(const u of n)c.append("id",u);a!==void 0&&c.append("name",a),s!==void 0&&c.append("name_contains",s),i!==void 0&&c.append("metadata",JSON.stringify(i));for await(const u of this._getPaginated(o,c))yield*u}async updateDataset(e){const{datasetId:r,datasetName:n,...a}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");const s=r??(await this.readDataset({datasetName:n})).id;K(s);const i=JSON.stringify(a);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await L(c,"update dataset"),c})).json()}async updateDatasetTag(e){const{datasetId:r,datasetName:n,asOf:a,tag:s}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");const i=r??(await this.readDataset({datasetName:n})).id;K(i);const o=JSON.stringify({as_of:typeof a=="string"?a:a.toISOString(),tag:s});await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${i}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await L(c,"update dataset tags",!0),c})}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",a=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(a=(await this.readDataset({datasetName:r})).id),a!==void 0)K(a),n+=`/${a}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{const s=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(s,`delete ${n}`,!0),s})}async indexDataset({datasetId:e,datasetName:r,tag:n}){let a=e;if(!a&&!r)throw new Error("Must provide either datasetName or datasetId");if(a&&r)throw new Error("Must provide either datasetName or datasetId, not both");a||(a=(await this.readDataset({datasetName:r})).id),K(a);const i=JSON.stringify({tag:n});await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${a}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await L(c,"index dataset"),c})).json()}async similarExamples(e,r,n,{filter:a}={}){const s={limit:n,inputs:e};a!==void 0&&(s.filter=a),K(r);const i=JSON.stringify(s);return(await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${r}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:i});return await L(u,"fetch similar examples"),u})).json()).examples}async createExample(e,r,n){if(Po(e)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let a=r?n?.datasetId:e.dataset_id;const s=r?n?.datasetName:e.dataset_name;if(a===void 0&&s===void 0)throw new Error("Must provide either datasetName or datasetId");if(a!==void 0&&s!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");a===void 0&&(a=(await this.readDataset({datasetName:s})).id);const i=(r?n?.createdAt:e.created_at)||new Date;let o;Po(e)?o=e:o={inputs:e,outputs:r,created_at:i?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};const c=await this._uploadExamplesMultipart(a,[o]);return await this.readExample(c.example_ids?.[0]??Te())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];const v=e;let _=v[0].dataset_id;const E=v[0].dataset_name;if(_===void 0&&E===void 0)throw new Error("Must provide either datasetName or datasetId");if(_!==void 0&&E!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");_===void 0&&(_=(await this.readDataset({datasetName:E})).id);const $=await this._uploadExamplesMultipart(_,v);return await Promise.all($.example_ids.map(z=>this.readExample(z)))}const{inputs:r,outputs:n,metadata:a,splits:s,sourceRunIds:i,useSourceRunIOs:o,useSourceRunAttachments:c,attachments:u,exampleIds:l,datasetId:d,datasetName:f}=e;if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let h=d;const p=f;if(h===void 0&&p===void 0)throw new Error("Must provide either datasetName or datasetId");if(h!==void 0&&p!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");h===void 0&&(h=(await this.readDataset({datasetName:p})).id);const m=r.map((v,_)=>({dataset_id:h,inputs:v,outputs:n?.[_],metadata:a?.[_],split:s?.[_],id:l?.[_],attachments:u?.[_],source_run_id:i?.[_],use_source_run_io:o?.[_],use_source_run_attachments:c?.[_]})),g=await this._uploadExamplesMultipart(h,m);return await Promise.all(g.example_ids.map(v=>this.readExample(v)))}async createLLMExample(e,r,n){return this.createExample({input:e},{output:r},n)}async createChatExample(e,r,n){const a=e.map(i=>Mi(i)?Li(i):i),s=Mi(r)?Li(r):r;return this.createExample({input:a},{output:s},n)}async readExample(e){K(e);const r=`/examples/${e}`,n=await this._get(r),{attachment_urls:a,...s}=n,i=s;return a&&(i.attachments=Object.entries(a).reduce((o,[c,u])=>(o[c.slice(11)]={presigned_url:u.presigned_url,mime_type:u.mime_type},o),{})),i}async*listExamples({datasetId:e,datasetName:r,exampleIds:n,asOf:a,splits:s,inlineS3Urls:i,metadata:o,limit:c,offset:u,filter:l,includeAttachments:d}={}){let f;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)f=e;else if(r!==void 0)f=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");const h=new URLSearchParams({dataset:f}),p=a?typeof a=="string"?a:a?.toISOString():void 0;p&&h.append("as_of",p);const m=i??!0;if(h.append("inline_s3_urls",m.toString()),n!==void 0)for(const y of n)h.append("id",y);if(s!==void 0)for(const y of s)h.append("splits",y);if(o!==void 0){const y=JSON.stringify(o);h.append("metadata",y)}c!==void 0&&h.append("limit",c.toString()),u!==void 0&&h.append("offset",u.toString()),l!==void 0&&h.append("filter",l),d===!0&&["attachment_urls","outputs","metadata"].forEach(y=>h.append("select",y));let g=0;for await(const y of this._getPaginated("/examples",h)){for(const v of y){const{attachment_urls:_,...E}=v,$=E;_&&($.attachments=Object.entries(_).reduce((U,[z,O])=>(U[z.slice(11)]={presigned_url:O.presigned_url,mime_type:O.mime_type||void 0},U),{})),yield $,g++}if(c!==void 0&&g>=c)break}}async deleteExample(e){K(e);const r=`/examples/${e}`;await this.caller.call(async()=>{const n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(n,`delete ${r}`,!0),n})}async updateExample(e,r){let n;r?n=e:n=e.id,K(n);let a;r?a={id:n,...r}:a=e;let s;return a.dataset_id!==void 0?s=a.dataset_id:s=(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(s,[a])}async updateExamples(e){let r;return e[0].dataset_id===void 0?r=(await this.readExample(e[0].id)).dataset_id:r=e[0].dataset_id,this._updateExamplesMultipart(r,e)}async readDatasetVersion({datasetId:e,datasetName:r,asOf:n,tag:a}){let s;if(e?s=e:s=(await this.readDataset({datasetName:r})).id,K(s),n&&a||!n&&!a)throw new Error("Exactly one of asOf and tag must be specified.");const i=new URLSearchParams;return n!==void 0&&i.append("as_of",typeof n=="string"?n:n.toISOString()),a!==void 0&&i.append("tag",a),await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${s}/version?${i.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(c,"read dataset version"),c})).json()}async listDatasetSplits({datasetId:e,datasetName:r,asOf:n}){let a;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?a=(await this.readDataset({datasetName:r})).id:a=e,K(a);const s=new URLSearchParams,i=n?typeof n=="string"?n:n?.toISOString():void 0;return i&&s.append("as_of",i),await this._get(`/datasets/${a}/splits`,s)}async updateDatasetSplits({datasetId:e,datasetName:r,splitName:n,exampleIds:a,remove:s=!1}){let i;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?i=(await this.readDataset({datasetName:r})).id:i=e,K(i);const o={split_name:n,examples:a.map(u=>(K(u),u)),remove:s},c=JSON.stringify(o);await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${i}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await L(u,"update dataset splits",!0),u})}async evaluateRun(e,r,{sourceInfo:n,loadChildRuns:a,referenceExample:s}={loadChildRuns:!1}){Ja("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");let i;if(typeof e=="string")i=await this.readRun(e,{loadChildRuns:a});else if(typeof e=="object"&&"id"in e)i=e;else throw new Error(`Invalid run type: ${typeof e}`);i.reference_example_id!==null&&i.reference_example_id!==void 0&&(s=await this.readExample(i.reference_example_id));const o=await r.evaluateRun(i,s),[c,u]=await this._logEvaluationFeedback(o,i,n);return u[0]}async createFeedback(e,r,{score:n,value:a,correction:s,comment:i,sourceInfo:o,feedbackSourceType:c="api",sourceRunId:u,feedbackId:l,feedbackConfig:d,projectId:f,comparativeExperimentId:h}){if(!e&&!f)throw new Error("One of runId or projectId must be provided");if(e&&f)throw new Error("Only one of runId or projectId can be provided");const p={type:c??"api",metadata:o??{}};u!==void 0&&p?.metadata!==void 0&&!p.metadata.__run&&(p.metadata.__run={run_id:u}),p?.metadata!==void 0&&p.metadata.__run?.run_id!==void 0&&K(p.metadata.__run.run_id);const m={id:l??Te(),run_id:e,key:r,score:Co(n),value:a,correction:s,comment:i,feedback_source:p,comparative_experiment_id:h,feedbackConfig:d,session_id:f},g=JSON.stringify(m),y=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const v=await this._fetch(y,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:g});return await L(v,"create feedback",!0),v}),m}async updateFeedback(e,{score:r,value:n,correction:a,comment:s}){const i={};r!=null&&(i.score=Co(r)),n!=null&&(i.value=n),a!=null&&(i.correction=a),s!=null&&(i.comment=s),K(e);const o=JSON.stringify(i);await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await L(c,"update feedback",!0),c})}async readFeedback(e){K(e);const r=`/feedback/${e}`;return await this._get(r)}async deleteFeedback(e){K(e);const r=`/feedback/${e}`;await this.caller.call(async()=>{const n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(n,`delete ${r}`,!0),n})}async*listFeedback({runIds:e,feedbackKeys:r,feedbackSourceTypes:n}={}){const a=new URLSearchParams;if(e)for(const s of e)K(s),a.append("run",s);if(r)for(const s of r)a.append("key",s);if(n)for(const s of n)a.append("source",s);for await(const s of this._getPaginated("/feedback",a))yield*s}async createPresignedFeedbackToken(e,r,{expiration:n,feedbackConfig:a}={}){const s={run_id:e,feedback_key:r,feedback_config:a};n?typeof n=="string"?s.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(s.expires_in=n):s.expires_in={hours:3};const i=JSON.stringify(s);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await L(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:e,experimentIds:r,referenceDatasetId:n,createdAt:a,description:s,metadata:i,id:o}){if(r.length===0)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:r[0]})).reference_dataset_id),!n==null)throw new Error("A reference dataset is required");const c={id:o,name:e,experiment_ids:r,reference_dataset_id:n,description:s,created_at:(a??new Date)?.toISOString(),extra:{}};i&&(c.extra.metadata=i);const u=JSON.stringify(c);return(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await L(d,"create comparative experiment"),d})).json()}async*listPresignedFeedbackTokens(e){K(e);const r=new URLSearchParams({run_id:e});for await(const n of this._getPaginated("/feedback/tokens",r))yield*n}_selectEvalResults(e){let r;return"results"in e?r=e.results:Array.isArray(e)?r=e:r=[e],r}async _logEvaluationFeedback(e,r,n){const a=this._selectEvalResults(e),s=[];for(const i of a){let o=n||{};i.evaluatorInfo&&(o={...i.evaluatorInfo,...o});let c=null;i.targetRunId?c=i.targetRunId:r&&(c=r.id),s.push(await this.createFeedback(c,i.key,{score:i.score,value:i.value,comment:i.comment,correction:i.correction,sourceInfo:o,sourceRunId:i.sourceRunId,feedbackConfig:i.feedbackConfig,feedbackSourceType:"model"}))}return[a,s]}async logEvaluationFeedback(e,r,n){const[a]=await this._logEvaluationFeedback(e,r,n);return a}async*listAnnotationQueues(e={}){const{queueIds:r,name:n,nameContains:a,limit:s}=e,i=new URLSearchParams;r&&r.forEach((c,u)=>{K(c,`queueIds[${u}]`),i.append("ids",c)}),n&&i.append("name",n),a&&i.append("name_contains",a),i.append("limit",(s!==void 0?Math.min(s,100):100).toString());let o=0;for await(const c of this._getPaginated("/annotation-queues",i))if(yield*c,o++,s!==void 0&&o>=s)break}async createAnnotationQueue(e){const{name:r,description:n,queueId:a,rubricInstructions:s}=e,i={name:r,description:n,id:a||Te(),rubric_instructions:s},o=JSON.stringify(Object.fromEntries(Object.entries(i).filter(([u,l])=>l!==void 0)));return(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await L(u,"create annotation queue"),u})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${K(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(e,r){const{name:n,description:a,rubricInstructions:s}=r,i=JSON.stringify({name:n,description:a,rubric_instructions:s});await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/annotation-queues/${K(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await L(o,"update annotation queue",!0),o})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${K(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(r,"delete annotation queue",!0),r})}async addRunsToAnnotationQueue(e,r){const n=JSON.stringify(r.map((a,s)=>K(a,`runIds[${s}]`).toString()));await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/annotation-queues/${K(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await L(a,"add runs to annotation queue",!0),a})}async getRunFromAnnotationQueue(e,r){const n=`/annotation-queues/${K(e,"queueId")}/run`;return(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${n}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(s,"get run from annotation queue"),s})).json()}async deleteRunFromAnnotationQueue(e,r){await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${K(e,"queueId")}/runs/${K(r,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(n,"delete run from annotation queue",!0),n})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${K(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(n,"get size from annotation queue"),n})).json()}async _currentTenantIsOwner(e){const r=await this._getSettings();return e=="-"||r.tenant_handle===e}async _ownerConflictError(e,r){const n=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
39
+ `):"Unspecified error"}`):new Error(`Failed to list shared examples: ${s.status} ${s.statusText}`);return i.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:r=null,metadata:n=null,upsert:a=!1,projectExtra:s=null,referenceDatasetId:i=null}){const o=a?"?upsert=true":"",c=`${this.apiUrl}/sessions${o}`,u=s||{};n&&(u.metadata=n);const l={name:e,extra:u,description:r};i!==null&&(l.reference_dataset_id=i);const d=JSON.stringify(l);return await(await this.caller.call(async()=>{const p=await this._fetch(c,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});return await M(p,"create project"),p})).json()}async updateProject(e,{name:r=null,description:n=null,metadata:a=null,projectExtra:s=null,endTime:i=null}){const o=`${this.apiUrl}/sessions/${e}`;let c=s;a&&(c={...c||{},metadata:a});const u=JSON.stringify({name:r,extra:c,description:n,end_time:i?new Date(i).toISOString():null});return await(await this.caller.call(async()=>{const f=await this._fetch(o,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await M(f,"update project"),f})).json()}async hasProject({projectId:e,projectName:r}){let n="/sessions";const a=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)K(e),n+=`/${e}`;else if(r!==void 0)a.append("name",r);else throw new Error("Must provide projectName or projectId");const s=await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${n}?${a}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(i,"has project"),i});try{const i=await s.json();return s.ok?Array.isArray(i)?i.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:r,includeStats:n}){let a="/sessions";const s=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)K(e),a+=`/${e}`;else if(r!==void 0)s.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&s.append("include_stats",n.toString());const i=await this._get(a,s);let o;if(Array.isArray(i)){if(i.length===0)throw new Error(`Project[id=${e}, name=${r}] not found`);o=i[0]}else o=i;return o}async getProjectUrl({projectId:e,projectName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");const n=await this.readProject({projectId:e,projectName:r}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");const n=await this.readDataset({datasetId:e,datasetName:r}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;const e=new URLSearchParams({limit:"1"});for await(const r of this._getPaginated("/sessions",e))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:r,nameContains:n,referenceDatasetId:a,referenceDatasetName:s,includeStats:i,datasetVersion:o,referenceFree:c,metadata:u}={}){const l=new URLSearchParams;if(e!==void 0)for(const d of e)l.append("id",d);if(r!==void 0&&l.append("name",r),n!==void 0&&l.append("name_contains",n),a!==void 0)l.append("reference_dataset",a);else if(s!==void 0){const d=await this.readDataset({datasetName:s});l.append("reference_dataset",d.id)}i!==void 0&&l.append("include_stats",i.toString()),o!==void 0&&l.append("dataset_version",o),c!==void 0&&l.append("reference_free",c.toString()),u!==void 0&&l.append("metadata",JSON.stringify(u));for await(const d of this._getPaginated("/sessions",l))yield*d}async deleteProject({projectId:e,projectName:r}){let n;if(e===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?n=(await this.readProject({projectName:r})).id:n=e,K(n),await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(a,`delete session ${n} (${r})`,!0),a})}async uploadCsv({csvFile:e,fileName:r,inputKeys:n,outputKeys:a,description:s,dataType:i,name:o}){const c=`${this.apiUrl}/datasets/upload`,u=new FormData;return u.append("file",e,r),n.forEach(f=>{u.append("input_keys",f)}),a.forEach(f=>{u.append("output_keys",f)}),s&&u.append("description",s),i&&u.append("data_type",i),o&&u.append("name",o),await(await this.caller.call(async()=>{const f=await this._fetch(c,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await M(f,"upload CSV"),f})).json()}async createDataset(e,{description:r,dataType:n,inputsSchema:a,outputsSchema:s,metadata:i}={}){const o={name:e,description:r,extra:i?{metadata:i}:void 0};n&&(o.data_type=n),a&&(o.inputs_schema_definition=a),s&&(o.outputs_schema_definition=s);const c=JSON.stringify(o);return await(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await M(d,"create dataset"),d})).json()}async readDataset({datasetId:e,datasetName:r}){let n="/datasets";const a=new URLSearchParams({limit:"1"});if(e&&r)throw new Error("Must provide either datasetName or datasetId, not both");if(e)K(e),n+=`/${e}`;else if(r)a.append("name",r);else throw new Error("Must provide datasetName or datasetId");const s=await this._get(n,a);let i;if(Array.isArray(s)){if(s.length===0)throw new Error(`Dataset[id=${e}, name=${r}] not found`);i=s[0]}else i=s;return i}async hasDataset({datasetId:e,datasetName:r}){try{return await this.readDataset({datasetId:e,datasetName:r}),!0}catch(n){if(n instanceof Error&&n.message.toLocaleLowerCase().includes("not found"))return!1;throw n}}async diffDatasetVersions({datasetId:e,datasetName:r,fromVersion:n,toVersion:a}){let s=e;if(s===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:r})).id);const i=new URLSearchParams({from_version:typeof n=="string"?n:n.toISOString(),to_version:typeof a=="string"?a:a.toISOString()});return await this._get(`/datasets/${s}/versions/diff`,i)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:r}){const n="/datasets";if(e===void 0)if(r!==void 0)e=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${n}/${e}/openai_ft`)).text()).trim().split(`
40
+ `).map(o=>JSON.parse(o))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:n,datasetName:a,datasetNameContains:s,metadata:i}={}){const o="/datasets",c=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(n!==void 0)for(const u of n)c.append("id",u);a!==void 0&&c.append("name",a),s!==void 0&&c.append("name_contains",s),i!==void 0&&c.append("metadata",JSON.stringify(i));for await(const u of this._getPaginated(o,c))yield*u}async updateDataset(e){const{datasetId:r,datasetName:n,...a}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");const s=r??(await this.readDataset({datasetName:n})).id;K(s);const i=JSON.stringify(a);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await M(c,"update dataset"),c})).json()}async updateDatasetTag(e){const{datasetId:r,datasetName:n,asOf:a,tag:s}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");const i=r??(await this.readDataset({datasetName:n})).id;K(i);const o=JSON.stringify({as_of:typeof a=="string"?a:a.toISOString(),tag:s});await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${i}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await M(c,"update dataset tags",!0),c})}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",a=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(a=(await this.readDataset({datasetName:r})).id),a!==void 0)K(a),n+=`/${a}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{const s=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(s,`delete ${n}`,!0),s})}async indexDataset({datasetId:e,datasetName:r,tag:n}){let a=e;if(!a&&!r)throw new Error("Must provide either datasetName or datasetId");if(a&&r)throw new Error("Must provide either datasetName or datasetId, not both");a||(a=(await this.readDataset({datasetName:r})).id),K(a);const i=JSON.stringify({tag:n});await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${a}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await M(c,"index dataset"),c})).json()}async similarExamples(e,r,n,{filter:a}={}){const s={limit:n,inputs:e};a!==void 0&&(s.filter=a),K(r);const i=JSON.stringify(s);return(await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${r}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:i});return await M(u,"fetch similar examples"),u})).json()).examples}async createExample(e,r,n){if(Co(e)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let a=r?n?.datasetId:e.dataset_id;const s=r?n?.datasetName:e.dataset_name;if(a===void 0&&s===void 0)throw new Error("Must provide either datasetName or datasetId");if(a!==void 0&&s!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");a===void 0&&(a=(await this.readDataset({datasetName:s})).id);const i=(r?n?.createdAt:e.created_at)||new Date;let o;Co(e)?o=e:o={inputs:e,outputs:r,created_at:i?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};const c=await this._uploadExamplesMultipart(a,[o]);return await this.readExample(c.example_ids?.[0]??Se())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];const w=e;let y=w[0].dataset_id;const I=w[0].dataset_name;if(y===void 0&&I===void 0)throw new Error("Must provide either datasetName or datasetId");if(y!==void 0&&I!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");y===void 0&&(y=(await this.readDataset({datasetName:I})).id);const C=await this._uploadExamplesMultipart(y,w);return await Promise.all(C.example_ids.map(z=>this.readExample(z)))}const{inputs:r,outputs:n,metadata:a,splits:s,sourceRunIds:i,useSourceRunIOs:o,useSourceRunAttachments:c,attachments:u,exampleIds:l,datasetId:d,datasetName:f}=e;if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let h=d;const p=f;if(h===void 0&&p===void 0)throw new Error("Must provide either datasetName or datasetId");if(h!==void 0&&p!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");h===void 0&&(h=(await this.readDataset({datasetName:p})).id);const g=r.map((w,y)=>({dataset_id:h,inputs:w,outputs:n?.[y],metadata:a?.[y],split:s?.[y],id:l?.[y],attachments:u?.[y],source_run_id:i?.[y],use_source_run_io:o?.[y],use_source_run_attachments:c?.[y]})),m=await this._uploadExamplesMultipart(h,g);return await Promise.all(m.example_ids.map(w=>this.readExample(w)))}async createLLMExample(e,r,n){return this.createExample({input:e},{output:r},n)}async createChatExample(e,r,n){const a=e.map(i=>Ni(i)?Pi(i):i),s=Ni(r)?Pi(r):r;return this.createExample({input:a},{output:s},n)}async readExample(e){K(e);const r=`/examples/${e}`,n=await this._get(r),{attachment_urls:a,...s}=n,i=s;return a&&(i.attachments=Object.entries(a).reduce((o,[c,u])=>(o[c.slice(11)]={presigned_url:u.presigned_url,mime_type:u.mime_type},o),{})),i}async*listExamples({datasetId:e,datasetName:r,exampleIds:n,asOf:a,splits:s,inlineS3Urls:i,metadata:o,limit:c,offset:u,filter:l,includeAttachments:d}={}){let f;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)f=e;else if(r!==void 0)f=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");const h=new URLSearchParams({dataset:f}),p=a?typeof a=="string"?a:a?.toISOString():void 0;p&&h.append("as_of",p);const g=i??!0;if(h.append("inline_s3_urls",g.toString()),n!==void 0)for(const _ of n)h.append("id",_);if(s!==void 0)for(const _ of s)h.append("splits",_);if(o!==void 0){const _=JSON.stringify(o);h.append("metadata",_)}c!==void 0&&h.append("limit",c.toString()),u!==void 0&&h.append("offset",u.toString()),l!==void 0&&h.append("filter",l),d===!0&&["attachment_urls","outputs","metadata"].forEach(_=>h.append("select",_));let m=0;for await(const _ of this._getPaginated("/examples",h)){for(const w of _){const{attachment_urls:y,...I}=w,C=I;y&&(C.attachments=Object.entries(y).reduce((B,[z,R])=>(B[z.slice(11)]={presigned_url:R.presigned_url,mime_type:R.mime_type||void 0},B),{})),yield C,m++}if(c!==void 0&&m>=c)break}}async deleteExample(e){K(e);const r=`/examples/${e}`;await this.caller.call(async()=>{const n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(n,`delete ${r}`,!0),n})}async updateExample(e,r){let n;r?n=e:n=e.id,K(n);let a;r?a={id:n,...r}:a=e;let s;return a.dataset_id!==void 0?s=a.dataset_id:s=(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(s,[a])}async updateExamples(e){let r;return e[0].dataset_id===void 0?r=(await this.readExample(e[0].id)).dataset_id:r=e[0].dataset_id,this._updateExamplesMultipart(r,e)}async readDatasetVersion({datasetId:e,datasetName:r,asOf:n,tag:a}){let s;if(e?s=e:s=(await this.readDataset({datasetName:r})).id,K(s),n&&a||!n&&!a)throw new Error("Exactly one of asOf and tag must be specified.");const i=new URLSearchParams;return n!==void 0&&i.append("as_of",typeof n=="string"?n:n.toISOString()),a!==void 0&&i.append("tag",a),await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${s}/version?${i.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(c,"read dataset version"),c})).json()}async listDatasetSplits({datasetId:e,datasetName:r,asOf:n}){let a;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?a=(await this.readDataset({datasetName:r})).id:a=e,K(a);const s=new URLSearchParams,i=n?typeof n=="string"?n:n?.toISOString():void 0;return i&&s.append("as_of",i),await this._get(`/datasets/${a}/splits`,s)}async updateDatasetSplits({datasetId:e,datasetName:r,splitName:n,exampleIds:a,remove:s=!1}){let i;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?i=(await this.readDataset({datasetName:r})).id:i=e,K(i);const o={split_name:n,examples:a.map(u=>(K(u),u)),remove:s},c=JSON.stringify(o);await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${i}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await M(u,"update dataset splits",!0),u})}async evaluateRun(e,r,{sourceInfo:n,loadChildRuns:a,referenceExample:s}={loadChildRuns:!1}){Va("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");let i;if(typeof e=="string")i=await this.readRun(e,{loadChildRuns:a});else if(typeof e=="object"&&"id"in e)i=e;else throw new Error(`Invalid run type: ${typeof e}`);i.reference_example_id!==null&&i.reference_example_id!==void 0&&(s=await this.readExample(i.reference_example_id));const o=await r.evaluateRun(i,s),[c,u]=await this._logEvaluationFeedback(o,i,n);return u[0]}async createFeedback(e,r,{score:n,value:a,correction:s,comment:i,sourceInfo:o,feedbackSourceType:c="api",sourceRunId:u,feedbackId:l,feedbackConfig:d,projectId:f,comparativeExperimentId:h}){if(!e&&!f)throw new Error("One of runId or projectId must be provided");if(e&&f)throw new Error("Only one of runId or projectId can be provided");const p={type:c??"api",metadata:o??{}};u!==void 0&&p?.metadata!==void 0&&!p.metadata.__run&&(p.metadata.__run={run_id:u}),p?.metadata!==void 0&&p.metadata.__run?.run_id!==void 0&&K(p.metadata.__run.run_id);const g={id:l??Se(),run_id:e,key:r,score:$o(n),value:a,correction:s,comment:i,feedback_source:p,comparative_experiment_id:h,feedbackConfig:d,session_id:f},m=JSON.stringify(g),_=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const w=await this._fetch(_,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:m});return await M(w,"create feedback",!0),w}),g}async updateFeedback(e,{score:r,value:n,correction:a,comment:s}){const i={};r!=null&&(i.score=$o(r)),n!=null&&(i.value=n),a!=null&&(i.correction=a),s!=null&&(i.comment=s),K(e);const o=JSON.stringify(i);await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await M(c,"update feedback",!0),c})}async readFeedback(e){K(e);const r=`/feedback/${e}`;return await this._get(r)}async deleteFeedback(e){K(e);const r=`/feedback/${e}`;await this.caller.call(async()=>{const n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(n,`delete ${r}`,!0),n})}async*listFeedback({runIds:e,feedbackKeys:r,feedbackSourceTypes:n}={}){const a=new URLSearchParams;if(e)for(const s of e)K(s),a.append("run",s);if(r)for(const s of r)a.append("key",s);if(n)for(const s of n)a.append("source",s);for await(const s of this._getPaginated("/feedback",a))yield*s}async createPresignedFeedbackToken(e,r,{expiration:n,feedbackConfig:a}={}){const s={run_id:e,feedback_key:r,feedback_config:a};n?typeof n=="string"?s.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(s.expires_in=n):s.expires_in={hours:3};const i=JSON.stringify(s);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await M(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:e,experimentIds:r,referenceDatasetId:n,createdAt:a,description:s,metadata:i,id:o}){if(r.length===0)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:r[0]})).reference_dataset_id),!n==null)throw new Error("A reference dataset is required");const c={id:o,name:e,experiment_ids:r,reference_dataset_id:n,description:s,created_at:(a??new Date)?.toISOString(),extra:{}};i&&(c.extra.metadata=i);const u=JSON.stringify(c);return(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await M(d,"create comparative experiment"),d})).json()}async*listPresignedFeedbackTokens(e){K(e);const r=new URLSearchParams({run_id:e});for await(const n of this._getPaginated("/feedback/tokens",r))yield*n}_selectEvalResults(e){let r;return"results"in e?r=e.results:Array.isArray(e)?r=e:r=[e],r}async _logEvaluationFeedback(e,r,n){const a=this._selectEvalResults(e),s=[];for(const i of a){let o=n||{};i.evaluatorInfo&&(o={...i.evaluatorInfo,...o});let c=null;i.targetRunId?c=i.targetRunId:r&&(c=r.id),s.push(await this.createFeedback(c,i.key,{score:i.score,value:i.value,comment:i.comment,correction:i.correction,sourceInfo:o,sourceRunId:i.sourceRunId,feedbackConfig:i.feedbackConfig,feedbackSourceType:"model"}))}return[a,s]}async logEvaluationFeedback(e,r,n){const[a]=await this._logEvaluationFeedback(e,r,n);return a}async*listAnnotationQueues(e={}){const{queueIds:r,name:n,nameContains:a,limit:s}=e,i=new URLSearchParams;r&&r.forEach((c,u)=>{K(c,`queueIds[${u}]`),i.append("ids",c)}),n&&i.append("name",n),a&&i.append("name_contains",a),i.append("limit",(s!==void 0?Math.min(s,100):100).toString());let o=0;for await(const c of this._getPaginated("/annotation-queues",i))if(yield*c,o++,s!==void 0&&o>=s)break}async createAnnotationQueue(e){const{name:r,description:n,queueId:a,rubricInstructions:s}=e,i={name:r,description:n,id:a||Se(),rubric_instructions:s},o=JSON.stringify(Object.fromEntries(Object.entries(i).filter(([u,l])=>l!==void 0)));return(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await M(u,"create annotation queue"),u})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${K(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(e,r){const{name:n,description:a,rubricInstructions:s}=r,i=JSON.stringify({name:n,description:a,rubric_instructions:s});await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/annotation-queues/${K(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await M(o,"update annotation queue",!0),o})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${K(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(r,"delete annotation queue",!0),r})}async addRunsToAnnotationQueue(e,r){const n=JSON.stringify(r.map((a,s)=>K(a,`runIds[${s}]`).toString()));await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/annotation-queues/${K(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await M(a,"add runs to annotation queue",!0),a})}async getRunFromAnnotationQueue(e,r){const n=`/annotation-queues/${K(e,"queueId")}/run`;return(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${n}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(s,"get run from annotation queue"),s})).json()}async deleteRunFromAnnotationQueue(e,r){await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${K(e,"queueId")}/runs/${K(r,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(n,"delete run from annotation queue",!0),n})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${K(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(n,"get size from annotation queue"),n})).json()}async _currentTenantIsOwner(e){const r=await this._getSettings();return e=="-"||r.tenant_handle===e}async _ownerConflictError(e,r){const n=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
43
41
 
44
42
  Current tenant: ${n.tenant_handle}
45
43
 
46
- Requested tenant: ${r}`)}async _getLatestCommitHash(e){const n=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(a,"get latest commit hash"),a})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(e,r){const[n,a,s]=lt(e),i=JSON.stringify({like:r});return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/likes/${n}/${a}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await L(c,`${r?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(e){const[r,n,a]=lt(e);if(await this._currentTenantIsOwner(r)){const s=await this._getSettings();return a!=="latest"?`${this.getHostUrl()}/prompts/${n}/${a.substring(0,8)}?organizationId=${s.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${s.id}`}else return a!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${a.substring(0,8)}`:`${this.getHostUrl()}/hub/${r}/${n}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){for await(const r of this._getPaginated(`/commits/${e}/`,new URLSearchParams,n=>n.commits))yield*r}async*listPrompts(e){const r=new URLSearchParams;r.append("sort_field",e?.sortField??"updated_at"),r.append("sort_direction","desc"),r.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&r.append("is_public",e.isPublic.toString()),e?.query&&r.append("query",e.query);for await(const n of this._getPaginated("/repos",r,a=>a.repos))yield*n}async getPrompt(e){const[r,n,a]=lt(e),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return o?.status===404?null:(await L(o,"get prompt"),o)}))?.json();return i?.repo?i.repo:null}async createPrompt(e,r){const n=await this._getSettings();if(r?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
44
+ Requested tenant: ${r}`)}async _getLatestCommitHash(e){const n=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(a,"get latest commit hash"),a})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(e,r){const[n,a,s]=ut(e),i=JSON.stringify({like:r});return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/likes/${n}/${a}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await M(c,`${r?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(e){const[r,n,a]=ut(e);if(await this._currentTenantIsOwner(r)){const s=await this._getSettings();return a!=="latest"?`${this.getHostUrl()}/prompts/${n}/${a.substring(0,8)}?organizationId=${s.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${s.id}`}else return a!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${a.substring(0,8)}`:`${this.getHostUrl()}/hub/${r}/${n}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){for await(const r of this._getPaginated(`/commits/${e}/`,new URLSearchParams,n=>n.commits))yield*r}async*listPrompts(e){const r=new URLSearchParams;r.append("sort_field",e?.sortField??"updated_at"),r.append("sort_direction","desc"),r.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&r.append("is_public",e.isPublic.toString()),e?.query&&r.append("query",e.query);for await(const n of this._getPaginated("/repos",r,a=>a.repos))yield*n}async getPrompt(e){const[r,n,a]=ut(e),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return o?.status===404?null:(await M(o,"get prompt"),o)}))?.json();return i?.repo?i.repo:null}async createPrompt(e,r){const n=await this._getSettings();if(r?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
47
45
 
48
46
  creating a LangChain Hub handle.
49
47
  You can add a handle by creating a public prompt at:
50
48
 
51
- https://smith.langchain.com/prompts`);const[a,s,i]=lt(e);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError("create a prompt",a);const o={repo_handle:s,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},c=JSON.stringify(o),u=await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await L(d,"create prompt"),d}),{repo:l}=await u.json();return l}async createCommit(e,r,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[a,s,i]=lt(e),o=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${a}/${s}`):n?.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(r)),parent_commit:o},u=JSON.stringify(c),d=await(await this.caller.call(async()=>{const f=await this._fetch(`${this.apiUrl}/commits/${a}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await L(f,"create commit"),f})).json();return this._getPromptUrl(`${a}/${s}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(e,r=[]){return this._updateExamplesMultipart(e,r)}async _updateExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const n=new FormData;for(const i of r){const o=i.id,c={...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split}},u=Le(c,`Serializing body for example with id: ${o}`),l=new Blob([u],{type:"application/json"});if(n.append(o,l),i.inputs){const d=Le(i.inputs,`Serializing inputs for example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.inputs`,f)}if(i.outputs){const d=Le(i.outputs,`Serializing outputs whle updating example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.outputs`,f)}if(i.attachments)for(const[d,f]of Object.entries(i.attachments)){let h,p;Array.isArray(f)?[h,p]=f:(h=f.mimeType,p=f.data);const m=new Blob([p],{type:`${h}; length=${p.byteLength}`});n.append(`${o}.attachment.${d}`,m)}if(i.attachments_operations){const d=Le(i.attachments_operations,`Serializing attachments while updating example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.attachments_operations`,f)}}const a=e??r[0]?.dataset_id;return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${a}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await L(i,"update examples"),i})).json()}async uploadExamplesMultipart(e,r=[]){return this._uploadExamplesMultipart(e,r)}async _uploadExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const n=new FormData;for(const s of r){const i=(s.id??Te()).toString(),o={created_at:s.created_at,...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split},...s.source_run_id&&{source_run_id:s.source_run_id},...s.use_source_run_io&&{use_source_run_io:s.use_source_run_io},...s.use_source_run_attachments&&{use_source_run_attachments:s.use_source_run_attachments}},c=Le(o,`Serializing body for uploaded example with id: ${i}`),u=new Blob([c],{type:"application/json"});if(n.append(i,u),s.inputs){const l=Le(s.inputs,`Serializing inputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});n.append(`${i}.inputs`,d)}if(s.outputs){const l=Le(s.outputs,`Serializing outputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});n.append(`${i}.outputs`,d)}if(s.attachments)for(const[l,d]of Object.entries(s.attachments)){let f,h;Array.isArray(d)?[f,h]=d:(f=d.mimeType,h=d.data);const p=new Blob([h],{type:`${f}; length=${h.byteLength}`});n.append(`${i}.attachment.${l}`,p)}}return(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await L(s,"upload examples"),s})).json()}async updatePrompt(e,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[n,a]=lt(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);const s={};if(r?.description!==void 0&&(s.description=r.description),r?.readme!==void 0&&(s.readme=r.readme),r?.tags!==void 0&&(s.tags=r.tags),r?.isPublic!==void 0&&(s.is_public=r.isPublic),r?.isArchived!==void 0&&(s.is_archived=r.isArchived),Object.keys(s).length===0)throw new Error("No valid update options provided");const i=JSON.stringify(s);return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/repos/${n}/${a}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await L(c,"update prompt"),c})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[r,n,a]=lt(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(i,"delete prompt"),i})).json()}async pullPromptCommit(e,r){const[n,a,s]=lt(e),o=await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/commits/${n}/${a}/${s}${r?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(c,"pull prompt commit"),c})).json();return{owner:n,repo:a,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async _pullPrompt(e,r){const n=await this.pullPromptCommit(e,{includeModel:r?.includeModel});return JSON.stringify(n.manifest)}async pushPrompt(e,r){return await this.promptExists(e)?r&&Object.keys(r).some(a=>a!=="object")&&await this.updatePrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}):await this.createPrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}),r?.object?await this.createCommit(e,r?.object,{parentCommitHash:r?.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,r={}){const{sourceApiUrl:n=this.apiUrl,datasetName:a}=r,[s,i]=this.parseTokenOrUrl(e,n),o=new yr({apiUrl:s,apiKey:"placeholder"}),c=await o.readSharedDataset(i),u=a||c.name;try{if(await this.hasDataset({datasetId:u})){console.log(`Dataset ${u} already exists in your tenant. Skipping.`);return}}catch{}const l=await o.listSharedExamples(i),d=await this.createDataset(u,{description:c.description,dataType:c.data_type||"kv",inputsSchema:c.inputs_schema_definition??void 0,outputsSchema:c.outputs_schema_definition??void 0});try{await this.createExamples({inputs:l.map(f=>f.inputs),outputs:l.flatMap(f=>f.outputs?[f.outputs]:[]),datasetId:d.id})}catch(f){throw console.error(`An error occurred while creating dataset ${u}. You should delete it manually.`),f}}parseTokenOrUrl(e,r,n=2,a="dataset"){try{return K(e),[r,e]}catch{}try{const i=new URL(e).pathname.split("/").filter(o=>o!=="");if(i.length>=n){const o=i[i.length-n];return[r,o]}else throw new Error(`Invalid public ${a} URL: ${e}`)}catch{throw new Error(`Invalid public ${a} URL or token: ${e}`)}}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await Af()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function Po(t){return"dataset_id"in t||"dataset_name"in t}const Ch=t=>!!["TRACING_V2","TRACING"].find(r=>ke(r)==="true"),ka=Symbol.for("lc:context_variables");function Nh(t){return t.replace(/[-:.]/g,"")}function su(t,e,r=1){const n=r.toFixed(0).slice(0,3).padStart(3,"0"),a=`${new Date(t).toISOString().slice(0,-1)}${n}Z`;return{dottedOrder:Nh(a)+e,microsecondPrecisionDatestring:a}}class nn{constructor(e,r,n,a){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=r,this.project_name=n,this.replicas=a}static fromHeader(e){const r=e.split(",");let n={},a=[],s,i;for(const o of r){const[c,u]=o.split("="),l=decodeURIComponent(u);c==="langsmith-metadata"?n=JSON.parse(l):c==="langsmith-tags"?a=l.split(","):c==="langsmith-project"?s=l:c==="langsmith-replicas"&&(i=JSON.parse(l))}return new nn(n,a,s,i)}toHeader(){const e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}}class Re{constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Ph(e)){Object.assign(this,{...e});return}const r=Re.getDefaultConfig(),{metadata:n,...a}=e,s=a.client??Re.getSharedClient(),i={...n,...a?.extra?.metadata};if(a.extra={...a.extra,metadata:i},"id"in a&&a.id==null&&delete a.id,Object.assign(this,{...r,...a,client:s}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=Uh(this.replicas),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){const{dottedOrder:o,microsecondPrecisionDatestring:c}=su(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+o:this.dotted_order=o,this._serialized_start_time=c}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){return{id:Te(),run_type:"chain",project_name:Hc(),child_runs:[],api_url:et("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:et("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return Re.sharedClient||(Re.sharedClient=new yr),Re.sharedClient}createChild(e){const r=this.child_execution_order+1,n=new Re({...e,parent_run:this,project_name:this.project_name,replicas:this.replicas,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:r,child_execution_order:r});ka in this&&(n[ka]=this[ka]);const a=Symbol.for("lc:child_config"),s=e.extra?.[a]??this.extra[a];if(Lh(s)){const c={...s},u=Mh(c.callbacks)?c.callbacks.copy?.():void 0;u&&(Object.assign(u,{_parentRunId:n.id}),u.handlers?.find(iu)?.updateFromRunTree?.(n),c.callbacks=u),n.extra[a]=c}const i=new Set;let o=this;for(;o!=null&&!i.has(o.id);)i.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,r),o=o.parent_run;return this.child_runs.push(n),n}async end(e,r,n=Date.now(),a){this.outputs=this.outputs??e,this.error=this.error??r,this.end_time=this.end_time??n,a&&Object.keys(a).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...a}}:{metadata:a})}_convertToCreate(e,r,n=!0){const a=e.extra??{};if(a?.runtime?.library===void 0&&(a.runtime||(a.runtime={}),r))for(const[o,c]of Object.entries(r))a.runtime[o]||(a.runtime[o]=c);let s,i;return n?(i=e.parent_run?.id??e.parent_run_id,s=[]):(s=e.child_runs.map(o=>this._convertToCreate(o,r,n)),i=void 0),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:a,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:s,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_remapForProject(e,r,n=!0){const a=this._convertToCreate(this,r,n);if(e===this.project_name)return a;const s=d=>yi(`${d}:${e}`,yi.DNS),i=s(a.id),o=a.trace_id?s(a.trace_id):void 0,c=a.parent_run_id?s(a.parent_run_id):void 0;let u;if(a.dotted_order){const d=jh(a.dotted_order),f=[];for(let p=0;p<d.length-1;p++){const[m,g]=d[p],y=s(g);f.push(m.toISOString().replace(/[-:]/g,"").replace(".","")+y)}const[h]=d[d.length-1];f.push(h.toISOString().replace(/[-:]/g,"").replace(".","")+i),u=f.join(".")}else u=void 0;return{...a,id:i,trace_id:o,parent_run_id:c,dotted_order:u,session_name:e}}async postRun(e=!0){try{const r=Wc();if(this.replicas&&this.replicas.length>0)for(const{projectName:n,apiKey:a,apiUrl:s,workspaceId:i}of this.replicas){const o=this._remapForProject(n??this.project_name,r,!0);await this.client.createRun(o,{apiKey:a,apiUrl:s,workspaceId:i})}else{const n=this._convertToCreate(this,r,e);await this.client.createRun(n)}if(!e){Ja("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const n of this.child_runs)await n.postRun(!1)}}catch(r){console.error(`Error in postRun for run ${this.id}:`,r)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(const{projectName:r,apiKey:n,apiUrl:a,workspaceId:s,updates:i}of this.replicas){const o=this._remapForProject(r??this.project_name),c={id:o.id,outputs:o.outputs,error:o.error,parent_run_id:o.parent_run_id,session_name:o.session_name,reference_example_id:o.reference_example_id,end_time:o.end_time,dotted_order:o.dotted_order,trace_id:o.trace_id,events:o.events,tags:o.tags,extra:o.extra,attachments:this.attachments,...i};e?.excludeInputs||(c.inputs=o.inputs),await this.client.updateRun(o.id,c,{apiKey:n,apiUrl:a,workspaceId:s})}else try{const r={end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e?.excludeInputs||(r.inputs=this.inputs),await this.client.updateRun(this.id,r)}catch(r){console.error(`Error in patchRun for run ${this.id}`,r)}}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,r){const n=e?.callbacks;let a,s,i,o=Ch();if(n){const u=n?.getParentRunId?.()??"",l=n?.handlers?.find(d=>d?.name=="langchain_tracer");a=l?.getRun?.(u),s=l?.projectName,i=l?.client,o=o||!!l}return a?new Re({name:a.name,id:a.id,trace_id:a.trace_id,dotted_order:a.dotted_order,client:i,tracingEnabled:o,project_name:s,tags:[...new Set((a?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...a?.extra?.metadata,...e?.metadata}}}).createChild(r):new Re({...r,client:i,tracingEnabled:o,project_name:s})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,r){const n="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,a=n["langsmith-trace"];if(!a||typeof a!="string")return;const s=a.trim(),i=s.split(".").map(u=>{const[l,d]=u.split("Z");return{strTime:l,time:Date.parse(l+"Z"),uuid:d}}),o=i[0].uuid,c={...r,name:r?.name??"parent",run_type:r?.run_type??"chain",start_time:r?.start_time??Date.now(),id:i.at(-1)?.uuid,trace_id:o,dotted_order:s};if(n.baggage&&typeof n.baggage=="string"){const u=nn.fromHeader(n.baggage);c.metadata=u.metadata,c.tags=u.tags,c.project_name=u.project_name,c.replicas=u.replicas}return new Re(c)}toHeaders(e){const r={"langsmith-trace":this.dotted_order,baggage:new nn(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(const[n,a]of Object.entries(r))e.set(n,a);return r}}Object.defineProperty(Re,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function Ph(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}function iu(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}function Mo(t){return Array.isArray(t)&&t.some(e=>iu(e))}function Mh(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}function Lh(t){return t!=null&&typeof t.callbacks=="object"&&(Mo(t.callbacks?.handlers)||Mo(t.callbacks))}function jh(t){return t.split(".").map(r=>{const n=r.slice(0,-36),a=r.slice(-36),s=parseInt(n.slice(0,4)),i=parseInt(n.slice(4,6))-1,o=parseInt(n.slice(6,8)),c=parseInt(n.slice(9,11)),u=parseInt(n.slice(11,13)),l=parseInt(n.slice(13,15)),d=parseInt(n.slice(15,21));return[new Date(s,i,o,c,u,l,d/1e3),a]})}function Dh(){const t=et("LANGSMITH_RUNS_ENDPOINTS");if(!t)return[];try{const e=JSON.parse(t);if(Array.isArray(e)){const r=[];for(const n of e){if(typeof n!="object"||n===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}r.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key})}return r}else if(typeof e=="object"&&e!==null){Fh(e);const r=[];for(const[n,a]of Object.entries(e)){const s=n.replace(/\/$/,"");if(typeof a=="string")r.push({apiUrl:s,apiKey:a});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof a}`);continue}}return r}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof e}`),[]}catch(e){if(_h(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function Uh(t){return t?t.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):Dh()}function Fh(t){if(Object.keys(t).length>0&&ke("ENDPOINT"))throw new yh}var Bh={};me(Bh,{BaseTracer:()=>Kt,isBaseTracer:()=>Lt});const zh=t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t};function Ka(t,e){if(t)return new Re({...t,start_time:t._serialized_start_time??t.start_time,parent_run:Ka(e),child_runs:t.child_runs.map(r=>Ka(r)).filter(r=>r!==void 0),extra:{...t.extra,runtime:Bc()},tracingEnabled:!1})}function $a(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}function Lt(t){return typeof t._addRunToRunMap=="function"}var Kt=class extends Ar{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(t){super(...arguments)}copy(){return this}getRunById(t){if(t!==void 0)return this.usesRunTreeMap?zh(this.runTreeMap.get(t)):this.runMap.get(t)}stringifyError(t){return t instanceof Error?t.message+(t?.stack?`
49
+ https://smith.langchain.com/prompts`);const[a,s,i]=ut(e);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError("create a prompt",a);const o={repo_handle:s,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},c=JSON.stringify(o),u=await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await M(d,"create prompt"),d}),{repo:l}=await u.json();return l}async createCommit(e,r,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[a,s,i]=ut(e),o=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${a}/${s}`):n?.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(r)),parent_commit:o},u=JSON.stringify(c),d=await(await this.caller.call(async()=>{const f=await this._fetch(`${this.apiUrl}/commits/${a}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await M(f,"create commit"),f})).json();return this._getPromptUrl(`${a}/${s}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(e,r=[]){return this._updateExamplesMultipart(e,r)}async _updateExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const n=new FormData;for(const i of r){const o=i.id,c={...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split}},u=Pe(c,`Serializing body for example with id: ${o}`),l=new Blob([u],{type:"application/json"});if(n.append(o,l),i.inputs){const d=Pe(i.inputs,`Serializing inputs for example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.inputs`,f)}if(i.outputs){const d=Pe(i.outputs,`Serializing outputs whle updating example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.outputs`,f)}if(i.attachments)for(const[d,f]of Object.entries(i.attachments)){let h,p;Array.isArray(f)?[h,p]=f:(h=f.mimeType,p=f.data);const g=new Blob([p],{type:`${h}; length=${p.byteLength}`});n.append(`${o}.attachment.${d}`,g)}if(i.attachments_operations){const d=Pe(i.attachments_operations,`Serializing attachments while updating example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.attachments_operations`,f)}}const a=e??r[0]?.dataset_id;return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${a}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await M(i,"update examples"),i})).json()}async uploadExamplesMultipart(e,r=[]){return this._uploadExamplesMultipart(e,r)}async _uploadExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const n=new FormData;for(const s of r){const i=(s.id??Se()).toString(),o={created_at:s.created_at,...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split},...s.source_run_id&&{source_run_id:s.source_run_id},...s.use_source_run_io&&{use_source_run_io:s.use_source_run_io},...s.use_source_run_attachments&&{use_source_run_attachments:s.use_source_run_attachments}},c=Pe(o,`Serializing body for uploaded example with id: ${i}`),u=new Blob([c],{type:"application/json"});if(n.append(i,u),s.inputs){const l=Pe(s.inputs,`Serializing inputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});n.append(`${i}.inputs`,d)}if(s.outputs){const l=Pe(s.outputs,`Serializing outputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});n.append(`${i}.outputs`,d)}if(s.attachments)for(const[l,d]of Object.entries(s.attachments)){let f,h;Array.isArray(d)?[f,h]=d:(f=d.mimeType,h=d.data);const p=new Blob([h],{type:`${f}; length=${h.byteLength}`});n.append(`${i}.attachment.${l}`,p)}}return(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await M(s,"upload examples"),s})).json()}async updatePrompt(e,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[n,a]=ut(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);const s={};if(r?.description!==void 0&&(s.description=r.description),r?.readme!==void 0&&(s.readme=r.readme),r?.tags!==void 0&&(s.tags=r.tags),r?.isPublic!==void 0&&(s.is_public=r.isPublic),r?.isArchived!==void 0&&(s.is_archived=r.isArchived),Object.keys(s).length===0)throw new Error("No valid update options provided");const i=JSON.stringify(s);return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/repos/${n}/${a}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await M(c,"update prompt"),c})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[r,n,a]=ut(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(i,"delete prompt"),i})).json()}async pullPromptCommit(e,r){const[n,a,s]=ut(e),o=await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/commits/${n}/${a}/${s}${r?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await M(c,"pull prompt commit"),c})).json();return{owner:n,repo:a,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async _pullPrompt(e,r){const n=await this.pullPromptCommit(e,{includeModel:r?.includeModel});return JSON.stringify(n.manifest)}async pushPrompt(e,r){return await this.promptExists(e)?r&&Object.keys(r).some(a=>a!=="object")&&await this.updatePrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}):await this.createPrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}),r?.object?await this.createCommit(e,r?.object,{parentCommitHash:r?.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,r={}){const{sourceApiUrl:n=this.apiUrl,datasetName:a}=r,[s,i]=this.parseTokenOrUrl(e,n),o=new gr({apiUrl:s,apiKey:"placeholder"}),c=await o.readSharedDataset(i),u=a||c.name;try{if(await this.hasDataset({datasetId:u})){console.log(`Dataset ${u} already exists in your tenant. Skipping.`);return}}catch{}const l=await o.listSharedExamples(i),d=await this.createDataset(u,{description:c.description,dataType:c.data_type||"kv",inputsSchema:c.inputs_schema_definition??void 0,outputsSchema:c.outputs_schema_definition??void 0});try{await this.createExamples({inputs:l.map(f=>f.inputs),outputs:l.flatMap(f=>f.outputs?[f.outputs]:[]),datasetId:d.id})}catch(f){throw console.error(`An error occurred while creating dataset ${u}. You should delete it manually.`),f}}parseTokenOrUrl(e,r,n=2,a="dataset"){try{return K(e),[r,e]}catch{}try{const i=new URL(e).pathname.split("/").filter(o=>o!=="");if(i.length>=n){const o=i[i.length-n];return[r,o]}else throw new Error(`Invalid public ${a} URL: ${e}`)}catch{throw new Error(`Invalid public ${a} URL or token: ${e}`)}}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await Sf()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function Co(t){return"dataset_id"in t||"dataset_name"in t}const Rh=t=>!!["TRACING_V2","TRACING"].find(r=>Oe(r)==="true"),Oa=Symbol.for("lc:context_variables");function Oh(t){return t.replace(/[-:.]/g,"")}function nu(t,e,r=1){const n=r.toFixed(0).slice(0,3).padStart(3,"0"),a=`${new Date(t).toISOString().slice(0,-1)}${n}Z`;return{dottedOrder:Oh(a)+e,microsecondPrecisionDatestring:a}}class rn{constructor(e,r,n,a){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=r,this.project_name=n,this.replicas=a}static fromHeader(e){const r=e.split(",");let n={},a=[],s,i;for(const o of r){const[c,u]=o.split("="),l=decodeURIComponent(u);c==="langsmith-metadata"?n=JSON.parse(l):c==="langsmith-tags"?a=l.split(","):c==="langsmith-project"?s=l:c==="langsmith-replicas"&&(i=JSON.parse(l))}return new rn(n,a,s,i)}toHeader(){const e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}}class Re{constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),$h(e)){Object.assign(this,{...e});return}const r=Re.getDefaultConfig(),{metadata:n,...a}=e,s=a.client??Re.getSharedClient(),i={...n,...a?.extra?.metadata};if(a.extra={...a.extra,metadata:i},"id"in a&&a.id==null&&delete a.id,Object.assign(this,{...r,...a,client:s}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=Lh(this.replicas),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){const{dottedOrder:o,microsecondPrecisionDatestring:c}=nu(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+o:this.dotted_order=o,this._serialized_start_time=c}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){return{id:Se(),run_type:"chain",project_name:qc(),child_runs:[],api_url:Qe("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Qe("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return Re.sharedClient||(Re.sharedClient=new gr),Re.sharedClient}createChild(e){const r=this.child_execution_order+1,n=new Re({...e,parent_run:this,project_name:this.project_name,replicas:this.replicas,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:r,child_execution_order:r});Oa in this&&(n[Oa]=this[Oa]);const a=Symbol.for("lc:child_config"),s=e.extra?.[a]??this.extra[a];if(Ch(s)){const c={...s},u=kh(c.callbacks)?c.callbacks.copy?.():void 0;u&&(Object.assign(u,{_parentRunId:n.id}),u.handlers?.find(au)?.updateFromRunTree?.(n),c.callbacks=u),n.extra[a]=c}const i=new Set;let o=this;for(;o!=null&&!i.has(o.id);)i.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,r),o=o.parent_run;return this.child_runs.push(n),n}async end(e,r,n=Date.now(),a){this.outputs=this.outputs??e,this.error=this.error??r,this.end_time=this.end_time??n,a&&Object.keys(a).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...a}}:{metadata:a})}_convertToCreate(e,r,n=!0){const a=e.extra??{};if(a?.runtime?.library===void 0&&(a.runtime||(a.runtime={}),r))for(const[o,c]of Object.entries(r))a.runtime[o]||(a.runtime[o]=c);let s,i;return n?(i=e.parent_run?.id??e.parent_run_id,s=[]):(s=e.child_runs.map(o=>this._convertToCreate(o,r,n)),i=void 0),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:a,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:s,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_remapForProject(e,r,n=!0){const a=this._convertToCreate(this,r,n);if(e===this.project_name)return a;const s=d=>mi(`${d}:${e}`,mi.DNS),i=s(a.id),o=a.trace_id?s(a.trace_id):void 0,c=a.parent_run_id?s(a.parent_run_id):void 0;let u;if(a.dotted_order){const d=Nh(a.dotted_order),f=[];for(let p=0;p<d.length-1;p++){const[g,m]=d[p],_=s(m);f.push(g.toISOString().replace(/[-:]/g,"").replace(".","")+_)}const[h]=d[d.length-1];f.push(h.toISOString().replace(/[-:]/g,"").replace(".","")+i),u=f.join(".")}else u=void 0;return{...a,id:i,trace_id:o,parent_run_id:c,dotted_order:u,session_name:e}}async postRun(e=!0){try{const r=Vc();if(this.replicas&&this.replicas.length>0)for(const{projectName:n,apiKey:a,apiUrl:s,workspaceId:i}of this.replicas){const o=this._remapForProject(n??this.project_name,r,!0);await this.client.createRun(o,{apiKey:a,apiUrl:s,workspaceId:i})}else{const n=this._convertToCreate(this,r,e);await this.client.createRun(n)}if(!e){Va("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const n of this.child_runs)await n.postRun(!1)}}catch(r){console.error(`Error in postRun for run ${this.id}:`,r)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(const{projectName:r,apiKey:n,apiUrl:a,workspaceId:s,updates:i}of this.replicas){const o=this._remapForProject(r??this.project_name),c={id:o.id,outputs:o.outputs,error:o.error,parent_run_id:o.parent_run_id,session_name:o.session_name,reference_example_id:o.reference_example_id,end_time:o.end_time,dotted_order:o.dotted_order,trace_id:o.trace_id,events:o.events,tags:o.tags,extra:o.extra,attachments:this.attachments,...i};e?.excludeInputs||(c.inputs=o.inputs),await this.client.updateRun(o.id,c,{apiKey:n,apiUrl:a,workspaceId:s})}else try{const r={end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e?.excludeInputs||(r.inputs=this.inputs),await this.client.updateRun(this.id,r)}catch(r){console.error(`Error in patchRun for run ${this.id}`,r)}}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,r){const n=e?.callbacks;let a,s,i,o=Rh();if(n){const u=n?.getParentRunId?.()??"",l=n?.handlers?.find(d=>d?.name=="langchain_tracer");a=l?.getRun?.(u),s=l?.projectName,i=l?.client,o=o||!!l}return a?new Re({name:a.name,id:a.id,trace_id:a.trace_id,dotted_order:a.dotted_order,client:i,tracingEnabled:o,project_name:s,tags:[...new Set((a?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...a?.extra?.metadata,...e?.metadata}}}).createChild(r):new Re({...r,client:i,tracingEnabled:o,project_name:s})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,r){const n="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,a=n["langsmith-trace"];if(!a||typeof a!="string")return;const s=a.trim(),i=s.split(".").map(u=>{const[l,d]=u.split("Z");return{strTime:l,time:Date.parse(l+"Z"),uuid:d}}),o=i[0].uuid,c={...r,name:r?.name??"parent",run_type:r?.run_type??"chain",start_time:r?.start_time??Date.now(),id:i.at(-1)?.uuid,trace_id:o,dotted_order:s};if(n.baggage&&typeof n.baggage=="string"){const u=rn.fromHeader(n.baggage);c.metadata=u.metadata,c.tags=u.tags,c.project_name=u.project_name,c.replicas=u.replicas}return new Re(c)}toHeaders(e){const r={"langsmith-trace":this.dotted_order,baggage:new rn(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(const[n,a]of Object.entries(r))e.set(n,a);return r}}Object.defineProperty(Re,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function $h(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}function au(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}function No(t){return Array.isArray(t)&&t.some(e=>au(e))}function kh(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}function Ch(t){return t!=null&&typeof t.callbacks=="object"&&(No(t.callbacks?.handlers)||No(t.callbacks))}function Nh(t){return t.split(".").map(r=>{const n=r.slice(0,-36),a=r.slice(-36),s=parseInt(n.slice(0,4)),i=parseInt(n.slice(4,6))-1,o=parseInt(n.slice(6,8)),c=parseInt(n.slice(9,11)),u=parseInt(n.slice(11,13)),l=parseInt(n.slice(13,15)),d=parseInt(n.slice(15,21));return[new Date(s,i,o,c,u,l,d/1e3),a]})}function Ph(){const t=Qe("LANGSMITH_RUNS_ENDPOINTS");if(!t)return[];try{const e=JSON.parse(t);if(Array.isArray(e)){const r=[];for(const n of e){if(typeof n!="object"||n===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}r.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key})}return r}else if(typeof e=="object"&&e!==null){Mh(e);const r=[];for(const[n,a]of Object.entries(e)){const s=n.replace(/\/$/,"");if(typeof a=="string")r.push({apiUrl:s,apiKey:a});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof a}`);continue}}return r}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof e}`),[]}catch(e){if(ph(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function Lh(t){return t?t.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):Ph()}function Mh(t){if(Object.keys(t).length>0&&Oe("ENDPOINT"))throw new hh}var jh={};me(jh,{BaseTracer:()=>Jt,isBaseTracer:()=>Lt});const Dh=t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t};function Ja(t,e){if(t)return new Re({...t,start_time:t._serialized_start_time??t.start_time,parent_run:Ja(e),child_runs:t.child_runs.map(r=>Ja(r)).filter(r=>r!==void 0),extra:{...t.extra,runtime:Uc()},tracingEnabled:!1})}function $a(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}function Lt(t){return typeof t._addRunToRunMap=="function"}var Jt=class extends Ir{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(t){super(...arguments)}copy(){return this}getRunById(t){if(t!==void 0)return this.usesRunTreeMap?Dh(this.runTreeMap.get(t)):this.runMap.get(t)}stringifyError(t){return t instanceof Error?t.message+(t?.stack?`
52
50
 
53
- ${t.stack}`:""):typeof t=="string"?t:`${t}`}_addChildRun(t,e){t.child_runs.push(e)}_addRunToRunMap(t){const{dottedOrder:e,microsecondPrecisionDatestring:r}=su(new Date(t.start_time).getTime(),t.id,t.execution_order),n={...t},a=this.getRunById(n.parent_run_id);if(n.parent_run_id!==void 0?a&&(this._addChildRun(a,n),a.child_execution_order=Math.max(a.child_execution_order,n.child_execution_order),n.trace_id=a.trace_id,a.dotted_order!==void 0&&(n.dotted_order=[a.dotted_order,e].join("."),n._serialized_start_time=r)):(n.trace_id=n.id,n.dotted_order=e,n._serialized_start_time=r),this.usesRunTreeMap){const s=Ka(n,a);s!==void 0&&this.runTreeMap.set(n.id,s)}else this.runMap.set(n.id,n);return n}async _endTrace(t){const e=t.parent_run_id!==void 0&&this.getRunById(t.parent_run_id);e?e.child_execution_order=Math.max(e.child_execution_order,t.child_execution_order):await this.persistRun(t),await this.onRunUpdate?.(t),this.usesRunTreeMap?this.runTreeMap.delete(t.id):this.runMap.delete(t.id)}_getExecutionOrder(t){const e=t!==void 0&&this.getRunById(t);return e?e.child_execution_order+1:1}_createRunForLLMStart(t,e,r,n,a,s,i,o){const c=this._getExecutionOrder(n),u=Date.now(),l=i?{...a,metadata:i}:a,d={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:e},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:l??{},tags:s||[]};return this._addRunToRunMap(d)}async handleLLMStart(t,e,r,n,a,s,i,o){const c=this.getRunById(r)??this._createRunForLLMStart(t,e,r,n,a,s,i,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(t,e,r,n,a,s,i,o){const c=this._getExecutionOrder(n),u=Date.now(),l=i?{...a,metadata:i}:a,d={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:e},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:l??{},tags:s||[]};return this._addRunToRunMap(d)}async handleChatModelStart(t,e,r,n,a,s,i,o){const c=this.getRunById(r)??this._createRunForChatModelStart(t,e,r,n,a,s,i,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(t,e,r,n,a){const s=this.getRunById(e);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.outputs=t,s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...a},await this.onLLMEnd?.(s),await this._endTrace(s),s}async handleLLMError(t,e,r,n,a){const s=this.getRunById(e);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(t),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...a},await this.onLLMError?.(s),await this._endTrace(s),s}_createRunForChainStart(t,e,r,n,a,s,i,o){const c=this._getExecutionOrder(n),u=Date.now(),l={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:e,execution_order:c,child_execution_order:c,run_type:i??"chain",child_runs:[],extra:s?{metadata:s}:{},tags:a||[]};return this._addRunToRunMap(l)}async handleChainStart(t,e,r,n,a,s,i,o){const c=this.getRunById(r)??this._createRunForChainStart(t,e,r,n,a,s,i,o);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(t,e,r,n,a){const s=this.getRunById(e);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.outputs=$a(t,"output"),s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),a?.inputs!==void 0&&(s.inputs=$a(a.inputs,"input")),await this.onChainEnd?.(s),await this._endTrace(s),s}async handleChainError(t,e,r,n,a){const s=this.getRunById(e);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(t),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),a?.inputs!==void 0&&(s.inputs=$a(a.inputs,"input")),await this.onChainError?.(s),await this._endTrace(s),s}_createRunForToolStart(t,e,r,n,a,s,i){const o=this._getExecutionOrder(n),c=Date.now(),u={id:r,name:i??t.id[t.id.length-1],parent_run_id:n,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:e},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:s?{metadata:s}:{},tags:a||[]};return this._addRunToRunMap(u)}async handleToolStart(t,e,r,n,a,s,i){const o=this.getRunById(r)??this._createRunForToolStart(t,e,r,n,a,s,i);return await this.onRunCreate?.(o),await this.onToolStart?.(o),o}async handleToolEnd(t,e){const r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(t,e){const r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(t,e){const r=this.getRunById(e);if(!r||r?.run_type!=="chain")return;const n=r;n.actions=n.actions||[],n.actions.push(t),n.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentAction?.(r)}async handleAgentEnd(t,e){const r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(t,e,r,n,a,s,i){const o=this._getExecutionOrder(n),c=Date.now(),u={id:r,name:i??t.id[t.id.length-1],parent_run_id:n,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:e},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:s?{metadata:s}:{},tags:a||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(t,e,r,n,a,s,i){const o=this.getRunById(r)??this._createRunForRetrieverStart(t,e,r,n,a,s,i);return await this.onRunCreate?.(o),await this.onRetrieverStart?.(o),o}async handleRetrieverEnd(t,e){const r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(t,e){const r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(t,e){const r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:t}}),await this.onText?.(r))}async handleLLMNewToken(t,e,r,n,a,s){const i=this.getRunById(r);if(!i||i?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return i.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:t,idx:e,chunk:s?.chunk}}),await this.onLLMNewToken?.(i,t,{chunk:s?.chunk}),i}},Hr={exports:{}};Hr.exports;var Lo;function qh(){return Lo||(Lo=1,(function(t){const r=(s=0)=>i=>`\x1B[${38+s};5;${i}m`,n=(s=0)=>(i,o,c)=>`\x1B[${38+s};2;${i};${o};${c}m`;function a(){const s=new Map,i={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};i.color.gray=i.color.blackBright,i.bgColor.bgGray=i.bgColor.bgBlackBright,i.color.grey=i.color.blackBright,i.bgColor.bgGrey=i.bgColor.bgBlackBright;for(const[o,c]of Object.entries(i)){for(const[u,l]of Object.entries(c))i[u]={open:`\x1B[${l[0]}m`,close:`\x1B[${l[1]}m`},c[u]=i[u],s.set(l[0],l[1]);Object.defineProperty(i,o,{value:c,enumerable:!1})}return Object.defineProperty(i,"codes",{value:s,enumerable:!1}),i.color.close="\x1B[39m",i.bgColor.close="\x1B[49m",i.color.ansi256=r(),i.color.ansi16m=n(),i.bgColor.ansi256=r(10),i.bgColor.ansi16m=n(10),Object.defineProperties(i,{rgbToAnsi256:{value:(o,c,u)=>o===c&&c===u?o<8?16:o>248?231:Math.round((o-8)/247*24)+232:16+36*Math.round(o/255*5)+6*Math.round(c/255*5)+Math.round(u/255*5),enumerable:!1},hexToRgb:{value:o=>{const c=/(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(o.toString(16));if(!c)return[0,0,0];let{colorString:u}=c.groups;u.length===3&&(u=u.split("").map(d=>d+d).join(""));const l=Number.parseInt(u,16);return[l>>16&255,l>>8&255,l&255]},enumerable:!1},hexToAnsi256:{value:o=>i.rgbToAnsi256(...i.hexToRgb(o)),enumerable:!1}}),i}Object.defineProperty(t,"exports",{enumerable:!0,get:a})})(Hr)),Hr.exports}var Gh=qh();const ou=br(Gh);var Hh={};me(Hh,{ConsoleCallbackHandler:()=>Ya});function be(t,e){return`${t.open}${e}${t.close}`}function je(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}function jo(t){return typeof t=="string"?t.trim():t==null?t:je(t,t.toString())}function dt(t){if(!t.end_time)return"";const e=t.end_time-t.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}const{color:Oe}=ou;var Ya=class extends Kt{name="console_callback_handler";persistRun(t){return Promise.resolve()}getParents(t){const e=[];let r=t;for(;r.parent_run_id;){const n=this.runMap.get(r.parent_run_id);if(n)e.push(n),r=n;else break}return e}getBreadcrumbs(t){const r=[...this.getParents(t).reverse(),t].map((n,a,s)=>{const i=`${n.execution_order}:${n.run_type}:${n.name}`;return a===s.length-1?be(ou.bold,i):i}).join(" > ");return be(Oe.grey,r)}onChainStart(t){const e=this.getBreadcrumbs(t);console.log(`${be(Oe.green,"[chain/start]")} [${e}] Entering Chain run with input: ${je(t.inputs,"[inputs]")}`)}onChainEnd(t){const e=this.getBreadcrumbs(t);console.log(`${be(Oe.cyan,"[chain/end]")} [${e}] [${dt(t)}] Exiting Chain run with output: ${je(t.outputs,"[outputs]")}`)}onChainError(t){const e=this.getBreadcrumbs(t);console.log(`${be(Oe.red,"[chain/error]")} [${e}] [${dt(t)}] Chain run errored with error: ${je(t.error,"[error]")}`)}onLLMStart(t){const e=this.getBreadcrumbs(t),r="prompts"in t.inputs?{prompts:t.inputs.prompts.map(n=>n.trim())}:t.inputs;console.log(`${be(Oe.green,"[llm/start]")} [${e}] Entering LLM run with input: ${je(r,"[inputs]")}`)}onLLMEnd(t){const e=this.getBreadcrumbs(t);console.log(`${be(Oe.cyan,"[llm/end]")} [${e}] [${dt(t)}] Exiting LLM run with output: ${je(t.outputs,"[response]")}`)}onLLMError(t){const e=this.getBreadcrumbs(t);console.log(`${be(Oe.red,"[llm/error]")} [${e}] [${dt(t)}] LLM run errored with error: ${je(t.error,"[error]")}`)}onToolStart(t){const e=this.getBreadcrumbs(t);console.log(`${be(Oe.green,"[tool/start]")} [${e}] Entering Tool run with input: "${jo(t.inputs.input)}"`)}onToolEnd(t){const e=this.getBreadcrumbs(t);console.log(`${be(Oe.cyan,"[tool/end]")} [${e}] [${dt(t)}] Exiting Tool run with output: "${jo(t.outputs?.output)}"`)}onToolError(t){const e=this.getBreadcrumbs(t);console.log(`${be(Oe.red,"[tool/error]")} [${e}] [${dt(t)}] Tool run errored with error: ${je(t.error,"[error]")}`)}onRetrieverStart(t){const e=this.getBreadcrumbs(t);console.log(`${be(Oe.green,"[retriever/start]")} [${e}] Entering Retriever run with input: ${je(t.inputs,"[inputs]")}`)}onRetrieverEnd(t){const e=this.getBreadcrumbs(t);console.log(`${be(Oe.cyan,"[retriever/end]")} [${e}] [${dt(t)}] Exiting Retriever run with output: ${je(t.outputs,"[outputs]")}`)}onRetrieverError(t){const e=this.getBreadcrumbs(t);console.log(`${be(Oe.red,"[retriever/error]")} [${e}] [${dt(t)}] Retriever run errored with error: ${je(t.error,"[error]")}`)}onAgentAction(t){const e=t,r=this.getBreadcrumbs(t);console.log(`${be(Oe.blue,"[agent/action]")} [${r}] Agent selected action: ${je(e.actions[e.actions.length-1],"[action]")}`)}};let Ca;const cu=()=>{if(Ca===void 0){const t=Et("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};Ca=new yr(t)}return Ca};let Zh=class{getStore(){}run(e,r){return r()}};const Na=Symbol.for("ls:tracing_async_local_storage"),Vh=new Zh;let Jh=class{getInstance(){return globalThis[Na]??Vh}initializeGlobalInstance(e){globalThis[Na]===void 0&&(globalThis[Na]=e)}};const Wh=new Jh;function Kh(t=!1){const e=Wh.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree.
51
+ ${t.stack}`:""):typeof t=="string"?t:`${t}`}_addChildRun(t,e){t.child_runs.push(e)}_addRunToRunMap(t){const{dottedOrder:e,microsecondPrecisionDatestring:r}=nu(new Date(t.start_time).getTime(),t.id,t.execution_order),n={...t},a=this.getRunById(n.parent_run_id);if(n.parent_run_id!==void 0?a&&(this._addChildRun(a,n),a.child_execution_order=Math.max(a.child_execution_order,n.child_execution_order),n.trace_id=a.trace_id,a.dotted_order!==void 0&&(n.dotted_order=[a.dotted_order,e].join("."),n._serialized_start_time=r)):(n.trace_id=n.id,n.dotted_order=e,n._serialized_start_time=r),this.usesRunTreeMap){const s=Ja(n,a);s!==void 0&&this.runTreeMap.set(n.id,s)}else this.runMap.set(n.id,n);return n}async _endTrace(t){const e=t.parent_run_id!==void 0&&this.getRunById(t.parent_run_id);e?e.child_execution_order=Math.max(e.child_execution_order,t.child_execution_order):await this.persistRun(t),await this.onRunUpdate?.(t),this.usesRunTreeMap?this.runTreeMap.delete(t.id):this.runMap.delete(t.id)}_getExecutionOrder(t){const e=t!==void 0&&this.getRunById(t);return e?e.child_execution_order+1:1}_createRunForLLMStart(t,e,r,n,a,s,i,o){const c=this._getExecutionOrder(n),u=Date.now(),l=i?{...a,metadata:i}:a,d={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:e},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:l??{},tags:s||[]};return this._addRunToRunMap(d)}async handleLLMStart(t,e,r,n,a,s,i,o){const c=this.getRunById(r)??this._createRunForLLMStart(t,e,r,n,a,s,i,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(t,e,r,n,a,s,i,o){const c=this._getExecutionOrder(n),u=Date.now(),l=i?{...a,metadata:i}:a,d={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:e},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:l??{},tags:s||[]};return this._addRunToRunMap(d)}async handleChatModelStart(t,e,r,n,a,s,i,o){const c=this.getRunById(r)??this._createRunForChatModelStart(t,e,r,n,a,s,i,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(t,e,r,n,a){const s=this.getRunById(e);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.outputs=t,s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...a},await this.onLLMEnd?.(s),await this._endTrace(s),s}async handleLLMError(t,e,r,n,a){const s=this.getRunById(e);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(t),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...a},await this.onLLMError?.(s),await this._endTrace(s),s}_createRunForChainStart(t,e,r,n,a,s,i,o){const c=this._getExecutionOrder(n),u=Date.now(),l={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:e,execution_order:c,child_execution_order:c,run_type:i??"chain",child_runs:[],extra:s?{metadata:s}:{},tags:a||[]};return this._addRunToRunMap(l)}async handleChainStart(t,e,r,n,a,s,i,o){const c=this.getRunById(r)??this._createRunForChainStart(t,e,r,n,a,s,i,o);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(t,e,r,n,a){const s=this.getRunById(e);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.outputs=$a(t,"output"),s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),a?.inputs!==void 0&&(s.inputs=$a(a.inputs,"input")),await this.onChainEnd?.(s),await this._endTrace(s),s}async handleChainError(t,e,r,n,a){const s=this.getRunById(e);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(t),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),a?.inputs!==void 0&&(s.inputs=$a(a.inputs,"input")),await this.onChainError?.(s),await this._endTrace(s),s}_createRunForToolStart(t,e,r,n,a,s,i){const o=this._getExecutionOrder(n),c=Date.now(),u={id:r,name:i??t.id[t.id.length-1],parent_run_id:n,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:e},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:s?{metadata:s}:{},tags:a||[]};return this._addRunToRunMap(u)}async handleToolStart(t,e,r,n,a,s,i){const o=this.getRunById(r)??this._createRunForToolStart(t,e,r,n,a,s,i);return await this.onRunCreate?.(o),await this.onToolStart?.(o),o}async handleToolEnd(t,e){const r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(t,e){const r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(t,e){const r=this.getRunById(e);if(!r||r?.run_type!=="chain")return;const n=r;n.actions=n.actions||[],n.actions.push(t),n.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentAction?.(r)}async handleAgentEnd(t,e){const r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(t,e,r,n,a,s,i){const o=this._getExecutionOrder(n),c=Date.now(),u={id:r,name:i??t.id[t.id.length-1],parent_run_id:n,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:e},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:s?{metadata:s}:{},tags:a||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(t,e,r,n,a,s,i){const o=this.getRunById(r)??this._createRunForRetrieverStart(t,e,r,n,a,s,i);return await this.onRunCreate?.(o),await this.onRetrieverStart?.(o),o}async handleRetrieverEnd(t,e){const r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(t,e){const r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(t,e){const r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:t}}),await this.onText?.(r))}async handleLLMNewToken(t,e,r,n,a,s){const i=this.getRunById(r);if(!i||i?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return i.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:t,idx:e,chunk:s?.chunk}}),await this.onLLMNewToken?.(i,t,{chunk:s?.chunk}),i}},Gr={exports:{}};Gr.exports;var Po;function Uh(){return Po||(Po=1,(function(t){const r=(s=0)=>i=>`\x1B[${38+s};5;${i}m`,n=(s=0)=>(i,o,c)=>`\x1B[${38+s};2;${i};${o};${c}m`;function a(){const s=new Map,i={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};i.color.gray=i.color.blackBright,i.bgColor.bgGray=i.bgColor.bgBlackBright,i.color.grey=i.color.blackBright,i.bgColor.bgGrey=i.bgColor.bgBlackBright;for(const[o,c]of Object.entries(i)){for(const[u,l]of Object.entries(c))i[u]={open:`\x1B[${l[0]}m`,close:`\x1B[${l[1]}m`},c[u]=i[u],s.set(l[0],l[1]);Object.defineProperty(i,o,{value:c,enumerable:!1})}return Object.defineProperty(i,"codes",{value:s,enumerable:!1}),i.color.close="\x1B[39m",i.bgColor.close="\x1B[49m",i.color.ansi256=r(),i.color.ansi16m=n(),i.bgColor.ansi256=r(10),i.bgColor.ansi16m=n(10),Object.defineProperties(i,{rgbToAnsi256:{value:(o,c,u)=>o===c&&c===u?o<8?16:o>248?231:Math.round((o-8)/247*24)+232:16+36*Math.round(o/255*5)+6*Math.round(c/255*5)+Math.round(u/255*5),enumerable:!1},hexToRgb:{value:o=>{const c=/(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(o.toString(16));if(!c)return[0,0,0];let{colorString:u}=c.groups;u.length===3&&(u=u.split("").map(d=>d+d).join(""));const l=Number.parseInt(u,16);return[l>>16&255,l>>8&255,l&255]},enumerable:!1},hexToAnsi256:{value:o=>i.rgbToAnsi256(...i.hexToRgb(o)),enumerable:!1}}),i}Object.defineProperty(t,"exports",{enumerable:!0,get:a})})(Gr)),Gr.exports}var Fh=Uh();const su=wr(Fh);var Bh={};me(Bh,{ConsoleCallbackHandler:()=>Ka});function be(t,e){return`${t.open}${e}${t.close}`}function Me(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}function Lo(t){return typeof t=="string"?t.trim():t==null?t:Me(t,t.toString())}function lt(t){if(!t.end_time)return"";const e=t.end_time-t.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}const{color:Ae}=su;var Ka=class extends Jt{name="console_callback_handler";persistRun(t){return Promise.resolve()}getParents(t){const e=[];let r=t;for(;r.parent_run_id;){const n=this.runMap.get(r.parent_run_id);if(n)e.push(n),r=n;else break}return e}getBreadcrumbs(t){const r=[...this.getParents(t).reverse(),t].map((n,a,s)=>{const i=`${n.execution_order}:${n.run_type}:${n.name}`;return a===s.length-1?be(su.bold,i):i}).join(" > ");return be(Ae.grey,r)}onChainStart(t){const e=this.getBreadcrumbs(t);console.log(`${be(Ae.green,"[chain/start]")} [${e}] Entering Chain run with input: ${Me(t.inputs,"[inputs]")}`)}onChainEnd(t){const e=this.getBreadcrumbs(t);console.log(`${be(Ae.cyan,"[chain/end]")} [${e}] [${lt(t)}] Exiting Chain run with output: ${Me(t.outputs,"[outputs]")}`)}onChainError(t){const e=this.getBreadcrumbs(t);console.log(`${be(Ae.red,"[chain/error]")} [${e}] [${lt(t)}] Chain run errored with error: ${Me(t.error,"[error]")}`)}onLLMStart(t){const e=this.getBreadcrumbs(t),r="prompts"in t.inputs?{prompts:t.inputs.prompts.map(n=>n.trim())}:t.inputs;console.log(`${be(Ae.green,"[llm/start]")} [${e}] Entering LLM run with input: ${Me(r,"[inputs]")}`)}onLLMEnd(t){const e=this.getBreadcrumbs(t);console.log(`${be(Ae.cyan,"[llm/end]")} [${e}] [${lt(t)}] Exiting LLM run with output: ${Me(t.outputs,"[response]")}`)}onLLMError(t){const e=this.getBreadcrumbs(t);console.log(`${be(Ae.red,"[llm/error]")} [${e}] [${lt(t)}] LLM run errored with error: ${Me(t.error,"[error]")}`)}onToolStart(t){const e=this.getBreadcrumbs(t);console.log(`${be(Ae.green,"[tool/start]")} [${e}] Entering Tool run with input: "${Lo(t.inputs.input)}"`)}onToolEnd(t){const e=this.getBreadcrumbs(t);console.log(`${be(Ae.cyan,"[tool/end]")} [${e}] [${lt(t)}] Exiting Tool run with output: "${Lo(t.outputs?.output)}"`)}onToolError(t){const e=this.getBreadcrumbs(t);console.log(`${be(Ae.red,"[tool/error]")} [${e}] [${lt(t)}] Tool run errored with error: ${Me(t.error,"[error]")}`)}onRetrieverStart(t){const e=this.getBreadcrumbs(t);console.log(`${be(Ae.green,"[retriever/start]")} [${e}] Entering Retriever run with input: ${Me(t.inputs,"[inputs]")}`)}onRetrieverEnd(t){const e=this.getBreadcrumbs(t);console.log(`${be(Ae.cyan,"[retriever/end]")} [${e}] [${lt(t)}] Exiting Retriever run with output: ${Me(t.outputs,"[outputs]")}`)}onRetrieverError(t){const e=this.getBreadcrumbs(t);console.log(`${be(Ae.red,"[retriever/error]")} [${e}] [${lt(t)}] Retriever run errored with error: ${Me(t.error,"[error]")}`)}onAgentAction(t){const e=t,r=this.getBreadcrumbs(t);console.log(`${be(Ae.blue,"[agent/action]")} [${r}] Agent selected action: ${Me(e.actions[e.actions.length-1],"[action]")}`)}};let ka;const iu=()=>{if(ka===void 0){const t=bt("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};ka=new gr(t)}return ka};let zh=class{getStore(){}run(e,r){return r()}};const Ca=Symbol.for("ls:tracing_async_local_storage"),qh=new zh;let Gh=class{getInstance(){return globalThis[Ca]??qh}initializeGlobalInstance(e){globalThis[Ca]===void 0&&(globalThis[Ca]=e)}};const Hh=new Gh;function Zh(t=!1){const e=Hh.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree.
54
52
 
55
- Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function Ms(t){return typeof t=="function"&&"langsmith:traceable"in t}var Yh={};me(Yh,{LangChainTracer:()=>Zr});var Zr=class uu extends Kt{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;constructor(e={}){super(e);const{exampleId:r,projectName:n,client:a,replicas:s}=e;this.projectName=n??Hc(),this.replicas=s,this.exampleId=r,this.client=a??cu();const i=uu.getTraceableRunTree();i&&this.updateFromRunTree(i)}async persistRun(e){}async onRunCreate(e){await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){await this.getRunTreeWithTracingConfig(e.id)?.patchRun()}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let r=e;const n=new Set;for(;r.parent_run&&!(n.has(r.id)||(n.add(r.id),!r.parent_run));)r=r.parent_run;n.clear();const a=[r];for(;a.length>0;){const s=a.shift();!s||n.has(s.id)||(n.add(s.id),this.runTreeMap.set(s.id,s),s.child_runs&&a.push(...s.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(e){const r=this.runTreeMap.get(e);if(r)return new Re({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return Kh(!0)}catch{return}}};let St;function Xh(){const t="default"in at?at.default:at;return new t({autoStart:!0,concurrency:1})}function Qh(){return typeof St>"u"&&(St=Xh()),St}async function de(t,e){if(e===!0){const r=gr();r!==void 0?await r.run(void 0,async()=>t()):await t()}else St=Qh(),St.add(async()=>{const r=gr();r!==void 0?await r.run(void 0,async()=>t()):await t()})}async function ep(){const t=cu();await Promise.allSettled([typeof St<"u"?St.onIdle():Promise.resolve(),t.awaitPendingTraceBatches()])}var tp={};me(tp,{awaitAllCallbacks:()=>ep,consumeCallback:()=>de});const rp=t=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(r=>Et(r)==="true");function lu(t){const e=gr();return e===void 0?void 0:e.getStore()?.[ir]?.[t]}const np=Symbol("lc:configure_hooks"),ap=()=>lu(np)||[];var sp={};me(sp,{BaseCallbackManager:()=>du,BaseRunManager:()=>Rr,CallbackManager:()=>Ct,CallbackManagerForChainRun:()=>hu,CallbackManagerForLLMRun:()=>Xa,CallbackManagerForRetrieverRun:()=>fu,CallbackManagerForToolRun:()=>pu,ensureHandler:()=>_r,parseCallbackConfigArg:()=>ip});function ip(t){return t?Array.isArray(t)||"name"in t?{callbacks:t}:t:{}}var du=class{setHandler(t){return this.setHandlers([t])}},Rr=class{constructor(t,e,r,n,a,s,i,o){this.runId=t,this.handlers=e,this.inheritableHandlers=r,this.tags=n,this.inheritableTags=a,this.metadata=s,this.inheritableMetadata=i,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(e=>de(async()=>{try{await e.handleText?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleText: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleCustomEvent(t,e,r,n,a){await Promise.all(this.handlers.map(s=>de(async()=>{try{await s.handleCustomEvent?.(t,e,this.runId,this.tags,this.metadata)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleCustomEvent: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}},fu=class extends Rr{getChild(t){const e=new Ct(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleRetrieverEnd(t){await Promise.all(this.handlers.map(e=>de(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetriever`),e.raiseError)throw r}},e.awaitHandlers)))}async handleRetrieverError(t){await Promise.all(this.handlers.map(e=>de(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetrieverError: ${r}`),e.raiseError)throw t}},e.awaitHandlers)))}},Xa=class extends Rr{async handleLLMNewToken(t,e,r,n,a,s){await Promise.all(this.handlers.map(i=>de(async()=>{if(!i.ignoreLLM)try{await i.handleLLMNewToken?.(t,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,s)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMNewToken: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleLLMError(t,e,r,n,a){await Promise.all(this.handlers.map(s=>de(async()=>{if(!s.ignoreLLM)try{await s.handleLLMError?.(t,this.runId,this._parentRunId,this.tags,a)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMError: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}async handleLLMEnd(t,e,r,n,a){await Promise.all(this.handlers.map(s=>de(async()=>{if(!s.ignoreLLM)try{await s.handleLLMEnd?.(t,this.runId,this._parentRunId,this.tags,a)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMEnd: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}},hu=class extends Rr{getChild(t){const e=new Ct(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleChainError(t,e,r,n,a){await Promise.all(this.handlers.map(s=>de(async()=>{if(!s.ignoreChain)try{await s.handleChainError?.(t,this.runId,this._parentRunId,this.tags,a)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainError: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}async handleChainEnd(t,e,r,n,a){await Promise.all(this.handlers.map(s=>de(async()=>{if(!s.ignoreChain)try{await s.handleChainEnd?.(t,this.runId,this._parentRunId,this.tags,a)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainEnd: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(e=>de(async()=>{if(!e.ignoreAgent)try{await e.handleAgentAction?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentAction: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleAgentEnd(t){await Promise.all(this.handlers.map(e=>de(async()=>{if(!e.ignoreAgent)try{await e.handleAgentEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},pu=class extends Rr{getChild(t){const e=new Ct(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleToolError(t){await Promise.all(this.handlers.map(e=>de(async()=>{if(!e.ignoreAgent)try{await e.handleToolError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolError: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEnd(t){await Promise.all(this.handlers.map(e=>de(async()=>{if(!e.ignoreAgent)try{await e.handleToolEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},Ct=class rr extends du{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(e,r){super(),this.handlers=r?.handlers??this.handlers,this.inheritableHandlers=r?.inheritableHandlers??this.inheritableHandlers,this.tags=r?.tags??this.tags,this.inheritableTags=r?.inheritableTags??this.inheritableTags,this.metadata=r?.metadata??this.metadata,this.inheritableMetadata=r?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,r,n=void 0,a=void 0,s=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(r.map(async(u,l)=>{const d=l===0&&n?n:Te();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return Lt(f)&&f._createRunForLLMStart(e,[u],d,this._parentRunId,s,this.tags,this.metadata,c),de(async()=>{try{await f.handleLLMStart?.(e,[u],d,this._parentRunId,s,this.tags,this.metadata,c)}catch(h){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${h}`),f.raiseError)throw h}},f.awaitHandlers)})),new Xa(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,r,n=void 0,a=void 0,s=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(r.map(async(u,l)=>{const d=l===0&&n?n:Te();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return Lt(f)&&f._createRunForChatModelStart(e,[u],d,this._parentRunId,s,this.tags,this.metadata,c),de(async()=>{try{if(f.handleChatModelStart)await f.handleChatModelStart?.(e,[u],d,this._parentRunId,s,this.tags,this.metadata,c);else if(f.handleLLMStart){const h=Is(u);await f.handleLLMStart?.(e,[h],d,this._parentRunId,s,this.tags,this.metadata,c)}}catch(h){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${h}`),f.raiseError)throw h}},f.awaitHandlers)})),new Xa(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,r,n=Te(),a=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreChain)return Lt(c)&&c._createRunForChainStart(e,r,n,this._parentRunId,this.tags,this.metadata,a,o),de(async()=>{try{await c.handleChainStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,a,o)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleChainStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new hu(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,r,n=Te(),a=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreAgent)return Lt(c)&&c._createRunForToolStart(e,r,n,this._parentRunId,this.tags,this.metadata,o),de(async()=>{try{await c.handleToolStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,o)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleToolStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new pu(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,r,n=Te(),a=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return Lt(c)&&c._createRunForRetrieverStart(e,r,n,this._parentRunId,this.tags,this.metadata,o),de(async()=>{try{await c.handleRetrieverStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,o)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new fu(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,r,n,a,s){await Promise.all(this.handlers.map(i=>de(async()=>{if(!i.ignoreCustomEvent)try{await i.handleCustomEvent?.(e,r,n,this.tags,this.metadata)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}addHandler(e,r=!0){this.handlers.push(e),r&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(r=>r!==e),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==e)}setHandlers(e,r=!0){this.handlers=[],this.inheritableHandlers=[];for(const n of e)this.addHandler(n,r)}addTags(e,r=!0){this.removeTags(e),this.tags.push(...e),r&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(r=>!e.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!e.includes(r))}addMetadata(e,r=!0){this.metadata={...this.metadata,...e},r&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(const r of Object.keys(e))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(e=[],r=!0){const n=new rr(this._parentRunId);for(const a of this.handlers){const s=this.inheritableHandlers.includes(a);n.addHandler(a,s)}for(const a of this.tags){const s=this.inheritableTags.includes(a);n.addTags([a],s)}for(const a of Object.keys(this.metadata)){const s=Object.keys(this.inheritableMetadata).includes(a);n.addMetadata({[a]:this.metadata[a]},s)}for(const a of e)n.handlers.filter(s=>s.name==="console_callback_handler").some(s=>s.name===a.name)||n.addHandler(a,r);return n}static fromHandlers(e){class r extends Ar{name=Te();constructor(){super(),Object.assign(this,e)}}const n=new this;return n.addHandler(new r),n}static configure(e,r,n,a,s,i,o){return this._configureSync(e,r,n,a,s,i,o)}static _configureSync(e,r,n,a,s,i,o){let c;(e||r)&&(Array.isArray(e)||!e?(c=new rr,c.setHandlers(e?.map(_r)??[],!0)):c=e,c=c.copy(Array.isArray(r)?r.map(_r):r?.handlers,!1));const u=Et("LANGCHAIN_VERBOSE")==="true"||o?.verbose,l=Zr.getTraceableRunTree()?.tracingEnabled||rp(),d=l||(Et("LANGCHAIN_TRACING")??!1);if(u||d){if(c||(c=new rr),u&&!c.handlers.some(f=>f.name===Ya.prototype.name)){const f=new Ya;c.addHandler(f,!0)}if(d&&!c.handlers.some(f=>f.name==="langchain_tracer")&&l){const f=new Zr;c.addHandler(f,!0)}if(l){const f=Zr.getTraceableRunTree();f&&c._parentRunId===void 0&&(c._parentRunId=f.id,c.handlers.find(p=>p.name==="langchain_tracer")?.updateFromRunTree(f))}}for(const{contextVar:f,inheritable:h=!0,handlerClass:p,envVar:m}of ap()){const g=m&&Et(m)==="true"&&p;let y;const v=f!==void 0?lu(f):void 0;v&&qc(v)?y=v:g&&(y=new p({})),y!==void 0&&(c||(c=new rr),c.handlers.some(_=>_.name===y.name)||c.addHandler(y,h))}return(n||a)&&c&&(c.addTags(n??[]),c.addTags(a??[],!1)),(s||i)&&c&&(c.addMetadata(s??{}),c.addMetadata(i??{},!1)),c}};function _r(t){return"name"in t?t:Ar.fromMethods(t)}var mu=class{getStore(){}run(t,e){return e()}enterWith(t){}};const op=new mu,Do=Symbol.for("lc:child_config");var cp=class{getInstance(){return gr()??op}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[Do]}runWithConfig(t,e,r){const n=Ct._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata),a=this.getInstance(),s=a.getStore(),i=n?.getParentRunId(),o=n?.handlers?.find(u=>u?.name==="langchain_tracer");let c;return o&&i?c=o.getRunTreeWithTracingConfig(i):r||(c=new Re({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[Do]:t}),s!==void 0&&s[ir]!==void 0&&(c===void 0&&(c={}),c[ir]=s[ir]),a.run(c,e)}initializeGlobalInstance(t){gr()===void 0&&vd(t)}};const ut=new cp;var up={};me(up,{AsyncLocalStorageProviderSingleton:()=>ut,MockAsyncLocalStorage:()=>mu,_CONTEXT_VARIABLES_KEY:()=>ir});const Pa=25;async function Ge(t){return Ct._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata)}function Uo(...t){const e={};for(const r of t.filter(n=>!!n))for(const n of Object.keys(r))if(n==="metadata")e[n]={...e[n],...r[n]};else if(n==="tags"){const a=e[n]??[];e[n]=[...new Set(a.concat(r[n]??[]))]}else if(n==="configurable")e[n]={...e[n],...r[n]};else if(n==="timeout")e.timeout===void 0?e.timeout=r.timeout:r.timeout!==void 0&&(e.timeout=Math.min(e.timeout,r.timeout));else if(n==="signal")e.signal===void 0?e.signal=r.signal:r.signal!==void 0&&("any"in AbortSignal?e.signal=AbortSignal.any([e.signal,r.signal]):e.signal=r.signal);else if(n==="callbacks"){const a=e.callbacks,s=r.callbacks;if(Array.isArray(s))if(!a)e.callbacks=s;else if(Array.isArray(a))e.callbacks=a.concat(s);else{const i=a.copy();for(const o of s)i.addHandler(_r(o),!0);e.callbacks=i}else if(s)if(!a)e.callbacks=s;else if(Array.isArray(a)){const i=s.copy();for(const o of a)i.addHandler(_r(o),!0);e.callbacks=i}else e.callbacks=new Ct(s._parentRunId,{handlers:a.handlers.concat(s.handlers),inheritableHandlers:a.inheritableHandlers.concat(s.inheritableHandlers),tags:Array.from(new Set(a.tags.concat(s.tags))),inheritableTags:Array.from(new Set(a.inheritableTags.concat(s.inheritableTags))),metadata:{...a.metadata,...s.metadata}})}else{const a=n;e[a]=r[a]??e[a]}return e}const lp=new Set(["string","number","boolean"]);function ie(t){const e=ut.getRunnableConfig();let r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){const{runId:n,runName:a,...s}=e;r=Object.entries(s).reduce((i,[o,c])=>(c!==void 0&&(i[o]=c),i),r)}if(t&&(r=Object.entries(t).reduce((n,[a,s])=>(s!==void 0&&(n[a]=s),n),r)),r?.configurable)for(const n of Object.keys(r.configurable))lp.has(typeof r.configurable[n])&&!r.metadata?.[n]&&(r.metadata||(r.metadata={}),r.metadata[n]=r.configurable[n]);if(r.timeout!==void 0){if(r.timeout<=0)throw new Error("Timeout must be a positive number");const n=AbortSignal.timeout(r.timeout);r.signal!==void 0?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,n])):r.signal=n,delete r.timeout}return r}function we(t={},{callbacks:e,maxConcurrency:r,recursionLimit:n,runName:a,configurable:s,runId:i}={}){const o=ie(t);return e!==void 0&&(delete o.runName,o.callbacks=e),n!==void 0&&(o.recursionLimit=n),r!==void 0&&(o.maxConcurrency=r),a!==void 0&&(o.runName=a),s!==void 0&&(o.configurable={...o.configurable,...s}),i!==void 0&&delete o.runId,o}function Zt(t){return t?{configurable:t.configurable,recursionLimit:t.recursionLimit,callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,maxConcurrency:t.maxConcurrency,timeout:t.timeout,signal:t.signal}:void 0}async function gt(t,e){if(e===void 0)return t;let r;return Promise.race([t.catch(n=>{if(!e?.aborted)throw n}),new Promise((n,a)=>{r=()=>{a(an(e))},e.addEventListener("abort",r),e.aborted&&a(an(e))})]).finally(()=>e.removeEventListener("abort",r))}function an(t){return t?.reason instanceof Error?t.reason:typeof t?.reason=="string"?new Error(t.reason):new Error("Aborted")}var dp={};me(dp,{AsyncGeneratorWithSetup:()=>Nt,IterableReadableStream:()=>He,atee:()=>Ls,concat:()=>js,pipeGeneratorWithSetup:()=>gu});var He=class Qa extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){const r=this.reader.cancel();this.reader.releaseLock(),await r}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){const r=e.getReader();return new Qa({start(n){return a();function a(){return r.read().then(({done:s,value:i})=>{if(s){n.close();return}return n.enqueue(i),a()})}},cancel(){r.releaseLock()}})}static fromAsyncGenerator(e){return new Qa({async pull(r){const{value:n,done:a}=await e.next();a&&r.close(),r.enqueue(n)},async cancel(r){await e.return(r)}})}};function Ls(t,e=2){const r=Array.from({length:e},()=>[]);return r.map(async function*(a){for(;;)if(a.length===0){const s=await t.next();for(const i of r)i.push(s)}else{if(a[0].done)return;yield a.shift().value}})}function js(t,e){if(Array.isArray(t)&&Array.isArray(e))return t.concat(e);if(typeof t=="string"&&typeof e=="string")return t+e;if(typeof t=="number"&&typeof e=="number")return t+e;if("concat"in t&&typeof t.concat=="function")return t.concat(e);if(typeof t=="object"&&typeof e=="object"){const r={...t};for(const[n,a]of Object.entries(e))n in r&&!Array.isArray(r[n])?r[n]=js(r[n],a):r[n]=a;return r}else throw new Error(`Cannot concat ${typeof t} and ${typeof e}`)}var Nt=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(t){this.generator=t.generator,this.config=t.config,this.signal=t.signal??this.config?.signal,this.setup=new Promise((e,r)=>{ut.runWithConfig(Zt(t.config),async()=>{this.firstResult=t.generator.next(),t.startSetup?this.firstResult.then(t.startSetup).then(e,r):this.firstResult.then(n=>e(void 0),r)},!0)})}async next(...t){return this.signal?.throwIfAborted(),this.firstResultUsed?ut.runWithConfig(Zt(this.config),this.signal?async()=>gt(this.generator.next(...t),this.signal):async()=>this.generator.next(...t),!0):(this.firstResultUsed=!0,this.firstResult)}async return(t){return this.generator.return(t)}async throw(t){return this.generator.throw(t)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function gu(t,e,r,n,...a){const s=new Nt({generator:e,startSetup:r,signal:n}),i=await s.setup;return{output:t(s,i,...a),setup:i}}const fp=Object.prototype.hasOwnProperty;function hp(t,e){return fp.call(t,e)}function pp(t){if(Array.isArray(t)){const r=new Array(t.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(t);let e=[];for(let r in t)hp(t,r)&&e.push(r);return e}function Ot(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function es(t){let e=0;const r=t.length;let n;for(;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function jg(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function mp(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function ts(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(ts(t[r]))return!0}else if(typeof t=="object"){const r=pp(t),n=r.length;for(var e=0;e<n;e++)if(ts(t[r[e]]))return!0}}return!1}function Fo(t,e){const r=[t];for(const n in e){const a=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof a<"u"&&r.push(`${n}: ${a}`)}return r.join(`
56
- `)}var gp=class extends Error{constructor(t,e,r,n,a){super(Fo(t,{name:e,index:r,operation:n,tree:a})),this.name=e,this.index=r,this.operation=n,this.tree=a,Object.setPrototypeOf(this,new.target.prototype),this.message=Fo(t,{name:e,index:r,operation:n,tree:a})}},yu={};me(yu,{JsonPatchError:()=>ue,_areEquals:()=>wr,applyOperation:()=>Tt,applyPatch:()=>vr,applyReducer:()=>vp,deepClone:()=>yp,getValueByPointer:()=>sn,validate:()=>_u,validator:()=>on});const ue=gp,yp=Ot,Dt={add:function(t,e,r){return t[e]=this.value,{newDocument:r}},remove:function(t,e,r){var n=t[e];return delete t[e],{newDocument:r,removed:n}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:function(t,e,r){let n=sn(r,this.path);n&&(n=Ot(n));const a=Tt(r,{op:"remove",path:this.from}).removed;return Tt(r,{op:"add",path:this.path,value:a}),{newDocument:r,removed:n}},copy:function(t,e,r){const n=sn(r,this.from);return Tt(r,{op:"add",path:this.path,value:Ot(n)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:wr(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}};var _p={add:function(t,e,r){return es(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},remove:function(t,e,r){var n=t.splice(e,1);return{newDocument:r,removed:n[0]}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:Dt.move,copy:Dt.copy,test:Dt.test,_get:Dt._get};function sn(t,e){if(e=="")return t;var r={op:"_get",path:e};return Tt(t,r),r.value}function Tt(t,e,r=!1,n=!0,a=!0,s=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):on(e,0)),e.path===""){let i={newDocument:t};if(e.op==="add")return i.newDocument=e.value,i;if(e.op==="replace")return i.newDocument=e.value,i.removed=t,i;if(e.op==="move"||e.op==="copy")return i.newDocument=sn(t,e.from),e.op==="move"&&(i.removed=t),i;if(e.op==="test"){if(i.test=wr(t,e.value),i.test===!1)throw new ue("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i.newDocument=t,i}else{if(e.op==="remove")return i.removed=t,i.newDocument=null,i;if(e.op==="_get")return e.value=t,i;if(r)throw new ue("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,t);return i}}else{n||(t=Ot(t));const o=(e.path||"").split("/");let c=t,u=1,l=o.length,d,f,h;for(typeof r=="function"?h=r:h=on;;){if(f=o[u],f&&f.indexOf("~")!=-1&&(f=mp(f)),a&&(f=="__proto__"||f=="prototype"&&u>0&&o[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&d===void 0&&(c[f]===void 0?d=o.slice(0,u).join("/"):u==l-1&&(d=e.path),d!==void 0&&h(e,0,t,d)),u++,Array.isArray(c)){if(f==="-")f=c.length;else{if(r&&!es(f))throw new ue("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,t);es(f)&&(f=~~f)}if(u>=l){if(r&&e.op==="add"&&f>c.length)throw new ue("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,t);const p=_p[e.op].call(e,c,f,t);if(p.test===!1)throw new ue("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return p}}else if(u>=l){const p=Dt[e.op].call(e,c,f,t);if(p.test===!1)throw new ue("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return p}if(c=c[f],r&&u<l&&(!c||typeof c!="object"))throw new ue("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,t)}}}function vr(t,e,r,n=!0,a=!0){if(r&&!Array.isArray(e))throw new ue("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=Ot(t));const s=new Array(e.length);for(let i=0,o=e.length;i<o;i++)s[i]=Tt(t,e[i],r,!0,a,i),t=s[i].newDocument;return s.newDocument=t,s}function vp(t,e,r){const n=Tt(t,e);if(n.test===!1)throw new ue("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function on(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new ue("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(Dt[t.op]){if(typeof t.path!="string")throw new ue("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new ue('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new ue("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new ue("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&ts(t.value))throw new ue("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var a=t.path.split("/").length,s=n.split("/").length;if(a!==s+1&&a!==s)throw new ue("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new ue("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var i={op:"_get",path:t.from,value:void 0},o=_u([i],r);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new ue("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new ue("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function _u(t,e,r){try{if(!Array.isArray(t))throw new ue("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)vr(Ot(e),Ot(t),r||!0);else{r=r||on;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(a){if(a instanceof ue)return a;throw a}}function wr(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=Array.isArray(t),n=Array.isArray(e),a,s,i;if(r&&n){if(s=t.length,s!=e.length)return!1;for(a=s;a--!==0;)if(!wr(t[a],e[a]))return!1;return!0}if(r!=n)return!1;var o=Object.keys(t);if(s=o.length,s!==Object.keys(e).length)return!1;for(a=s;a--!==0;)if(!e.hasOwnProperty(o[a]))return!1;for(a=s;a--!==0;)if(i=o[a],!wr(t[i],e[i]))return!1;return!0}return t!==t&&e!==e}({...yu});var wp={};me(wp,{LogStreamCallbackHandler:()=>ns,RunLog:()=>Ds,RunLogPatch:()=>rt,isLogStreamHandler:()=>vu});var rt=class{ops;constructor(t){this.ops=t.ops??[]}concat(t){const e=this.ops.concat(t.ops),r=vr({},e);return new Ds({ops:e,state:r[r.length-1].newDocument})}},Ds=class rs extends rt{state;constructor(e){super(e),this.state=e.state}concat(e){const r=this.ops.concat(e.ops),n=vr(this.state,e.ops);return new rs({ops:r,state:n[n.length-1].newDocument})}static fromRunLogPatch(e){const r=vr({},e.ops);return new rs({ops:e.ops,state:r[r.length-1].newDocument})}};const vu=t=>t.name==="log_stream_tracer";async function Bo(t,e){if(e==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:r}=t;if(["retriever","llm","prompt"].includes(t.run_type))return r;if(!(Object.keys(r).length===1&&r?.input===""))return r.input}async function zo(t,e){const{outputs:r}=t;return e==="original"||["retriever","llm","prompt"].includes(t.run_type)?r:r!==void 0&&Object.keys(r).length===1&&r?.output!==void 0?r.output:r}function bp(t){return t!==void 0&&t.message!==void 0}var ns=class extends Kt{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat="original";rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name="log_stream_tracer";lc_prefer_streaming=!0;constructor(t){super({_awaitHandler:!0,...t}),this.autoClose=t?.autoClose??!0,this.includeNames=t?.includeNames,this.includeTypes=t?.includeTypes,this.includeTags=t?.includeTags,this.excludeNames=t?.excludeNames,this.excludeTypes=t?.excludeTypes,this.excludeTags=t?.excludeTags,this._schemaFormat=t?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=He.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(t){}_includeRun(t){if(t.id===this.rootId)return!1;const e=t.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(t.run_type)),this.includeTags!==void 0&&(r=r||e.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(t.run_type)),this.excludeTags!==void 0&&(r=r&&e.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(t,e){for await(const r of e){if(t!==this.rootId){const n=this.keyMapByRunId[t];n&&await this.writer.write(new rt({ops:[{op:"add",path:`/logs/${n}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(t){if(this.rootId===void 0&&(this.rootId=t.id,await this.writer.write(new rt({ops:[{op:"replace",path:"",value:{id:t.id,name:t.name,type:t.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(t))return;this.counterMapByRunName[t.name]===void 0&&(this.counterMapByRunName[t.name]=0),this.counterMapByRunName[t.name]+=1;const e=this.counterMapByRunName[t.name];this.keyMapByRunId[t.id]=e===1?t.name:`${t.name}:${e}`;const r={id:t.id,name:t.name,type:t.run_type,tags:t.tags??[],metadata:t.extra?.metadata??{},start_time:new Date(t.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(r.inputs=await Bo(t,this._schemaFormat)),await this.writer.write(new rt({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[t.id]}`,value:r}]}))}async onRunUpdate(t){try{const e=this.keyMapByRunId[t.id];if(e===void 0)return;const r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${e}/inputs`,value:await Bo(t,this._schemaFormat)}),r.push({op:"add",path:`/logs/${e}/final_output`,value:await zo(t,this._schemaFormat)}),t.end_time!==void 0&&r.push({op:"add",path:`/logs/${e}/end_time`,value:new Date(t.end_time).toISOString()});const n=new rt({ops:r});await this.writer.write(n)}finally{if(t.id===this.rootId){const e=new rt({ops:[{op:"replace",path:"/final_output",value:await zo(t,this._schemaFormat)}]});await this.writer.write(e),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(t,e,r){const n=this.keyMapByRunId[t.id];if(n===void 0)return;const a=t.inputs.messages!==void 0;let s;a?bp(r?.chunk)?s=r?.chunk:s=new kt({id:`run-${t.id}`,content:e}):s=e;const i=new rt({ops:[{op:"add",path:`/logs/${n}/streamed_output_str/-`,value:e},{op:"add",path:`/logs/${n}/streamed_output/-`,value:s}]});await this.writer.write(i)}},Ep={};me(Ep,{ChatGenerationChunk:()=>Tp,GenerationChunk:()=>cn,RUN_KEY:()=>Sp});const Sp="__run";var cn=class wu{text;generationInfo;constructor(e){this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new wu({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}},Tp=class bu extends cn{message;constructor(e){super(e),this.message=e.message}concat(e){return new bu({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo},message:this.message.concat(e.message)})}};function Gr({name:t,serialized:e}){return t!==void 0?t:e?.name!==void 0?e.name:e?.id!==void 0&&Array.isArray(e?.id)?e.id[e.id.length-1]:"Unnamed"}const xp=t=>t.name==="event_stream_tracer";var Ip=class extends Kt{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;name="event_stream_tracer";lc_prefer_streaming=!0;constructor(t){super({_awaitHandler:!0,...t}),this.autoClose=t?.autoClose??!0,this.includeNames=t?.includeNames,this.includeTypes=t?.includeTypes,this.includeTags=t?.includeTags,this.excludeNames=t?.excludeNames,this.excludeTypes=t?.excludeTypes,this.excludeTags=t?.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=He.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(t){}_includeRun(t){const e=t.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(t.runType)),this.includeTags!==void 0&&(r=r||e.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(t.runType)),this.excludeTags!==void 0&&(r=r&&e.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(t,e){const r=await e.next();if(r.done)return;const n=this.runInfoMap.get(t);if(n===void 0){yield r.value;return}function a(i,o){return i==="llm"&&typeof o=="string"?new cn({text:o}):o}let s=this.tappedPromises.get(t);if(s===void 0){let i;s=new Promise(o=>{i=o}),this.tappedPromises.set(t,s);try{const o={event:`on_${n.runType}_stream`,run_id:t,name:n.name,tags:n.tags,metadata:n.metadata,data:{}};await this.send({...o,data:{chunk:a(n.runType,r.value)}},n),yield r.value;for await(const c of e)n.runType!=="tool"&&n.runType!=="retriever"&&await this.send({...o,data:{chunk:a(n.runType,c)}},n),yield c}finally{i?.()}}else{yield r.value;for await(const i of e)yield i}}async send(t,e){this._includeRun(e)&&await this.writer.write(t)}async sendEndEvent(t,e){const r=this.tappedPromises.get(t.run_id);r!==void 0?r.then(()=>{this.send(t,e)}):await this.send(t,e)}async onLLMStart(t){const e=Gr(t),r=t.inputs.messages!==void 0?"chat_model":"llm",n={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:r,inputs:t.inputs};this.runInfoMap.set(t.id,n);const a=`on_${r}_start`;await this.send({event:a,data:{input:t.inputs},name:e,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},n)}async onLLMNewToken(t,e,r){const n=this.runInfoMap.get(t.id);let a,s;if(n===void 0)throw new Error(`onLLMNewToken: Run ID ${t.id} not found in run map.`);if(this.runInfoMap.size!==1){if(n.runType==="chat_model")s="on_chat_model_stream",r?.chunk===void 0?a=new kt({content:e,id:`run-${t.id}`}):a=r.chunk.message;else if(n.runType==="llm")s="on_llm_stream",r?.chunk===void 0?a=new cn({text:e}):a=r.chunk;else throw new Error(`Unexpected run type ${n.runType}`);await this.send({event:s,data:{chunk:a},run_id:t.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}}async onLLMEnd(t){const e=this.runInfoMap.get(t.id);this.runInfoMap.delete(t.id);let r;if(e===void 0)throw new Error(`onLLMEnd: Run ID ${t.id} not found in run map.`);const n=t.outputs?.generations;let a;if(e.runType==="chat_model"){for(const s of n??[]){if(a!==void 0)break;a=s[0]?.message}r="on_chat_model_end"}else if(e.runType==="llm")a={generations:n?.map(s=>s.map(i=>({text:i.text,generationInfo:i.generationInfo}))),llmOutput:t.outputs?.llmOutput??{}},r="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${e.runType}`);await this.sendEndEvent({event:r,data:{output:a,input:e.inputs},run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata},e)}async onChainStart(t){const e=Gr(t),r=t.run_type??"chain",n={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:t.run_type};let a={};t.inputs.input===""&&Object.keys(t.inputs).length===1?(a={},n.inputs={}):t.inputs.input!==void 0?(a.input=t.inputs.input,n.inputs=t.inputs.input):(a.input=t.inputs,n.inputs=t.inputs),this.runInfoMap.set(t.id,n),await this.send({event:`on_${r}_start`,data:a,name:e,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},n)}async onChainEnd(t){const e=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),e===void 0)throw new Error(`onChainEnd: Run ID ${t.id} not found in run map.`);const r=`on_${t.run_type}_end`,n=t.inputs??e.inputs??{},s={output:t.outputs?.output??t.outputs,input:n};n.input&&Object.keys(n).length===1&&(s.input=n.input,e.inputs=n.input),await this.sendEndEvent({event:r,data:s,run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata??{}},e)}async onToolStart(t){const e=Gr(t),r={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:"tool",inputs:t.inputs??{}};this.runInfoMap.set(t.id,r),await this.send({event:"on_tool_start",data:{input:t.inputs??{}},name:e,run_id:t.id,tags:t.tags??[],metadata:t.extra?.metadata??{}},r)}async onToolEnd(t){const e=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),e===void 0)throw new Error(`onToolEnd: Run ID ${t.id} not found in run map.`);if(e.inputs===void 0)throw new Error(`onToolEnd: Run ID ${t.id} is a tool call, and is expected to have traced inputs.`);const r=t.outputs?.output===void 0?t.outputs:t.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:e.inputs},run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata},e)}async onRetrieverStart(t){const e=Gr(t),n={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:"retriever",inputs:{query:t.inputs.query}};this.runInfoMap.set(t.id,n),await this.send({event:"on_retriever_start",data:{input:{query:t.inputs.query}},name:e,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},n)}async onRetrieverEnd(t){const e=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),e===void 0)throw new Error(`onRetrieverEnd: Run ID ${t.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:t.outputs?.documents??t.outputs,input:e.inputs},run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata},e)}async handleCustomEvent(t,e,r){const n=this.runInfoMap.get(r);if(n===void 0)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:t,tags:n.tags,metadata:n.metadata,data:e},n)}async finish(){const t=[...this.tappedPromises.values()];Promise.all(t).finally(()=>{this.writer.close()})}},Ap={};me(Ap,{AsyncCaller:()=>Eu});const Op=[400,401,402,403,404,405,406,407,409],Rp=t=>{if(t.message.startsWith("Cancel")||t.message.startsWith("AbortError")||t.name==="AbortError"||t?.code==="ECONNABORTED")throw t;const e=t?.response?.status??t?.status;if(e&&Op.includes(+e))throw t;if(t?.error?.code==="insufficient_quota"){const r=new Error(t?.message);throw r.name="InsufficientQuotaError",r}};var Eu=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(t){this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,this.onFailedAttempt=t.onFailedAttempt??Rp;const e="default"in at?at.default:at;this.queue=new e({concurrency:this.maxConcurrency})}call(t,...e){return this.queue.add(()=>tn(()=>t(...e).catch(r=>{throw r instanceof Error?r:new Error(r)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(t,e,...r){if(t.signal){let n;return Promise.race([this.call(e,...r),new Promise((a,s)=>{n=()=>{s(an(t.signal))},t.signal?.addEventListener("abort",n)})]).finally(()=>{t.signal&&n&&t.signal.removeEventListener("abort",n)})}return this.call(e,...r)}fetch(...t){return this.call(()=>fetch(...t).then(e=>e.ok?e:Promise.reject(e)))}},Su=class extends Kt{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:t,onStart:e,onEnd:r,onError:n}){super({_awaitHandler:!0}),this.config=t,this.argOnStart=e,this.argOnEnd=r,this.argOnError=n}persistRun(t){return Promise.resolve()}async onRunCreate(t){this.rootId||(this.rootId=t.id,this.argOnStart&&await this.argOnStart(t,this.config))}async onRunUpdate(t){t.id===this.rootId&&(t.error?this.argOnError&&await this.argOnError(t,this.config):this.argOnEnd&&await this.argOnEnd(t,this.config))}};function Us(t){return t?t.lc_runnable:!1}var kp=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(t){this.includeNames=t.includeNames,this.includeTypes=t.includeTypes,this.includeTags=t.includeTags,this.excludeNames=t.excludeNames,this.excludeTypes=t.excludeTypes,this.excludeTags=t.excludeTags}includeEvent(t,e){let r=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0;const n=t.tags??[];return this.includeNames!==void 0&&(r=r||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e)),this.includeTags!==void 0&&(r=r||n.some(a=>this.includeTags?.includes(a))),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e)),this.excludeTags!==void 0&&(r=r&&n.every(a=>!this.excludeTags?.includes(a))),r}};function fe(t){if(typeof t!="object"||t===null)return!1;const e=t;if(!("_zod"in e))return!1;const r=e._zod;return typeof r=="object"&&r!==null&&"def"in r}function ge(t){if(typeof t!="object"||t===null)return!1;const e=t;if(!("_def"in e)||"_zod"in e)return!1;const r=e._def;return typeof r=="object"&&r!=null&&"typeName"in r}function Dg(t){return fe(t)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),ge(t)}function Tu(t){return!t||typeof t!="object"||Array.isArray(t)?!1:!!(fe(t)||ge(t))}function $p(t){return typeof t=="object"&&t!==null&&"_def"in t&&typeof t._def=="object"&&t._def!==null&&"typeName"in t._def&&t._def.typeName==="ZodLiteral"}function Cp(t){return fe(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="literal":!1}function Ug(t){return!!($p(t)||Cp(t))}async function Fg(t,e){if(fe(t))try{return{success:!0,data:await nc(t,e)}}catch(r){return{success:!1,error:r}}if(ge(t))return await t.safeParseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function Np(t,e){if(fe(t))return await nc(t,e);if(ge(t))return await t.parseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Bg(t,e){if(fe(t))try{return{success:!0,data:os(t,e)}}catch(r){return{success:!1,error:r}}if(ge(t))return t.safeParse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function zg(t,e){if(fe(t))return os(t,e);if(ge(t))return t.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Pp(t){if(fe(t))return $e.get(t)?.description;if(ge(t)||"description"in t&&typeof t.description=="string")return t.description}function qg(t){if(!Tu(t))return!1;if(ge(t)){const e=t._def;if(e.typeName==="ZodObject"){const r=t;return!r.shape||Object.keys(r.shape).length===0}if(e.typeName==="ZodRecord")return!0}if(fe(t)){const e=t._zod.def;if(e.type==="object"){const r=t;return!r.shape||Object.keys(r.shape).length===0}if(e.type==="record")return!0}return typeof t=="object"&&t!==null&&!("shape"in t)}function Mp(t){return Tu(t)?ge(t)?t._def.typeName==="ZodString":fe(t)?t._zod.def.type==="string":!1:!1}function xu(t){return typeof t=="object"&&t!==null&&"_def"in t&&typeof t._def=="object"&&t._def!==null&&"typeName"in t._def&&t._def.typeName==="ZodObject"}function st(t){return fe(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="object":!1}function Fs(t){return fe(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="array":!1}function Gg(t){return!!(xu(t)||st(t))}function qo(t){if(ge(t))return t.shape;if(fe(t))return t._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Hg(t,e){if(ge(t))return t.extend(e);if(fe(t))return tl(t,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Zg(t){if(ge(t))return t.partial();if(fe(t))return rl(ac,t,void 0);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function as(t,e=!1){if(ge(t))return t.strict();if(st(t)){const r=t._zod.def.shape;if(e)for(const[s,i]of Object.entries(t._zod.def.shape)){if(st(i)){const c=as(i,e);r[s]=c}else if(Fs(i)){let c=i._zod.def.element;st(c)&&(c=as(c,e)),r[s]=xt(i,{...i._zod.def,element:c})}else r[s]=i;const o=$e.get(i);o&&$e.add(r[s],o)}const n=xt(t,{...t._zod.def,shape:r,catchall:Qu(el)}),a=$e.get(t);return a&&$e.add(n,a),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Go(t,e=!1){if(xu(t))return t.passthrough();if(st(t)){const r=t._zod.def.shape;if(e)for(const[s,i]of Object.entries(t._zod.def.shape)){if(st(i)){const c=Go(i,e);r[s]=c}else if(Fs(i)){let c=i._zod.def.element;st(c)&&(c=Go(c,e)),r[s]=xt(i,{...i._zod.def,element:c})}else r[s]=i;const o=$e.get(i);o&&$e.add(r[s],o)}const n=xt(t,{...t._zod.def,shape:r,catchall:nl(al)}),a=$e.get(t);return a&&$e.add(n,a),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Vg(t){if(ge(t))try{const e=t.parse(void 0);return()=>e}catch{return}if(fe(t))try{const e=os(t,void 0);return()=>e}catch{return}}function Lp(t){return ge(t)&&"typeName"in t._def&&t._def.typeName==="ZodEffects"}function jp(t){return fe(t)&&t._zod.def.type==="pipe"}function nr(t,e=!1){if(ge(t))return Lp(t)?nr(t._def.schema,e):t;if(fe(t)){let r=t;if(jp(t)&&(r=nr(t._zod.def.in,e)),e){if(st(r)){const a=r._zod.def.shape;for(const[s,i]of Object.entries(r._zod.def.shape))a[s]=nr(i,e);r=xt(r,{...r._zod.def,shape:a})}else if(Fs(r)){const a=nr(r._zod.def.element,e);r=xt(r,{...r._zod.def,element:a})}}const n=$e.get(t);return n&&$e.add(r,n),r}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Jg(t,e){if(ge(t)){const r=qo(t),n={};for(const[a,s]of Object.entries(r))e(a,s)?n[a]=s.optional():n[a]=s;return t.extend(n)}if(fe(t)){const r=qo(t),n={...t._zod.def.shape};for(const[i,o]of Object.entries(r))e(i,o)&&(n[i]=new ac({type:"optional",innerType:o}));const a=xt(t,{...t._zod.def,shape:n}),s=$e.get(t);return s&&$e.add(a,s),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Ma(t){return t.replace(/[^a-zA-Z-_0-9]/g,"_")}const Dp=["*","_","`"];function Up(t){let e="";for(const[r,n]of Object.entries(t))e+=` classDef ${r} ${n};
57
- `;return e}function Fp(t,e,r){const{firstNode:n,lastNode:a,nodeColors:s,withStyles:i=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=r??{};let u=i?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
53
+ Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function Ps(t){return typeof t=="function"&&"langsmith:traceable"in t}var Vh={};me(Vh,{LangChainTracer:()=>Hr});var Hr=class ou extends Jt{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;constructor(e={}){super(e);const{exampleId:r,projectName:n,client:a,replicas:s}=e;this.projectName=n??qc(),this.replicas=s,this.exampleId=r,this.client=a??iu();const i=ou.getTraceableRunTree();i&&this.updateFromRunTree(i)}async persistRun(e){}async onRunCreate(e){await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){await this.getRunTreeWithTracingConfig(e.id)?.patchRun()}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let r=e;const n=new Set;for(;r.parent_run&&!(n.has(r.id)||(n.add(r.id),!r.parent_run));)r=r.parent_run;n.clear();const a=[r];for(;a.length>0;){const s=a.shift();!s||n.has(s.id)||(n.add(s.id),this.runTreeMap.set(s.id,s),s.child_runs&&a.push(...s.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(e){const r=this.runTreeMap.get(e);if(r)return new Re({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return Zh(!0)}catch{return}}};let Et;function Wh(){const t="default"in nt?nt.default:nt;return new t({autoStart:!0,concurrency:1})}function Jh(){return typeof Et>"u"&&(Et=Wh()),Et}async function de(t,e){if(e===!0){const r=mr();r!==void 0?await r.run(void 0,async()=>t()):await t()}else Et=Jh(),Et.add(async()=>{const r=mr();r!==void 0?await r.run(void 0,async()=>t()):await t()})}async function Kh(){const t=iu();await Promise.allSettled([typeof Et<"u"?Et.onIdle():Promise.resolve(),t.awaitPendingTraceBatches()])}var Yh={};me(Yh,{awaitAllCallbacks:()=>Kh,consumeCallback:()=>de});const Xh=t=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(r=>bt(r)==="true");function cu(t){const e=mr();return e===void 0?void 0:e.getStore()?.[sr]?.[t]}const Qh=Symbol("lc:configure_hooks"),ep=()=>cu(Qh)||[];var tp={};me(tp,{BaseCallbackManager:()=>uu,BaseRunManager:()=>Rr,CallbackManager:()=>kt,CallbackManagerForChainRun:()=>du,CallbackManagerForLLMRun:()=>Ya,CallbackManagerForRetrieverRun:()=>lu,CallbackManagerForToolRun:()=>fu,ensureHandler:()=>_r,parseCallbackConfigArg:()=>rp});function rp(t){return t?Array.isArray(t)||"name"in t?{callbacks:t}:t:{}}var uu=class{setHandler(t){return this.setHandlers([t])}},Rr=class{constructor(t,e,r,n,a,s,i,o){this.runId=t,this.handlers=e,this.inheritableHandlers=r,this.tags=n,this.inheritableTags=a,this.metadata=s,this.inheritableMetadata=i,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(e=>de(async()=>{try{await e.handleText?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleText: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleCustomEvent(t,e,r,n,a){await Promise.all(this.handlers.map(s=>de(async()=>{try{await s.handleCustomEvent?.(t,e,this.runId,this.tags,this.metadata)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleCustomEvent: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}},lu=class extends Rr{getChild(t){const e=new kt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleRetrieverEnd(t){await Promise.all(this.handlers.map(e=>de(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetriever`),e.raiseError)throw r}},e.awaitHandlers)))}async handleRetrieverError(t){await Promise.all(this.handlers.map(e=>de(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetrieverError: ${r}`),e.raiseError)throw t}},e.awaitHandlers)))}},Ya=class extends Rr{async handleLLMNewToken(t,e,r,n,a,s){await Promise.all(this.handlers.map(i=>de(async()=>{if(!i.ignoreLLM)try{await i.handleLLMNewToken?.(t,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,s)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMNewToken: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleLLMError(t,e,r,n,a){await Promise.all(this.handlers.map(s=>de(async()=>{if(!s.ignoreLLM)try{await s.handleLLMError?.(t,this.runId,this._parentRunId,this.tags,a)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMError: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}async handleLLMEnd(t,e,r,n,a){await Promise.all(this.handlers.map(s=>de(async()=>{if(!s.ignoreLLM)try{await s.handleLLMEnd?.(t,this.runId,this._parentRunId,this.tags,a)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMEnd: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}},du=class extends Rr{getChild(t){const e=new kt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleChainError(t,e,r,n,a){await Promise.all(this.handlers.map(s=>de(async()=>{if(!s.ignoreChain)try{await s.handleChainError?.(t,this.runId,this._parentRunId,this.tags,a)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainError: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}async handleChainEnd(t,e,r,n,a){await Promise.all(this.handlers.map(s=>de(async()=>{if(!s.ignoreChain)try{await s.handleChainEnd?.(t,this.runId,this._parentRunId,this.tags,a)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainEnd: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(e=>de(async()=>{if(!e.ignoreAgent)try{await e.handleAgentAction?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentAction: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleAgentEnd(t){await Promise.all(this.handlers.map(e=>de(async()=>{if(!e.ignoreAgent)try{await e.handleAgentEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},fu=class extends Rr{getChild(t){const e=new kt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleToolError(t){await Promise.all(this.handlers.map(e=>de(async()=>{if(!e.ignoreAgent)try{await e.handleToolError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolError: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEnd(t){await Promise.all(this.handlers.map(e=>de(async()=>{if(!e.ignoreAgent)try{await e.handleToolEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},kt=class tr extends uu{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(e,r){super(),this.handlers=r?.handlers??this.handlers,this.inheritableHandlers=r?.inheritableHandlers??this.inheritableHandlers,this.tags=r?.tags??this.tags,this.inheritableTags=r?.inheritableTags??this.inheritableTags,this.metadata=r?.metadata??this.metadata,this.inheritableMetadata=r?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,r,n=void 0,a=void 0,s=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(r.map(async(u,l)=>{const d=l===0&&n?n:Se();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return Lt(f)&&f._createRunForLLMStart(e,[u],d,this._parentRunId,s,this.tags,this.metadata,c),de(async()=>{try{await f.handleLLMStart?.(e,[u],d,this._parentRunId,s,this.tags,this.metadata,c)}catch(h){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${h}`),f.raiseError)throw h}},f.awaitHandlers)})),new Ya(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,r,n=void 0,a=void 0,s=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(r.map(async(u,l)=>{const d=l===0&&n?n:Se();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return Lt(f)&&f._createRunForChatModelStart(e,[u],d,this._parentRunId,s,this.tags,this.metadata,c),de(async()=>{try{if(f.handleChatModelStart)await f.handleChatModelStart?.(e,[u],d,this._parentRunId,s,this.tags,this.metadata,c);else if(f.handleLLMStart){const h=xs(u);await f.handleLLMStart?.(e,[h],d,this._parentRunId,s,this.tags,this.metadata,c)}}catch(h){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${h}`),f.raiseError)throw h}},f.awaitHandlers)})),new Ya(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,r,n=Se(),a=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreChain)return Lt(c)&&c._createRunForChainStart(e,r,n,this._parentRunId,this.tags,this.metadata,a,o),de(async()=>{try{await c.handleChainStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,a,o)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleChainStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new du(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,r,n=Se(),a=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreAgent)return Lt(c)&&c._createRunForToolStart(e,r,n,this._parentRunId,this.tags,this.metadata,o),de(async()=>{try{await c.handleToolStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,o)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleToolStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new fu(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,r,n=Se(),a=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return Lt(c)&&c._createRunForRetrieverStart(e,r,n,this._parentRunId,this.tags,this.metadata,o),de(async()=>{try{await c.handleRetrieverStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,o)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new lu(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,r,n,a,s){await Promise.all(this.handlers.map(i=>de(async()=>{if(!i.ignoreCustomEvent)try{await i.handleCustomEvent?.(e,r,n,this.tags,this.metadata)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}addHandler(e,r=!0){this.handlers.push(e),r&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(r=>r!==e),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==e)}setHandlers(e,r=!0){this.handlers=[],this.inheritableHandlers=[];for(const n of e)this.addHandler(n,r)}addTags(e,r=!0){this.removeTags(e),this.tags.push(...e),r&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(r=>!e.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!e.includes(r))}addMetadata(e,r=!0){this.metadata={...this.metadata,...e},r&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(const r of Object.keys(e))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(e=[],r=!0){const n=new tr(this._parentRunId);for(const a of this.handlers){const s=this.inheritableHandlers.includes(a);n.addHandler(a,s)}for(const a of this.tags){const s=this.inheritableTags.includes(a);n.addTags([a],s)}for(const a of Object.keys(this.metadata)){const s=Object.keys(this.inheritableMetadata).includes(a);n.addMetadata({[a]:this.metadata[a]},s)}for(const a of e)n.handlers.filter(s=>s.name==="console_callback_handler").some(s=>s.name===a.name)||n.addHandler(a,r);return n}static fromHandlers(e){class r extends Ir{name=Se();constructor(){super(),Object.assign(this,e)}}const n=new this;return n.addHandler(new r),n}static configure(e,r,n,a,s,i,o){return this._configureSync(e,r,n,a,s,i,o)}static _configureSync(e,r,n,a,s,i,o){let c;(e||r)&&(Array.isArray(e)||!e?(c=new tr,c.setHandlers(e?.map(_r)??[],!0)):c=e,c=c.copy(Array.isArray(r)?r.map(_r):r?.handlers,!1));const u=bt("LANGCHAIN_VERBOSE")==="true"||o?.verbose,l=Hr.getTraceableRunTree()?.tracingEnabled||Xh(),d=l||(bt("LANGCHAIN_TRACING")??!1);if(u||d){if(c||(c=new tr),u&&!c.handlers.some(f=>f.name===Ka.prototype.name)){const f=new Ka;c.addHandler(f,!0)}if(d&&!c.handlers.some(f=>f.name==="langchain_tracer")&&l){const f=new Hr;c.addHandler(f,!0)}if(l){const f=Hr.getTraceableRunTree();f&&c._parentRunId===void 0&&(c._parentRunId=f.id,c.handlers.find(p=>p.name==="langchain_tracer")?.updateFromRunTree(f))}}for(const{contextVar:f,inheritable:h=!0,handlerClass:p,envVar:g}of ep()){const m=g&&bt(g)==="true"&&p;let _;const w=f!==void 0?cu(f):void 0;w&&Bc(w)?_=w:m&&(_=new p({})),_!==void 0&&(c||(c=new tr),c.handlers.some(y=>y.name===_.name)||c.addHandler(_,h))}return(n||a)&&c&&(c.addTags(n??[]),c.addTags(a??[],!1)),(s||i)&&c&&(c.addMetadata(s??{}),c.addMetadata(i??{},!1)),c}};function _r(t){return"name"in t?t:Ir.fromMethods(t)}var hu=class{getStore(){}run(t,e){return e()}enterWith(t){}};const np=new hu,Mo=Symbol.for("lc:child_config");var ap=class{getInstance(){return mr()??np}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[Mo]}runWithConfig(t,e,r){const n=kt._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata),a=this.getInstance(),s=a.getStore(),i=n?.getParentRunId(),o=n?.handlers?.find(u=>u?.name==="langchain_tracer");let c;return o&&i?c=o.getRunTreeWithTracingConfig(i):r||(c=new Re({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[Mo]:t}),s!==void 0&&s[sr]!==void 0&&(c===void 0&&(c={}),c[sr]=s[sr]),a.run(c,e)}initializeGlobalInstance(t){mr()===void 0&&md(t)}};const ct=new ap;var sp={};me(sp,{AsyncLocalStorageProviderSingleton:()=>ct,MockAsyncLocalStorage:()=>hu,_CONTEXT_VARIABLES_KEY:()=>sr});const Na=25;async function qe(t){return kt._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata)}function jo(...t){const e={};for(const r of t.filter(n=>!!n))for(const n of Object.keys(r))if(n==="metadata")e[n]={...e[n],...r[n]};else if(n==="tags"){const a=e[n]??[];e[n]=[...new Set(a.concat(r[n]??[]))]}else if(n==="configurable")e[n]={...e[n],...r[n]};else if(n==="timeout")e.timeout===void 0?e.timeout=r.timeout:r.timeout!==void 0&&(e.timeout=Math.min(e.timeout,r.timeout));else if(n==="signal")e.signal===void 0?e.signal=r.signal:r.signal!==void 0&&("any"in AbortSignal?e.signal=AbortSignal.any([e.signal,r.signal]):e.signal=r.signal);else if(n==="callbacks"){const a=e.callbacks,s=r.callbacks;if(Array.isArray(s))if(!a)e.callbacks=s;else if(Array.isArray(a))e.callbacks=a.concat(s);else{const i=a.copy();for(const o of s)i.addHandler(_r(o),!0);e.callbacks=i}else if(s)if(!a)e.callbacks=s;else if(Array.isArray(a)){const i=s.copy();for(const o of a)i.addHandler(_r(o),!0);e.callbacks=i}else e.callbacks=new kt(s._parentRunId,{handlers:a.handlers.concat(s.handlers),inheritableHandlers:a.inheritableHandlers.concat(s.inheritableHandlers),tags:Array.from(new Set(a.tags.concat(s.tags))),inheritableTags:Array.from(new Set(a.inheritableTags.concat(s.inheritableTags))),metadata:{...a.metadata,...s.metadata}})}else{const a=n;e[a]=r[a]??e[a]}return e}const ip=new Set(["string","number","boolean"]);function ie(t){const e=ct.getRunnableConfig();let r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){const{runId:n,runName:a,...s}=e;r=Object.entries(s).reduce((i,[o,c])=>(c!==void 0&&(i[o]=c),i),r)}if(t&&(r=Object.entries(t).reduce((n,[a,s])=>(s!==void 0&&(n[a]=s),n),r)),r?.configurable)for(const n of Object.keys(r.configurable))ip.has(typeof r.configurable[n])&&!r.metadata?.[n]&&(r.metadata||(r.metadata={}),r.metadata[n]=r.configurable[n]);if(r.timeout!==void 0){if(r.timeout<=0)throw new Error("Timeout must be a positive number");const n=AbortSignal.timeout(r.timeout);r.signal!==void 0?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,n])):r.signal=n,delete r.timeout}return r}function we(t={},{callbacks:e,maxConcurrency:r,recursionLimit:n,runName:a,configurable:s,runId:i}={}){const o=ie(t);return e!==void 0&&(delete o.runName,o.callbacks=e),n!==void 0&&(o.recursionLimit=n),r!==void 0&&(o.maxConcurrency=r),a!==void 0&&(o.runName=a),s!==void 0&&(o.configurable={...o.configurable,...s}),i!==void 0&&delete o.runId,o}function Ht(t){return t?{configurable:t.configurable,recursionLimit:t.recursionLimit,callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,maxConcurrency:t.maxConcurrency,timeout:t.timeout,signal:t.signal}:void 0}async function mt(t,e){if(e===void 0)return t;let r;return Promise.race([t.catch(n=>{if(!e?.aborted)throw n}),new Promise((n,a)=>{r=()=>{a(nn(e))},e.addEventListener("abort",r),e.aborted&&a(nn(e))})]).finally(()=>e.removeEventListener("abort",r))}function nn(t){return t?.reason instanceof Error?t.reason:typeof t?.reason=="string"?new Error(t.reason):new Error("Aborted")}var op={};me(op,{AsyncGeneratorWithSetup:()=>Ct,IterableReadableStream:()=>Ge,atee:()=>Ls,concat:()=>Ms,pipeGeneratorWithSetup:()=>pu});var Ge=class Xa extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){const r=this.reader.cancel();this.reader.releaseLock(),await r}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){const r=e.getReader();return new Xa({start(n){return a();function a(){return r.read().then(({done:s,value:i})=>{if(s){n.close();return}return n.enqueue(i),a()})}},cancel(){r.releaseLock()}})}static fromAsyncGenerator(e){return new Xa({async pull(r){const{value:n,done:a}=await e.next();a&&r.close(),r.enqueue(n)},async cancel(r){await e.return(r)}})}};function Ls(t,e=2){const r=Array.from({length:e},()=>[]);return r.map(async function*(a){for(;;)if(a.length===0){const s=await t.next();for(const i of r)i.push(s)}else{if(a[0].done)return;yield a.shift().value}})}function Ms(t,e){if(Array.isArray(t)&&Array.isArray(e))return t.concat(e);if(typeof t=="string"&&typeof e=="string")return t+e;if(typeof t=="number"&&typeof e=="number")return t+e;if("concat"in t&&typeof t.concat=="function")return t.concat(e);if(typeof t=="object"&&typeof e=="object"){const r={...t};for(const[n,a]of Object.entries(e))n in r&&!Array.isArray(r[n])?r[n]=Ms(r[n],a):r[n]=a;return r}else throw new Error(`Cannot concat ${typeof t} and ${typeof e}`)}var Ct=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(t){this.generator=t.generator,this.config=t.config,this.signal=t.signal??this.config?.signal,this.setup=new Promise((e,r)=>{ct.runWithConfig(Ht(t.config),async()=>{this.firstResult=t.generator.next(),t.startSetup?this.firstResult.then(t.startSetup).then(e,r):this.firstResult.then(n=>e(void 0),r)},!0)})}async next(...t){return this.signal?.throwIfAborted(),this.firstResultUsed?ct.runWithConfig(Ht(this.config),this.signal?async()=>mt(this.generator.next(...t),this.signal):async()=>this.generator.next(...t),!0):(this.firstResultUsed=!0,this.firstResult)}async return(t){return this.generator.return(t)}async throw(t){return this.generator.throw(t)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function pu(t,e,r,n,...a){const s=new Ct({generator:e,startSetup:r,signal:n}),i=await s.setup;return{output:t(s,i,...a),setup:i}}const cp=Object.prototype.hasOwnProperty;function up(t,e){return cp.call(t,e)}function lp(t){if(Array.isArray(t)){const r=new Array(t.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(t);let e=[];for(let r in t)up(t,r)&&e.push(r);return e}function At(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Qa(t){let e=0;const r=t.length;let n;for(;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function Ng(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function dp(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function es(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(es(t[r]))return!0}else if(typeof t=="object"){const r=lp(t),n=r.length;for(var e=0;e<n;e++)if(es(t[r[e]]))return!0}}return!1}function Do(t,e){const r=[t];for(const n in e){const a=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof a<"u"&&r.push(`${n}: ${a}`)}return r.join(`
54
+ `)}var fp=class extends Error{constructor(t,e,r,n,a){super(Do(t,{name:e,index:r,operation:n,tree:a})),this.name=e,this.index=r,this.operation=n,this.tree=a,Object.setPrototypeOf(this,new.target.prototype),this.message=Do(t,{name:e,index:r,operation:n,tree:a})}},mu={};me(mu,{JsonPatchError:()=>ue,_areEquals:()=>vr,applyOperation:()=>St,applyPatch:()=>yr,applyReducer:()=>mp,deepClone:()=>hp,getValueByPointer:()=>an,validate:()=>gu,validator:()=>sn});const ue=fp,hp=At,jt={add:function(t,e,r){return t[e]=this.value,{newDocument:r}},remove:function(t,e,r){var n=t[e];return delete t[e],{newDocument:r,removed:n}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:function(t,e,r){let n=an(r,this.path);n&&(n=At(n));const a=St(r,{op:"remove",path:this.from}).removed;return St(r,{op:"add",path:this.path,value:a}),{newDocument:r,removed:n}},copy:function(t,e,r){const n=an(r,this.from);return St(r,{op:"add",path:this.path,value:At(n)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:vr(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}};var pp={add:function(t,e,r){return Qa(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},remove:function(t,e,r){var n=t.splice(e,1);return{newDocument:r,removed:n[0]}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:jt.move,copy:jt.copy,test:jt.test,_get:jt._get};function an(t,e){if(e=="")return t;var r={op:"_get",path:e};return St(t,r),r.value}function St(t,e,r=!1,n=!0,a=!0,s=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):sn(e,0)),e.path===""){let i={newDocument:t};if(e.op==="add")return i.newDocument=e.value,i;if(e.op==="replace")return i.newDocument=e.value,i.removed=t,i;if(e.op==="move"||e.op==="copy")return i.newDocument=an(t,e.from),e.op==="move"&&(i.removed=t),i;if(e.op==="test"){if(i.test=vr(t,e.value),i.test===!1)throw new ue("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i.newDocument=t,i}else{if(e.op==="remove")return i.removed=t,i.newDocument=null,i;if(e.op==="_get")return e.value=t,i;if(r)throw new ue("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,t);return i}}else{n||(t=At(t));const o=(e.path||"").split("/");let c=t,u=1,l=o.length,d,f,h;for(typeof r=="function"?h=r:h=sn;;){if(f=o[u],f&&f.indexOf("~")!=-1&&(f=dp(f)),a&&(f=="__proto__"||f=="prototype"&&u>0&&o[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&d===void 0&&(c[f]===void 0?d=o.slice(0,u).join("/"):u==l-1&&(d=e.path),d!==void 0&&h(e,0,t,d)),u++,Array.isArray(c)){if(f==="-")f=c.length;else{if(r&&!Qa(f))throw new ue("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,t);Qa(f)&&(f=~~f)}if(u>=l){if(r&&e.op==="add"&&f>c.length)throw new ue("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,t);const p=pp[e.op].call(e,c,f,t);if(p.test===!1)throw new ue("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return p}}else if(u>=l){const p=jt[e.op].call(e,c,f,t);if(p.test===!1)throw new ue("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return p}if(c=c[f],r&&u<l&&(!c||typeof c!="object"))throw new ue("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,t)}}}function yr(t,e,r,n=!0,a=!0){if(r&&!Array.isArray(e))throw new ue("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=At(t));const s=new Array(e.length);for(let i=0,o=e.length;i<o;i++)s[i]=St(t,e[i],r,!0,a,i),t=s[i].newDocument;return s.newDocument=t,s}function mp(t,e,r){const n=St(t,e);if(n.test===!1)throw new ue("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function sn(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new ue("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(jt[t.op]){if(typeof t.path!="string")throw new ue("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new ue('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new ue("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new ue("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&es(t.value))throw new ue("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var a=t.path.split("/").length,s=n.split("/").length;if(a!==s+1&&a!==s)throw new ue("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new ue("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var i={op:"_get",path:t.from,value:void 0},o=gu([i],r);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new ue("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new ue("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function gu(t,e,r){try{if(!Array.isArray(t))throw new ue("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)yr(At(e),At(t),r||!0);else{r=r||sn;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(a){if(a instanceof ue)return a;throw a}}function vr(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=Array.isArray(t),n=Array.isArray(e),a,s,i;if(r&&n){if(s=t.length,s!=e.length)return!1;for(a=s;a--!==0;)if(!vr(t[a],e[a]))return!1;return!0}if(r!=n)return!1;var o=Object.keys(t);if(s=o.length,s!==Object.keys(e).length)return!1;for(a=s;a--!==0;)if(!e.hasOwnProperty(o[a]))return!1;for(a=s;a--!==0;)if(i=o[a],!vr(t[i],e[i]))return!1;return!0}return t!==t&&e!==e}({...mu});var gp={};me(gp,{LogStreamCallbackHandler:()=>rs,RunLog:()=>js,RunLogPatch:()=>tt,isLogStreamHandler:()=>_u});var tt=class{ops;constructor(t){this.ops=t.ops??[]}concat(t){const e=this.ops.concat(t.ops),r=yr({},e);return new js({ops:e,state:r[r.length-1].newDocument})}},js=class ts extends tt{state;constructor(e){super(e),this.state=e.state}concat(e){const r=this.ops.concat(e.ops),n=yr(this.state,e.ops);return new ts({ops:r,state:n[n.length-1].newDocument})}static fromRunLogPatch(e){const r=yr({},e.ops);return new ts({ops:e.ops,state:r[r.length-1].newDocument})}};const _u=t=>t.name==="log_stream_tracer";async function Uo(t,e){if(e==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:r}=t;if(["retriever","llm","prompt"].includes(t.run_type))return r;if(!(Object.keys(r).length===1&&r?.input===""))return r.input}async function Fo(t,e){const{outputs:r}=t;return e==="original"||["retriever","llm","prompt"].includes(t.run_type)?r:r!==void 0&&Object.keys(r).length===1&&r?.output!==void 0?r.output:r}function _p(t){return t!==void 0&&t.message!==void 0}var rs=class extends Jt{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat="original";rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name="log_stream_tracer";lc_prefer_streaming=!0;constructor(t){super({_awaitHandler:!0,...t}),this.autoClose=t?.autoClose??!0,this.includeNames=t?.includeNames,this.includeTypes=t?.includeTypes,this.includeTags=t?.includeTags,this.excludeNames=t?.excludeNames,this.excludeTypes=t?.excludeTypes,this.excludeTags=t?.excludeTags,this._schemaFormat=t?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Ge.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(t){}_includeRun(t){if(t.id===this.rootId)return!1;const e=t.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(t.run_type)),this.includeTags!==void 0&&(r=r||e.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(t.run_type)),this.excludeTags!==void 0&&(r=r&&e.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(t,e){for await(const r of e){if(t!==this.rootId){const n=this.keyMapByRunId[t];n&&await this.writer.write(new tt({ops:[{op:"add",path:`/logs/${n}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(t){if(this.rootId===void 0&&(this.rootId=t.id,await this.writer.write(new tt({ops:[{op:"replace",path:"",value:{id:t.id,name:t.name,type:t.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(t))return;this.counterMapByRunName[t.name]===void 0&&(this.counterMapByRunName[t.name]=0),this.counterMapByRunName[t.name]+=1;const e=this.counterMapByRunName[t.name];this.keyMapByRunId[t.id]=e===1?t.name:`${t.name}:${e}`;const r={id:t.id,name:t.name,type:t.run_type,tags:t.tags??[],metadata:t.extra?.metadata??{},start_time:new Date(t.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(r.inputs=await Uo(t,this._schemaFormat)),await this.writer.write(new tt({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[t.id]}`,value:r}]}))}async onRunUpdate(t){try{const e=this.keyMapByRunId[t.id];if(e===void 0)return;const r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${e}/inputs`,value:await Uo(t,this._schemaFormat)}),r.push({op:"add",path:`/logs/${e}/final_output`,value:await Fo(t,this._schemaFormat)}),t.end_time!==void 0&&r.push({op:"add",path:`/logs/${e}/end_time`,value:new Date(t.end_time).toISOString()});const n=new tt({ops:r});await this.writer.write(n)}finally{if(t.id===this.rootId){const e=new tt({ops:[{op:"replace",path:"/final_output",value:await Fo(t,this._schemaFormat)}]});await this.writer.write(e),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(t,e,r){const n=this.keyMapByRunId[t.id];if(n===void 0)return;const a=t.inputs.messages!==void 0;let s;a?_p(r?.chunk)?s=r?.chunk:s=new Ot({id:`run-${t.id}`,content:e}):s=e;const i=new tt({ops:[{op:"add",path:`/logs/${n}/streamed_output_str/-`,value:e},{op:"add",path:`/logs/${n}/streamed_output/-`,value:s}]});await this.writer.write(i)}},yp={};me(yp,{ChatGenerationChunk:()=>wp,GenerationChunk:()=>on,RUN_KEY:()=>vp});const vp="__run";var on=class yu{text;generationInfo;constructor(e){this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new yu({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}},wp=class vu extends on{message;constructor(e){super(e),this.message=e.message}concat(e){return new vu({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo},message:this.message.concat(e.message)})}};function qr({name:t,serialized:e}){return t!==void 0?t:e?.name!==void 0?e.name:e?.id!==void 0&&Array.isArray(e?.id)?e.id[e.id.length-1]:"Unnamed"}const bp=t=>t.name==="event_stream_tracer";var Ep=class extends Jt{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;name="event_stream_tracer";lc_prefer_streaming=!0;constructor(t){super({_awaitHandler:!0,...t}),this.autoClose=t?.autoClose??!0,this.includeNames=t?.includeNames,this.includeTypes=t?.includeTypes,this.includeTags=t?.includeTags,this.excludeNames=t?.excludeNames,this.excludeTypes=t?.excludeTypes,this.excludeTags=t?.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Ge.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(t){}_includeRun(t){const e=t.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(t.runType)),this.includeTags!==void 0&&(r=r||e.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(t.runType)),this.excludeTags!==void 0&&(r=r&&e.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(t,e){const r=await e.next();if(r.done)return;const n=this.runInfoMap.get(t);if(n===void 0){yield r.value;return}function a(i,o){return i==="llm"&&typeof o=="string"?new on({text:o}):o}let s=this.tappedPromises.get(t);if(s===void 0){let i;s=new Promise(o=>{i=o}),this.tappedPromises.set(t,s);try{const o={event:`on_${n.runType}_stream`,run_id:t,name:n.name,tags:n.tags,metadata:n.metadata,data:{}};await this.send({...o,data:{chunk:a(n.runType,r.value)}},n),yield r.value;for await(const c of e)n.runType!=="tool"&&n.runType!=="retriever"&&await this.send({...o,data:{chunk:a(n.runType,c)}},n),yield c}finally{i?.()}}else{yield r.value;for await(const i of e)yield i}}async send(t,e){this._includeRun(e)&&await this.writer.write(t)}async sendEndEvent(t,e){const r=this.tappedPromises.get(t.run_id);r!==void 0?r.then(()=>{this.send(t,e)}):await this.send(t,e)}async onLLMStart(t){const e=qr(t),r=t.inputs.messages!==void 0?"chat_model":"llm",n={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:r,inputs:t.inputs};this.runInfoMap.set(t.id,n);const a=`on_${r}_start`;await this.send({event:a,data:{input:t.inputs},name:e,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},n)}async onLLMNewToken(t,e,r){const n=this.runInfoMap.get(t.id);let a,s;if(n===void 0)throw new Error(`onLLMNewToken: Run ID ${t.id} not found in run map.`);if(this.runInfoMap.size!==1){if(n.runType==="chat_model")s="on_chat_model_stream",r?.chunk===void 0?a=new Ot({content:e,id:`run-${t.id}`}):a=r.chunk.message;else if(n.runType==="llm")s="on_llm_stream",r?.chunk===void 0?a=new on({text:e}):a=r.chunk;else throw new Error(`Unexpected run type ${n.runType}`);await this.send({event:s,data:{chunk:a},run_id:t.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}}async onLLMEnd(t){const e=this.runInfoMap.get(t.id);this.runInfoMap.delete(t.id);let r;if(e===void 0)throw new Error(`onLLMEnd: Run ID ${t.id} not found in run map.`);const n=t.outputs?.generations;let a;if(e.runType==="chat_model"){for(const s of n??[]){if(a!==void 0)break;a=s[0]?.message}r="on_chat_model_end"}else if(e.runType==="llm")a={generations:n?.map(s=>s.map(i=>({text:i.text,generationInfo:i.generationInfo}))),llmOutput:t.outputs?.llmOutput??{}},r="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${e.runType}`);await this.sendEndEvent({event:r,data:{output:a,input:e.inputs},run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata},e)}async onChainStart(t){const e=qr(t),r=t.run_type??"chain",n={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:t.run_type};let a={};t.inputs.input===""&&Object.keys(t.inputs).length===1?(a={},n.inputs={}):t.inputs.input!==void 0?(a.input=t.inputs.input,n.inputs=t.inputs.input):(a.input=t.inputs,n.inputs=t.inputs),this.runInfoMap.set(t.id,n),await this.send({event:`on_${r}_start`,data:a,name:e,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},n)}async onChainEnd(t){const e=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),e===void 0)throw new Error(`onChainEnd: Run ID ${t.id} not found in run map.`);const r=`on_${t.run_type}_end`,n=t.inputs??e.inputs??{},s={output:t.outputs?.output??t.outputs,input:n};n.input&&Object.keys(n).length===1&&(s.input=n.input,e.inputs=n.input),await this.sendEndEvent({event:r,data:s,run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata??{}},e)}async onToolStart(t){const e=qr(t),r={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:"tool",inputs:t.inputs??{}};this.runInfoMap.set(t.id,r),await this.send({event:"on_tool_start",data:{input:t.inputs??{}},name:e,run_id:t.id,tags:t.tags??[],metadata:t.extra?.metadata??{}},r)}async onToolEnd(t){const e=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),e===void 0)throw new Error(`onToolEnd: Run ID ${t.id} not found in run map.`);if(e.inputs===void 0)throw new Error(`onToolEnd: Run ID ${t.id} is a tool call, and is expected to have traced inputs.`);const r=t.outputs?.output===void 0?t.outputs:t.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:e.inputs},run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata},e)}async onRetrieverStart(t){const e=qr(t),n={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:"retriever",inputs:{query:t.inputs.query}};this.runInfoMap.set(t.id,n),await this.send({event:"on_retriever_start",data:{input:{query:t.inputs.query}},name:e,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},n)}async onRetrieverEnd(t){const e=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),e===void 0)throw new Error(`onRetrieverEnd: Run ID ${t.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:t.outputs?.documents??t.outputs,input:e.inputs},run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata},e)}async handleCustomEvent(t,e,r){const n=this.runInfoMap.get(r);if(n===void 0)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:t,tags:n.tags,metadata:n.metadata,data:e},n)}async finish(){const t=[...this.tappedPromises.values()];Promise.all(t).finally(()=>{this.writer.close()})}},Sp={};me(Sp,{AsyncCaller:()=>wu});const Tp=[400,401,402,403,404,405,406,407,409],xp=t=>{if(t.message.startsWith("Cancel")||t.message.startsWith("AbortError")||t.name==="AbortError"||t?.code==="ECONNABORTED")throw t;const e=t?.response?.status??t?.status;if(e&&Tp.includes(+e))throw t;if(t?.error?.code==="insufficient_quota"){const r=new Error(t?.message);throw r.name="InsufficientQuotaError",r}};var wu=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(t){this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,this.onFailedAttempt=t.onFailedAttempt??xp;const e="default"in nt?nt.default:nt;this.queue=new e({concurrency:this.maxConcurrency})}call(t,...e){return this.queue.add(()=>en(()=>t(...e).catch(r=>{throw r instanceof Error?r:new Error(r)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(t,e,...r){if(t.signal){let n;return Promise.race([this.call(e,...r),new Promise((a,s)=>{n=()=>{s(nn(t.signal))},t.signal?.addEventListener("abort",n)})]).finally(()=>{t.signal&&n&&t.signal.removeEventListener("abort",n)})}return this.call(e,...r)}fetch(...t){return this.call(()=>fetch(...t).then(e=>e.ok?e:Promise.reject(e)))}},bu=class extends Jt{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:t,onStart:e,onEnd:r,onError:n}){super({_awaitHandler:!0}),this.config=t,this.argOnStart=e,this.argOnEnd=r,this.argOnError=n}persistRun(t){return Promise.resolve()}async onRunCreate(t){this.rootId||(this.rootId=t.id,this.argOnStart&&await this.argOnStart(t,this.config))}async onRunUpdate(t){t.id===this.rootId&&(t.error?this.argOnError&&await this.argOnError(t,this.config):this.argOnEnd&&await this.argOnEnd(t,this.config))}};function Ds(t){return t?t.lc_runnable:!1}var Ip=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(t){this.includeNames=t.includeNames,this.includeTypes=t.includeTypes,this.includeTags=t.includeTags,this.excludeNames=t.excludeNames,this.excludeTypes=t.excludeTypes,this.excludeTags=t.excludeTags}includeEvent(t,e){let r=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0;const n=t.tags??[];return this.includeNames!==void 0&&(r=r||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e)),this.includeTags!==void 0&&(r=r||n.some(a=>this.includeTags?.includes(a))),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e)),this.excludeTags!==void 0&&(r=r&&n.every(a=>!this.excludeTags?.includes(a))),r}};function fe(t){if(typeof t!="object"||t===null)return!1;const e=t;if(!("_zod"in e))return!1;const r=e._zod;return typeof r=="object"&&r!==null&&"def"in r}function ge(t){if(typeof t!="object"||t===null)return!1;const e=t;if(!("_def"in e)||"_zod"in e)return!1;const r=e._def;return typeof r=="object"&&r!=null&&"typeName"in r}function Pg(t){return fe(t)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),ge(t)}function Eu(t){return!t||typeof t!="object"||Array.isArray(t)?!1:!!(fe(t)||ge(t))}function Ap(t){return typeof t=="object"&&t!==null&&"_def"in t&&typeof t._def=="object"&&t._def!==null&&"typeName"in t._def&&t._def.typeName==="ZodLiteral"}function Rp(t){return fe(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="literal":!1}function Lg(t){return!!(Ap(t)||Rp(t))}async function Mg(t,e){if(fe(t))try{return{success:!0,data:await tc(t,e)}}catch(r){return{success:!1,error:r}}if(ge(t))return await t.safeParseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function Op(t,e){if(fe(t))return await tc(t,e);if(ge(t))return await t.parseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function jg(t,e){if(fe(t))try{return{success:!0,data:is(t,e)}}catch(r){return{success:!1,error:r}}if(ge(t))return t.safeParse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Dg(t,e){if(fe(t))return is(t,e);if(ge(t))return t.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function $p(t){if(fe(t))return Le.get(t)?.description;if(ge(t)||"description"in t&&typeof t.description=="string")return t.description}function Ug(t){if(!Eu(t))return!1;if(ge(t)){const e=t._def;if(e.typeName==="ZodObject"){const r=t;return!r.shape||Object.keys(r.shape).length===0}if(e.typeName==="ZodRecord")return!0}if(fe(t)){const e=t._zod.def;if(e.type==="object"){const r=t;return!r.shape||Object.keys(r.shape).length===0}if(e.type==="record")return!0}return typeof t=="object"&&t!==null&&!("shape"in t)}function kp(t){return Eu(t)?ge(t)?t._def.typeName==="ZodString":fe(t)?t._zod.def.type==="string":!1:!1}function Su(t){return typeof t=="object"&&t!==null&&"_def"in t&&typeof t._def=="object"&&t._def!==null&&"typeName"in t._def&&t._def.typeName==="ZodObject"}function at(t){return fe(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="object":!1}function Us(t){return fe(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="array":!1}function Fg(t){return!!(Su(t)||at(t))}function Bo(t){if(ge(t))return t.shape;if(fe(t))return t._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Bg(t,e){if(ge(t))return t.extend(e);if(fe(t))return Yu(t,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function zg(t){if(ge(t))return t.partial();if(fe(t))return Xu(rc,t,void 0);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function ns(t,e=!1){if(ge(t))return t.strict();if(at(t)){const r=t._zod.def.shape;if(e)for(const[s,i]of Object.entries(t._zod.def.shape)){if(at(i)){const c=ns(i,e);r[s]=c}else if(Us(i)){let c=i._zod.def.element;at(c)&&(c=ns(c,e)),r[s]=Tt(i,{...i._zod.def,element:c})}else r[s]=i;const o=Le.get(i);o&&Le.add(r[s],o)}const n=Tt(t,{...t._zod.def,shape:r,catchall:Ju(Ku)}),a=Le.get(t);return a&&Le.add(n,a),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function zo(t,e=!1){if(Su(t))return t.passthrough();if(at(t)){const r=t._zod.def.shape;if(e)for(const[s,i]of Object.entries(t._zod.def.shape)){if(at(i)){const c=zo(i,e);r[s]=c}else if(Us(i)){let c=i._zod.def.element;at(c)&&(c=zo(c,e)),r[s]=Tt(i,{...i._zod.def,element:c})}else r[s]=i;const o=Le.get(i);o&&Le.add(r[s],o)}const n=Tt(t,{...t._zod.def,shape:r,catchall:Qu(el)}),a=Le.get(t);return a&&Le.add(n,a),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function qg(t){if(ge(t))try{const e=t.parse(void 0);return()=>e}catch{return}if(fe(t))try{const e=is(t,void 0);return()=>e}catch{return}}function Cp(t){return ge(t)&&"typeName"in t._def&&t._def.typeName==="ZodEffects"}function Np(t){return fe(t)&&t._zod.def.type==="pipe"}function rr(t,e=!1){if(ge(t))return Cp(t)?rr(t._def.schema,e):t;if(fe(t)){let r=t;if(Np(t)&&(r=rr(t._zod.def.in,e)),e){if(at(r)){const a=r._zod.def.shape;for(const[s,i]of Object.entries(r._zod.def.shape))a[s]=rr(i,e);r=Tt(r,{...r._zod.def,shape:a})}else if(Us(r)){const a=rr(r._zod.def.element,e);r=Tt(r,{...r._zod.def,element:a})}}const n=Le.get(t);return n&&Le.add(r,n),r}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Gg(t,e){if(ge(t)){const r=Bo(t),n={};for(const[a,s]of Object.entries(r))e(a,s)?n[a]=s.optional():n[a]=s;return t.extend(n)}if(fe(t)){const r=Bo(t),n={...t._zod.def.shape};for(const[i,o]of Object.entries(r))e(i,o)&&(n[i]=new rc({type:"optional",innerType:o}));const a=Tt(t,{...t._zod.def,shape:n}),s=Le.get(t);return s&&Le.add(a,s),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Pa(t){return t.replace(/[^a-zA-Z-_0-9]/g,"_")}const Pp=["*","_","`"];function Lp(t){let e="";for(const[r,n]of Object.entries(t))e+=` classDef ${r} ${n};
55
+ `;return e}function Mp(t,e,r){const{firstNode:n,lastNode:a,nodeColors:s,withStyles:i=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=r??{};let u=i?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
58
56
  graph TD;
59
57
  `:`graph TD;
60
- `;if(i){const h="default",p={[h]:"{0}({1})"};n!==void 0&&(p[n]="{0}([{1}]):::first"),a!==void 0&&(p[a]="{0}([{1}]):::last");for(const[m,g]of Object.entries(t)){const y=g.name.split(":").pop()??"";let _=Dp.some($=>y.startsWith($)&&y.endsWith($))?`<p>${y}</p>`:y;Object.keys(g.metadata??{}).length&&(_+=`<hr/><small><em>${Object.entries(g.metadata??{}).map(([$,U])=>`${$} = ${U}`).join(`
61
- `)}</em></small>`);const E=(p[m]??p[h]).replace("{0}",Ma(m)).replace("{1}",_);u+=` ${E}
62
- `}}const l={};for(const h of e){const p=h.source.split(":"),m=h.target.split(":"),g=p.filter((y,v)=>y===m[v]).join(":");l[g]||(l[g]=[]),l[g].push(h)}const d=new Set;function f(h,p){const m=h.length===1&&h[0].source===h[0].target;if(p&&!m){const g=p.split(":").pop();if(d.has(g))throw new Error(`Found duplicate subgraph '${g}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(g),u+=` subgraph ${g}
63
- `}for(const g of h){const{source:y,target:v,data:_,conditional:E}=g;let $="";if(_!==void 0){let U=_;const z=U.split(" ");z.length>c&&(U=Array.from({length:Math.ceil(z.length/c)},(O,oe)=>z.slice(oe*c,(oe+1)*c).join(" ")).join("&nbsp;<br>&nbsp;")),$=E?` -. &nbsp;${U}&nbsp; .-> `:` -- &nbsp;${U}&nbsp; --> `}else $=E?" -.-> ":" --> ";u+=` ${Ma(y)}${$}${Ma(v)};
64
- `}for(const g in l)g.startsWith(`${p}:`)&&g!==p&&f(l[g],g);p&&!m&&(u+=` end
65
- `)}f(l[""]??[],"");for(const h in l)!h.includes(":")&&h!==""&&f(l[h],h);return i&&(u+=Up(s??{})),u}async function Bp(t,e){let r=e?.backgroundColor??"white";const n=e?.imageType??"png",a=btoa(t);r!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));const s=`https://mermaid.ink/img/${a}?bgColor=${r}&type=${n}`,i=await fetch(s);if(!i.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join(`
66
- `));return await i.blob()}const zp=Symbol("Let zodToJsonSchema decide on which parser to use"),qp={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Gp=t=>({...qp,...t}),Hp=t=>{const e=Gp(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,a])=>[a._def,{def:a._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}},Iu=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function Pe(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Iu(e,t.currentPath):e.join("/")}}function Au(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ae(t,e,r,n,a){t[e]=r,Au(t,e,n,a)}function Zp(t,e){const r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==b.ZodAny&&(r.items=re(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ae(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ae(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ae(r,"minItems",t.exactLength.value,t.exactLength.message,e),ae(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Vp(t,e){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ae(r,"minimum",n.value,n.message,e):ae(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ae(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ae(r,"maximum",n.value,n.message,e):ae(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ae(r,"maximum",n.value,n.message,e));break;case"multipleOf":ae(r,"multipleOf",n.value,n.message,e);break}return r}function Jp(){return{type:"boolean"}}function Ou(t,e){return re(t.type._def,e)}const Wp=(t,e)=>re(t.innerType._def,e);function Ru(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(a=>Ru(t,e,a))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Kp(t,e)}}const Kp=(t,e)=>{const r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(const n of t.checks)switch(n.kind){case"min":ae(r,"minimum",n.value,n.message,e);break;case"max":ae(r,"maximum",n.value,n.message,e);break}return r};function Yp(t,e){return{...re(t.innerType._def,e),default:t.defaultValue()}}function Xp(t,e){return e.effectStrategy==="input"?re(t.schema._def,e):Pe(e)}function Qp(t){return{type:"string",enum:Array.from(t.values)}}const em=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function tm(t,e){const r=[re(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),re(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const a=[];return r.forEach(s=>{if(em(s))a.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:o,...c}=s;i=c}else n=void 0;a.push(i)}}),a.length?{allOf:a,...n}:void 0}function rm(t,e){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}let La;const Fe={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(La===void 0&&(La=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),La),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function ku(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":ae(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ae(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Be(r,"email",n.message,e);break;case"format:idn-email":Be(r,"idn-email",n.message,e);break;case"pattern:zod":Ee(r,Fe.email,n.message,e);break}break;case"url":Be(r,"uri",n.message,e);break;case"uuid":Be(r,"uuid",n.message,e);break;case"regex":Ee(r,n.regex,n.message,e);break;case"cuid":Ee(r,Fe.cuid,n.message,e);break;case"cuid2":Ee(r,Fe.cuid2,n.message,e);break;case"startsWith":Ee(r,RegExp(`^${ja(n.value,e)}`),n.message,e);break;case"endsWith":Ee(r,RegExp(`${ja(n.value,e)}$`),n.message,e);break;case"datetime":Be(r,"date-time",n.message,e);break;case"date":Be(r,"date",n.message,e);break;case"time":Be(r,"time",n.message,e);break;case"duration":Be(r,"duration",n.message,e);break;case"length":ae(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ae(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":Ee(r,RegExp(ja(n.value,e)),n.message,e);break;case"ip":n.version!=="v6"&&Be(r,"ipv4",n.message,e),n.version!=="v4"&&Be(r,"ipv6",n.message,e);break;case"base64url":Ee(r,Fe.base64url,n.message,e);break;case"jwt":Ee(r,Fe.jwt,n.message,e);break;case"cidr":n.version!=="v6"&&Ee(r,Fe.ipv4Cidr,n.message,e),n.version!=="v4"&&Ee(r,Fe.ipv6Cidr,n.message,e);break;case"emoji":Ee(r,Fe.emoji(),n.message,e);break;case"ulid":Ee(r,Fe.ulid,n.message,e);break;case"base64":switch(e.base64Strategy){case"format:binary":Be(r,"binary",n.message,e);break;case"contentEncoding:base64":ae(r,"contentEncoding","base64",n.message,e);break;case"pattern:zod":Ee(r,Fe.base64,n.message,e);break}break;case"nanoid":Ee(r,Fe.nanoid,n.message,e);break}return r}function ja(t,e){return e.patternStrategy==="escape"?am(t):t}const nm=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function am(t){let e="";for(let r=0;r<t.length;r++)nm.has(t[r])||(e+="\\"),e+=t[r];return e}function Be(t,e,r,n){t.format||t.anyOf?.some(a=>a.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ae(t,"format",e,r,n)}function Ee(t,e,r,n){t.pattern||t.allOf?.some(a=>a.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Ho(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ae(t,"pattern",Ho(e,n),r,n)}function Ho(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source;let a="",s=!1,i=!1,o=!1;for(let c=0;c<n.length;c++){if(s){a+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){o?(a+=n[c],a+=`${n[c-2]}-${n[c]}`.toUpperCase(),o=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(a+=n[c],o=!0):a+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){a+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){a+=`(^|(?<=[\r
58
+ `;if(i){const h="default",p={[h]:"{0}({1})"};n!==void 0&&(p[n]="{0}([{1}]):::first"),a!==void 0&&(p[a]="{0}([{1}]):::last");for(const[g,m]of Object.entries(t)){const _=m.name.split(":").pop()??"";let y=Pp.some(C=>_.startsWith(C)&&_.endsWith(C))?`<p>${_}</p>`:_;Object.keys(m.metadata??{}).length&&(y+=`<hr/><small><em>${Object.entries(m.metadata??{}).map(([C,B])=>`${C} = ${B}`).join(`
59
+ `)}</em></small>`);const I=(p[g]??p[h]).replace("{0}",Pa(g)).replace("{1}",y);u+=` ${I}
60
+ `}}const l={};for(const h of e){const p=h.source.split(":"),g=h.target.split(":"),m=p.filter((_,w)=>_===g[w]).join(":");l[m]||(l[m]=[]),l[m].push(h)}const d=new Set;function f(h,p){const g=h.length===1&&h[0].source===h[0].target;if(p&&!g){const m=p.split(":").pop();if(d.has(m))throw new Error(`Found duplicate subgraph '${m}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(m),u+=` subgraph ${m}
61
+ `}for(const m of h){const{source:_,target:w,data:y,conditional:I}=m;let C="";if(y!==void 0){let B=y;const z=B.split(" ");z.length>c&&(B=Array.from({length:Math.ceil(z.length/c)},(R,oe)=>z.slice(oe*c,(oe+1)*c).join(" ")).join("&nbsp;<br>&nbsp;")),C=I?` -. &nbsp;${B}&nbsp; .-> `:` -- &nbsp;${B}&nbsp; --> `}else C=I?" -.-> ":" --> ";u+=` ${Pa(_)}${C}${Pa(w)};
62
+ `}for(const m in l)m.startsWith(`${p}:`)&&m!==p&&f(l[m],m);p&&!g&&(u+=` end
63
+ `)}f(l[""]??[],"");for(const h in l)!h.includes(":")&&h!==""&&f(l[h],h);return i&&(u+=Lp(s??{})),u}async function jp(t,e){let r=e?.backgroundColor??"white";const n=e?.imageType??"png",a=btoa(t);r!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));const s=`https://mermaid.ink/img/${a}?bgColor=${r}&type=${n}`,i=await fetch(s);if(!i.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join(`
64
+ `));return await i.blob()}const Dp=Symbol("Let zodToJsonSchema decide on which parser to use"),Up={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Fp=t=>({...Up,...t}),Bp=t=>{const e=Fp(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,a])=>[a._def,{def:a._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}},Tu=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function Ce(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Tu(e,t.currentPath):e.join("/")}}function xu(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ae(t,e,r,n,a){t[e]=r,xu(t,e,n,a)}function zp(t,e){const r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==b.ZodAny&&(r.items=re(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ae(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ae(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ae(r,"minItems",t.exactLength.value,t.exactLength.message,e),ae(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function qp(t,e){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ae(r,"minimum",n.value,n.message,e):ae(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ae(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ae(r,"maximum",n.value,n.message,e):ae(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ae(r,"maximum",n.value,n.message,e));break;case"multipleOf":ae(r,"multipleOf",n.value,n.message,e);break}return r}function Gp(){return{type:"boolean"}}function Iu(t,e){return re(t.type._def,e)}const Hp=(t,e)=>re(t.innerType._def,e);function Au(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(a=>Au(t,e,a))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Zp(t,e)}}const Zp=(t,e)=>{const r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(const n of t.checks)switch(n.kind){case"min":ae(r,"minimum",n.value,n.message,e);break;case"max":ae(r,"maximum",n.value,n.message,e);break}return r};function Vp(t,e){return{...re(t.innerType._def,e),default:t.defaultValue()}}function Wp(t,e){return e.effectStrategy==="input"?re(t.schema._def,e):Ce(e)}function Jp(t){return{type:"string",enum:Array.from(t.values)}}const Kp=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Yp(t,e){const r=[re(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),re(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const a=[];return r.forEach(s=>{if(Kp(s))a.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:o,...c}=s;i=c}else n=void 0;a.push(i)}}),a.length?{allOf:a,...n}:void 0}function Xp(t,e){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}let La;const Ue={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(La===void 0&&(La=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),La),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Ru(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":ae(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ae(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Fe(r,"email",n.message,e);break;case"format:idn-email":Fe(r,"idn-email",n.message,e);break;case"pattern:zod":Ee(r,Ue.email,n.message,e);break}break;case"url":Fe(r,"uri",n.message,e);break;case"uuid":Fe(r,"uuid",n.message,e);break;case"regex":Ee(r,n.regex,n.message,e);break;case"cuid":Ee(r,Ue.cuid,n.message,e);break;case"cuid2":Ee(r,Ue.cuid2,n.message,e);break;case"startsWith":Ee(r,RegExp(`^${Ma(n.value,e)}`),n.message,e);break;case"endsWith":Ee(r,RegExp(`${Ma(n.value,e)}$`),n.message,e);break;case"datetime":Fe(r,"date-time",n.message,e);break;case"date":Fe(r,"date",n.message,e);break;case"time":Fe(r,"time",n.message,e);break;case"duration":Fe(r,"duration",n.message,e);break;case"length":ae(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ae(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":Ee(r,RegExp(Ma(n.value,e)),n.message,e);break;case"ip":n.version!=="v6"&&Fe(r,"ipv4",n.message,e),n.version!=="v4"&&Fe(r,"ipv6",n.message,e);break;case"base64url":Ee(r,Ue.base64url,n.message,e);break;case"jwt":Ee(r,Ue.jwt,n.message,e);break;case"cidr":n.version!=="v6"&&Ee(r,Ue.ipv4Cidr,n.message,e),n.version!=="v4"&&Ee(r,Ue.ipv6Cidr,n.message,e);break;case"emoji":Ee(r,Ue.emoji(),n.message,e);break;case"ulid":Ee(r,Ue.ulid,n.message,e);break;case"base64":switch(e.base64Strategy){case"format:binary":Fe(r,"binary",n.message,e);break;case"contentEncoding:base64":ae(r,"contentEncoding","base64",n.message,e);break;case"pattern:zod":Ee(r,Ue.base64,n.message,e);break}break;case"nanoid":Ee(r,Ue.nanoid,n.message,e);break}return r}function Ma(t,e){return e.patternStrategy==="escape"?em(t):t}const Qp=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function em(t){let e="";for(let r=0;r<t.length;r++)Qp.has(t[r])||(e+="\\"),e+=t[r];return e}function Fe(t,e,r,n){t.format||t.anyOf?.some(a=>a.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ae(t,"format",e,r,n)}function Ee(t,e,r,n){t.pattern||t.allOf?.some(a=>a.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:qo(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ae(t,"pattern",qo(e,n),r,n)}function qo(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source;let a="",s=!1,i=!1,o=!1;for(let c=0;c<n.length;c++){if(s){a+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){o?(a+=n[c],a+=`${n[c-2]}-${n[c]}`.toUpperCase(),o=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(a+=n[c],o=!0):a+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){a+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){a+=`(^|(?<=[\r
67
65
  ]))`;continue}else if(n[c]==="$"){a+=`($|(?=[\r
68
66
  ]))`;continue}}if(r.s&&n[c]==="."){a+=i?`${n[c]}\r
69
67
  `:`[${n[c]}\r
70
- ]`;continue}a+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return a}function $u(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===b.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,a)=>({...n,[a]:re(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",a]})??Pe(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const r={type:"object",additionalProperties:re(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===b.ZodString&&t.keyType._def.checks?.length){const{type:n,...a}=ku(t.keyType._def,e);return{...r,propertyNames:a}}else{if(t.keyType?._def.typeName===b.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===b.ZodBranded&&t.keyType._def.type._def.typeName===b.ZodString&&t.keyType._def.type._def.checks?.length){const{type:n,...a}=Ou(t.keyType._def,e);return{...r,propertyNames:a}}}return r}function sm(t,e){if(e.mapStrategy==="record")return $u(t,e);const r=re(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Pe(e),n=re(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Pe(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function im(t){const e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),a=Array.from(new Set(n.map(s=>typeof s)));return{type:a.length===1?a[0]==="string"?"string":"number":["string","number"],enum:n}}function om(t){return t.target==="openAi"?void 0:{not:Pe({...t,currentPath:[...t.currentPath,"not"]})}}function cm(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const un={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function um(t,e){if(e.target==="openApi3")return Zo(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in un&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((a,s)=>{const i=un[s._def.typeName];return i&&!a.includes(i)?[...a,i]:a},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((a,s)=>{const i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...a,i];case"bigint":return[...a,"integer"];case"object":return s._def.value===null?[...a,"null"]:a;case"symbol":case"undefined":case"function":default:return a}},[]);if(n.length===r.length){const a=n.filter((s,i,o)=>o.indexOf(s)===i);return{type:a.length>1?a:a[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,a)=>[...n,...a._def.values.filter(s=>!n.includes(s))],[])};return Zo(t,e)}const Zo=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,a)=>re(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${a}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function lm(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:un[t.innerType._def.typeName],nullable:!0}:{type:[un[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=re(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=re(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function dm(t,e){const r={type:"number"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"int":r.type="integer",Au(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ae(r,"minimum",n.value,n.message,e):ae(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ae(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ae(r,"maximum",n.value,n.message,e):ae(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ae(r,"maximum",n.value,n.message,e));break;case"multipleOf":ae(r,"multipleOf",n.value,n.message,e);break}return r}function fm(t,e){const r=e.target==="openAi",n={type:"object",properties:{}},a=[],s=t.shape();for(const o in s){let c=s[o];if(c===void 0||c._def===void 0)continue;let u=pm(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=re(c._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});l!==void 0&&(n.properties[o]=l,u||a.push(o))}a.length&&(n.required=a);const i=hm(t,e);return i!==void 0&&(n.additionalProperties=i),n}function hm(t,e){if(t.catchall._def.typeName!=="ZodNever")return re(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function pm(t){try{return t.isOptional()}catch{return!0}}const mm=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return re(t.innerType._def,e);const r=re(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Pe(e)},r]}:Pe(e)},gm=(t,e)=>{if(e.pipeStrategy==="input")return re(t.in._def,e);if(e.pipeStrategy==="output")return re(t.out._def,e);const r=re(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=re(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(a=>a!==void 0)}};function ym(t,e){return re(t.type._def,e)}function _m(t,e){const n={type:"array",uniqueItems:!0,items:re(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ae(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ae(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function vm(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>re(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:re(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>re(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function wm(t){return{not:Pe(t)}}function bm(t){return Pe(t)}const Em=(t,e)=>re(t.innerType._def,e),Sm=(t,e,r)=>{switch(e){case b.ZodString:return ku(t,r);case b.ZodNumber:return dm(t,r);case b.ZodObject:return fm(t,r);case b.ZodBigInt:return Vp(t,r);case b.ZodBoolean:return Jp();case b.ZodDate:return Ru(t,r);case b.ZodUndefined:return wm(r);case b.ZodNull:return cm(r);case b.ZodArray:return Zp(t,r);case b.ZodUnion:case b.ZodDiscriminatedUnion:return um(t,r);case b.ZodIntersection:return tm(t,r);case b.ZodTuple:return vm(t,r);case b.ZodRecord:return $u(t,r);case b.ZodLiteral:return rm(t,r);case b.ZodEnum:return Qp(t);case b.ZodNativeEnum:return im(t);case b.ZodNullable:return lm(t,r);case b.ZodOptional:return mm(t,r);case b.ZodMap:return sm(t,r);case b.ZodSet:return _m(t,r);case b.ZodLazy:return()=>t.getter()._def;case b.ZodPromise:return ym(t,r);case b.ZodNaN:case b.ZodNever:return om(r);case b.ZodEffects:return Xp(t,r);case b.ZodAny:return Pe(r);case b.ZodUnknown:return bm(r);case b.ZodDefault:return Yp(t,r);case b.ZodBranded:return Ou(t,r);case b.ZodReadonly:return Em(t,r);case b.ZodCatch:return Wp(t,r);case b.ZodPipeline:return gm(t,r);case b.ZodFunction:case b.ZodVoid:case b.ZodSymbol:return;default:return(n=>{})()}};function re(t,e,r=!1){const n=e.seen.get(t);if(e.override){const o=e.override?.(t,e,n,r);if(o!==zp)return o}if(n&&!r){const o=Tm(n,e);if(o!==void 0)return o}const a={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,a);const s=Sm(t,t.typeName,e),i=typeof s=="function"?re(s(),e):s;if(i&&xm(t,e,i),e.postProcess){const o=e.postProcess(i,t,e);return a.jsonSchema=i,o}return a.jsonSchema=i,i}const Tm=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Iu(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Pe(e)):e.$refStrategy==="seen"?Pe(e):void 0}},xm=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),Im=(t,e)=>{const r=Hp(e);let n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((o,[c,u])=>({...o,[c]:re(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??Pe(r)}),{}):void 0;const a=typeof e=="string"?e:e?.name,s=re(t._def,r,!1)??Pe(r);r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const i=a===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,a].join("/"),[r.definitionPath]:{...n,[a]:s}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};function Ft(t,e){const r=typeof t;if(r!==typeof e)return!1;if(Array.isArray(t)){if(!Array.isArray(e))return!1;const n=t.length;if(n!==e.length)return!1;for(let a=0;a<n;a++)if(!Ft(t[a],e[a]))return!1;return!0}if(r==="object"){if(!t||!e)return t===e;const n=Object.keys(t),a=Object.keys(e);if(n.length!==a.length)return!1;for(const i of n)if(!Ft(t[i],e[i]))return!1;return!0}return t===e}function ze(t){return encodeURI(Am(t))}function Am(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}const Om={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Rm={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},km={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 $m=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function ht(t,e=Object.create(null),r=$m,n=""){if(t&&typeof t=="object"&&!Array.isArray(t)){const s=t.$id||t.id;if(s){const i=new URL(s,r.href);i.hash.length>1?e[i.href]=t:(i.hash="",n===""?r=i:ht(t,e,r))}}else if(t!==!0&&t!==!1)return e;const a=r.href+(n?"#"+n:"");if(e[a]!==void 0)throw new Error(`Duplicate schema URI "${a}".`);if(e[a]=t,t===!0||t===!1)return e;if(t.__absolute_uri__===void 0&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:a}),t.$ref&&t.__absolute_ref__===void 0){const s=new URL(t.$ref,r.href);s.hash=s.hash,Object.defineProperty(t,"__absolute_ref__",{enumerable:!1,value:s.href})}if(t.$recursiveRef&&t.__absolute_recursive_ref__===void 0){const s=new URL(t.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(t,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(t.$anchor){const s=new URL("#"+t.$anchor,r.href);e[s.href]=t}for(let s in t){if(km[s])continue;const i=`${n}/${ze(s)}`,o=t[s];if(Array.isArray(o)){if(Om[s]){const c=o.length;for(let u=0;u<c;u++)ht(o[u],e,r,`${i}/${u}`)}}else if(Rm[s])for(let c in o)ht(o[c],e,r,`${i}/${ze(c)}`);else ht(o,e,r,i)}return e}const Cm=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Nm=[0,31,28,31,30,31,30,31,31,30,31,30,31],Pm=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Mm=/^(?=.{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,Lm=/^(?:[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,jm=/^(?:(?:[^\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,Dm=/^(?:(?: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,Um=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Fm=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Bm=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,zm=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,qm=t=>{if(t[0]==='"')return!1;const[e,r,...n]=t.split("@");return!e||!r||n.length!==0||e.length>64||r.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:r.split(".").every(a=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(a))},Gm=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Hm=/^((([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,Zm=t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t));function Ke(t){return t.test.bind(t)}const Vo={date:Cu,time:Nu.bind(void 0,!1),"date-time":Wm,duration:Zm,uri:Xm,"uri-reference":Ke(Lm),"uri-template":Ke(jm),url:Ke(Dm),email:qm,hostname:Ke(Mm),ipv4:Ke(Gm),ipv6:Ke(Hm),regex:eg,uuid:Ke(Um),"json-pointer":Ke(Fm),"json-pointer-uri-fragment":Ke(Bm),"relative-json-pointer":Ke(zm)};function Vm(t){return t%4===0&&(t%100!==0||t%400===0)}function Cu(t){const e=t.match(Cm);if(!e)return!1;const r=+e[1],n=+e[2],a=+e[3];return n>=1&&n<=12&&a>=1&&a<=(n==2&&Vm(r)?29:Nm[n])}function Nu(t,e){const r=e.match(Pm);if(!r)return!1;const n=+r[1],a=+r[2],s=+r[3],i=!!r[5];return(n<=23&&a<=59&&s<=59||n==23&&a==59&&s==60)&&(!t||i)}const Jm=/t|\s/i;function Wm(t){const e=t.split(Jm);return e.length==2&&Cu(e[0])&&Nu(!0,e[1])}const Km=/\/|:/,Ym=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Xm(t){return Km.test(t)&&Ym.test(t)}const Qm=/[^\\]\\Z/;function eg(t){if(Qm.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}function tg(t){let e=0,r=t.length,n=0,a;for(;n<r;)e++,a=t.charCodeAt(n++),a>=55296&&a<=56319&&n<r&&(a=t.charCodeAt(n),(a&64512)==56320&&n++);return e}function ce(t,e,r="2019-09",n=ht(e),a=!0,s=null,i="#",o="#",c=Object.create(null)){if(e===!0)return{valid:!0,errors:[]};if(e===!1)return{valid:!1,errors:[{instanceLocation:i,keyword:"false",keywordLocation:i,error:"False boolean schema."}]};const u=typeof t;let l;switch(u){case"boolean":case"number":case"string":l=u;break;case"object":t===null?l="null":Array.isArray(t)?l="array":l="object";break;default:throw new Error(`Instances of "${u}" type are not supported.`)}const{$ref:d,$recursiveRef:f,$recursiveAnchor:h,type:p,const:m,enum:g,required:y,not:v,anyOf:_,allOf:E,oneOf:$,if:U,then:z,else:O,format:oe,properties:ye,patternProperties:Me,additionalProperties:Ue,unevaluatedProperties:Pt,minProperties:I,maxProperties:S,propertyNames:F,dependentRequired:P,dependentSchemas:B,dependencies:M,prefixItems:H,items:Q,additionalItems:Y,unevaluatedItems:se,contains:he,minContains:ne,maxContains:Je,minItems:bn,maxItems:En,uniqueItems:Wu,minimum:vt,maximum:wt,exclusiveMinimum:Yt,exclusiveMaximum:Xt,multipleOf:$r,minLength:Cr,maxLength:Nr,pattern:Gs,__absolute_ref__:Pr,__absolute_recursive_ref__:Ku}=e,A=[];if(h===!0&&s===null&&(s=e),f==="#"){const q=s===null?n[Ku]:s,j=`${o}/$recursiveRef`,J=ce(t,s===null?e:s,r,n,a,q,i,j,c);J.valid||A.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:j,error:"A subschema had errors."},...J.errors)}if(d!==void 0){const j=n[Pr||d];if(j===void 0){let T=`Unresolved $ref "${d}".`;throw Pr&&Pr!==d&&(T+=` Absolute URI "${Pr}".`),T+=`
68
+ ]`;continue}a+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return a}function Ou(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===b.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,a)=>({...n,[a]:re(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",a]})??Ce(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const r={type:"object",additionalProperties:re(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===b.ZodString&&t.keyType._def.checks?.length){const{type:n,...a}=Ru(t.keyType._def,e);return{...r,propertyNames:a}}else{if(t.keyType?._def.typeName===b.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===b.ZodBranded&&t.keyType._def.type._def.typeName===b.ZodString&&t.keyType._def.type._def.checks?.length){const{type:n,...a}=Iu(t.keyType._def,e);return{...r,propertyNames:a}}}return r}function tm(t,e){if(e.mapStrategy==="record")return Ou(t,e);const r=re(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ce(e),n=re(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ce(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function rm(t){const e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),a=Array.from(new Set(n.map(s=>typeof s)));return{type:a.length===1?a[0]==="string"?"string":"number":["string","number"],enum:n}}function nm(t){return t.target==="openAi"?void 0:{not:Ce({...t,currentPath:[...t.currentPath,"not"]})}}function am(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const cn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function sm(t,e){if(e.target==="openApi3")return Go(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in cn&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((a,s)=>{const i=cn[s._def.typeName];return i&&!a.includes(i)?[...a,i]:a},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((a,s)=>{const i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...a,i];case"bigint":return[...a,"integer"];case"object":return s._def.value===null?[...a,"null"]:a;case"symbol":case"undefined":case"function":default:return a}},[]);if(n.length===r.length){const a=n.filter((s,i,o)=>o.indexOf(s)===i);return{type:a.length>1?a:a[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,a)=>[...n,...a._def.values.filter(s=>!n.includes(s))],[])};return Go(t,e)}const Go=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,a)=>re(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${a}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function im(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:cn[t.innerType._def.typeName],nullable:!0}:{type:[cn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=re(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=re(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function om(t,e){const r={type:"number"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"int":r.type="integer",xu(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ae(r,"minimum",n.value,n.message,e):ae(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ae(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ae(r,"maximum",n.value,n.message,e):ae(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ae(r,"maximum",n.value,n.message,e));break;case"multipleOf":ae(r,"multipleOf",n.value,n.message,e);break}return r}function cm(t,e){const r=e.target==="openAi",n={type:"object",properties:{}},a=[],s=t.shape();for(const o in s){let c=s[o];if(c===void 0||c._def===void 0)continue;let u=lm(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=re(c._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});l!==void 0&&(n.properties[o]=l,u||a.push(o))}a.length&&(n.required=a);const i=um(t,e);return i!==void 0&&(n.additionalProperties=i),n}function um(t,e){if(t.catchall._def.typeName!=="ZodNever")return re(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function lm(t){try{return t.isOptional()}catch{return!0}}const dm=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return re(t.innerType._def,e);const r=re(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ce(e)},r]}:Ce(e)},fm=(t,e)=>{if(e.pipeStrategy==="input")return re(t.in._def,e);if(e.pipeStrategy==="output")return re(t.out._def,e);const r=re(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=re(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(a=>a!==void 0)}};function hm(t,e){return re(t.type._def,e)}function pm(t,e){const n={type:"array",uniqueItems:!0,items:re(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ae(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ae(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function mm(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>re(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:re(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>re(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function gm(t){return{not:Ce(t)}}function _m(t){return Ce(t)}const ym=(t,e)=>re(t.innerType._def,e),vm=(t,e,r)=>{switch(e){case b.ZodString:return Ru(t,r);case b.ZodNumber:return om(t,r);case b.ZodObject:return cm(t,r);case b.ZodBigInt:return qp(t,r);case b.ZodBoolean:return Gp();case b.ZodDate:return Au(t,r);case b.ZodUndefined:return gm(r);case b.ZodNull:return am(r);case b.ZodArray:return zp(t,r);case b.ZodUnion:case b.ZodDiscriminatedUnion:return sm(t,r);case b.ZodIntersection:return Yp(t,r);case b.ZodTuple:return mm(t,r);case b.ZodRecord:return Ou(t,r);case b.ZodLiteral:return Xp(t,r);case b.ZodEnum:return Jp(t);case b.ZodNativeEnum:return rm(t);case b.ZodNullable:return im(t,r);case b.ZodOptional:return dm(t,r);case b.ZodMap:return tm(t,r);case b.ZodSet:return pm(t,r);case b.ZodLazy:return()=>t.getter()._def;case b.ZodPromise:return hm(t,r);case b.ZodNaN:case b.ZodNever:return nm(r);case b.ZodEffects:return Wp(t,r);case b.ZodAny:return Ce(r);case b.ZodUnknown:return _m(r);case b.ZodDefault:return Vp(t,r);case b.ZodBranded:return Iu(t,r);case b.ZodReadonly:return ym(t,r);case b.ZodCatch:return Hp(t,r);case b.ZodPipeline:return fm(t,r);case b.ZodFunction:case b.ZodVoid:case b.ZodSymbol:return;default:return(n=>{})()}};function re(t,e,r=!1){const n=e.seen.get(t);if(e.override){const o=e.override?.(t,e,n,r);if(o!==Dp)return o}if(n&&!r){const o=wm(n,e);if(o!==void 0)return o}const a={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,a);const s=vm(t,t.typeName,e),i=typeof s=="function"?re(s(),e):s;if(i&&bm(t,e,i),e.postProcess){const o=e.postProcess(i,t,e);return a.jsonSchema=i,o}return a.jsonSchema=i,i}const wm=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Tu(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Ce(e)):e.$refStrategy==="seen"?Ce(e):void 0}},bm=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),Em=(t,e)=>{const r=Bp(e);let n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((o,[c,u])=>({...o,[c]:re(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??Ce(r)}),{}):void 0;const a=typeof e=="string"?e:e?.name,s=re(t._def,r,!1)??Ce(r);r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const i=a===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,a].join("/"),[r.definitionPath]:{...n,[a]:s}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};function Ut(t,e){const r=typeof t;if(r!==typeof e)return!1;if(Array.isArray(t)){if(!Array.isArray(e))return!1;const n=t.length;if(n!==e.length)return!1;for(let a=0;a<n;a++)if(!Ut(t[a],e[a]))return!1;return!0}if(r==="object"){if(!t||!e)return t===e;const n=Object.keys(t),a=Object.keys(e);if(n.length!==a.length)return!1;for(const i of n)if(!Ut(t[i],e[i]))return!1;return!0}return t===e}function Be(t){return encodeURI(Sm(t))}function Sm(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}const Tm={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},xm={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Im={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 Am=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function ft(t,e=Object.create(null),r=Am,n=""){if(t&&typeof t=="object"&&!Array.isArray(t)){const s=t.$id||t.id;if(s){const i=new URL(s,r.href);i.hash.length>1?e[i.href]=t:(i.hash="",n===""?r=i:ft(t,e,r))}}else if(t!==!0&&t!==!1)return e;const a=r.href+(n?"#"+n:"");if(e[a]!==void 0)throw new Error(`Duplicate schema URI "${a}".`);if(e[a]=t,t===!0||t===!1)return e;if(t.__absolute_uri__===void 0&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:a}),t.$ref&&t.__absolute_ref__===void 0){const s=new URL(t.$ref,r.href);s.hash=s.hash,Object.defineProperty(t,"__absolute_ref__",{enumerable:!1,value:s.href})}if(t.$recursiveRef&&t.__absolute_recursive_ref__===void 0){const s=new URL(t.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(t,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(t.$anchor){const s=new URL("#"+t.$anchor,r.href);e[s.href]=t}for(let s in t){if(Im[s])continue;const i=`${n}/${Be(s)}`,o=t[s];if(Array.isArray(o)){if(Tm[s]){const c=o.length;for(let u=0;u<c;u++)ft(o[u],e,r,`${i}/${u}`)}}else if(xm[s])for(let c in o)ft(o[c],e,r,`${i}/${Be(c)}`);else ft(o,e,r,i)}return e}const Rm=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Om=[0,31,28,31,30,31,30,31,31,30,31,30,31],$m=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,km=/^(?=.{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,Cm=/^(?:[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,Nm=/^(?:(?:[^\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,Pm=/^(?:(?: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,Lm=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Mm=/^(?:\/(?:[^~/]|~0|~1)*)*$/,jm=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Dm=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Um=t=>{if(t[0]==='"')return!1;const[e,r,...n]=t.split("@");return!e||!r||n.length!==0||e.length>64||r.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:r.split(".").every(a=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(a))},Fm=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Bm=/^((([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,zm=t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t));function Je(t){return t.test.bind(t)}const Ho={date:$u,time:ku.bind(void 0,!1),"date-time":Hm,duration:zm,uri:Wm,"uri-reference":Je(Cm),"uri-template":Je(Nm),url:Je(Pm),email:Um,hostname:Je(km),ipv4:Je(Fm),ipv6:Je(Bm),regex:Km,uuid:Je(Lm),"json-pointer":Je(Mm),"json-pointer-uri-fragment":Je(jm),"relative-json-pointer":Je(Dm)};function qm(t){return t%4===0&&(t%100!==0||t%400===0)}function $u(t){const e=t.match(Rm);if(!e)return!1;const r=+e[1],n=+e[2],a=+e[3];return n>=1&&n<=12&&a>=1&&a<=(n==2&&qm(r)?29:Om[n])}function ku(t,e){const r=e.match($m);if(!r)return!1;const n=+r[1],a=+r[2],s=+r[3],i=!!r[5];return(n<=23&&a<=59&&s<=59||n==23&&a==59&&s==60)&&(!t||i)}const Gm=/t|\s/i;function Hm(t){const e=t.split(Gm);return e.length==2&&$u(e[0])&&ku(!0,e[1])}const Zm=/\/|:/,Vm=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Wm(t){return Zm.test(t)&&Vm.test(t)}const Jm=/[^\\]\\Z/;function Km(t){if(Jm.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}function Ym(t){let e=0,r=t.length,n=0,a;for(;n<r;)e++,a=t.charCodeAt(n++),a>=55296&&a<=56319&&n<r&&(a=t.charCodeAt(n),(a&64512)==56320&&n++);return e}function ce(t,e,r="2019-09",n=ft(e),a=!0,s=null,i="#",o="#",c=Object.create(null)){if(e===!0)return{valid:!0,errors:[]};if(e===!1)return{valid:!1,errors:[{instanceLocation:i,keyword:"false",keywordLocation:i,error:"False boolean schema."}]};const u=typeof t;let l;switch(u){case"boolean":case"number":case"string":l=u;break;case"object":t===null?l="null":Array.isArray(t)?l="array":l="object";break;default:throw new Error(`Instances of "${u}" type are not supported.`)}const{$ref:d,$recursiveRef:f,$recursiveAnchor:h,type:p,const:g,enum:m,required:_,not:w,anyOf:y,allOf:I,oneOf:C,if:B,then:z,else:R,format:oe,properties:_e,patternProperties:Ne,additionalProperties:De,unevaluatedProperties:Nt,minProperties:x,maxProperties:E,propertyNames:U,dependentRequired:P,dependentSchemas:F,dependencies:L,prefixItems:H,items:Q,additionalItems:Y,unevaluatedItems:se,contains:he,minContains:ne,maxContains:Ve,minItems:wn,maxItems:bn,uniqueItems:Vu,minimum:yt,maximum:vt,exclusiveMinimum:Kt,exclusiveMaximum:Yt,multipleOf:$r,minLength:kr,maxLength:Cr,pattern:qs,__absolute_ref__:Nr,__absolute_recursive_ref__:Wu}=e,A=[];if(h===!0&&s===null&&(s=e),f==="#"){const q=s===null?n[Wu]:s,j=`${o}/$recursiveRef`,W=ce(t,s===null?e:s,r,n,a,q,i,j,c);W.valid||A.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:j,error:"A subschema had errors."},...W.errors)}if(d!==void 0){const j=n[Nr||d];if(j===void 0){let S=`Unresolved $ref "${d}".`;throw Nr&&Nr!==d&&(S+=` Absolute URI "${Nr}".`),S+=`
71
69
  Known schemas:
72
70
  - ${Object.keys(n).join(`
73
- - `)}`,new Error(T)}const J=`${o}/$ref`,C=ce(t,j,r,n,a,s,i,J,c);if(C.valid||A.push({instanceLocation:i,keyword:"$ref",keywordLocation:J,error:"A subschema had errors."},...C.errors),r==="4"||r==="7")return{valid:A.length===0,errors:A}}if(Array.isArray(p)){let q=p.length,j=!1;for(let J=0;J<q;J++)if(l===p[J]||p[J]==="integer"&&l==="number"&&t%1===0&&t===t){j=!0;break}j||A.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${p.join('", "')}".`})}else p==="integer"?(l!=="number"||t%1||t!==t)&&A.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${p}".`}):p!==void 0&&l!==p&&A.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${p}".`});if(m!==void 0&&(l==="object"||l==="array"?Ft(t,m)||A.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(m)}.`}):t!==m&&A.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(m)}.`})),g!==void 0&&(l==="object"||l==="array"?g.some(q=>Ft(t,q))||A.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(q=>t===q)||A.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),v!==void 0){const q=`${o}/not`;ce(t,v,r,n,a,s,i,q).valid&&A.push({instanceLocation:i,keyword:"not",keywordLocation:q,error:'Instance matched "not" schema.'})}let Mr=[];if(_!==void 0){const q=`${o}/anyOf`,j=A.length;let J=!1;for(let C=0;C<_.length;C++){const T=_[C],Z=Object.create(c),G=ce(t,T,r,n,a,h===!0?s:null,i,`${q}/${C}`,Z);A.push(...G.errors),J=J||G.valid,G.valid&&Mr.push(Z)}J?A.length=j:A.splice(j,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:q,error:"Instance does not match any subschemas."})}if(E!==void 0){const q=`${o}/allOf`,j=A.length;let J=!0;for(let C=0;C<E.length;C++){const T=E[C],Z=Object.create(c),G=ce(t,T,r,n,a,h===!0?s:null,i,`${q}/${C}`,Z);A.push(...G.errors),J=J&&G.valid,G.valid&&Mr.push(Z)}J?A.length=j:A.splice(j,0,{instanceLocation:i,keyword:"allOf",keywordLocation:q,error:"Instance does not match every subschema."})}if($!==void 0){const q=`${o}/oneOf`,j=A.length,J=$.filter((C,T)=>{const Z=Object.create(c),G=ce(t,C,r,n,a,h===!0?s:null,i,`${q}/${T}`,Z);return A.push(...G.errors),G.valid&&Mr.push(Z),G.valid}).length;J===1?A.length=j:A.splice(j,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:q,error:`Instance does not match exactly one subschema (${J} matches).`})}if((l==="object"||l==="array")&&Object.assign(c,...Mr),U!==void 0){const q=`${o}/if`;if(ce(t,U,r,n,a,s,i,q,c).valid){if(z!==void 0){const J=ce(t,z,r,n,a,s,i,`${o}/then`,c);J.valid||A.push({instanceLocation:i,keyword:"if",keywordLocation:q,error:'Instance does not match "then" schema.'},...J.errors)}}else if(O!==void 0){const J=ce(t,O,r,n,a,s,i,`${o}/else`,c);J.valid||A.push({instanceLocation:i,keyword:"if",keywordLocation:q,error:'Instance does not match "else" schema.'},...J.errors)}}if(l==="object"){if(y!==void 0)for(const C of y)C in t||A.push({instanceLocation:i,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${C}".`});const q=Object.keys(t);if(I!==void 0&&q.length<I&&A.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${I} properties.`}),S!==void 0&&q.length>S&&A.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${S} properties.`}),F!==void 0){const C=`${o}/propertyNames`;for(const T in t){const Z=`${i}/${ze(T)}`,G=ce(T,F,r,n,a,s,Z,C);G.valid||A.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:C,error:`Property name "${T}" does not match schema.`},...G.errors)}}if(P!==void 0){const C=`${o}/dependantRequired`;for(const T in P)if(T in t){const Z=P[T];for(const G of Z)G in t||A.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:C,error:`Instance has "${T}" but does not have "${G}".`})}}if(B!==void 0)for(const C in B){const T=`${o}/dependentSchemas`;if(C in t){const Z=ce(t,B[C],r,n,a,s,i,`${T}/${ze(C)}`,c);Z.valid||A.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:T,error:`Instance has "${C}" but does not match dependant schema.`},...Z.errors)}}if(M!==void 0){const C=`${o}/dependencies`;for(const T in M)if(T in t){const Z=M[T];if(Array.isArray(Z))for(const G of Z)G in t||A.push({instanceLocation:i,keyword:"dependencies",keywordLocation:C,error:`Instance has "${T}" but does not have "${G}".`});else{const G=ce(t,Z,r,n,a,s,i,`${C}/${ze(T)}`);G.valid||A.push({instanceLocation:i,keyword:"dependencies",keywordLocation:C,error:`Instance has "${T}" but does not match dependant schema.`},...G.errors)}}}const j=Object.create(null);let J=!1;if(ye!==void 0){const C=`${o}/properties`;for(const T in ye){if(!(T in t))continue;const Z=`${i}/${ze(T)}`,G=ce(t[T],ye[T],r,n,a,s,Z,`${C}/${ze(T)}`);if(G.valid)c[T]=j[T]=!0;else if(J=a,A.push({instanceLocation:i,keyword:"properties",keywordLocation:C,error:`Property "${T}" does not match schema.`},...G.errors),J)break}}if(!J&&Me!==void 0){const C=`${o}/patternProperties`;for(const T in Me){const Z=new RegExp(T,"u"),G=Me[T];for(const Ae in t){if(!Z.test(Ae))continue;const Hs=`${i}/${ze(Ae)}`,Zs=ce(t[Ae],G,r,n,a,s,Hs,`${C}/${ze(T)}`);Zs.valid?c[Ae]=j[Ae]=!0:(J=a,A.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:C,error:`Property "${Ae}" matches pattern "${T}" but does not match associated schema.`},...Zs.errors))}}}if(!J&&Ue!==void 0){const C=`${o}/additionalProperties`;for(const T in t){if(j[T])continue;const Z=`${i}/${ze(T)}`,G=ce(t[T],Ue,r,n,a,s,Z,C);G.valid?c[T]=!0:(J=a,A.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:C,error:`Property "${T}" does not match additional properties schema.`},...G.errors))}}else if(!J&&Pt!==void 0){const C=`${o}/unevaluatedProperties`;for(const T in t)if(!c[T]){const Z=`${i}/${ze(T)}`,G=ce(t[T],Pt,r,n,a,s,Z,C);G.valid?c[T]=!0:A.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:C,error:`Property "${T}" does not match unevaluated properties schema.`},...G.errors)}}}else if(l==="array"){En!==void 0&&t.length>En&&A.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${t.length} > ${En}).`}),bn!==void 0&&t.length<bn&&A.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${t.length} < ${bn}).`});const q=t.length;let j=0,J=!1;if(H!==void 0){const C=`${o}/prefixItems`,T=Math.min(H.length,q);for(;j<T;j++){const Z=ce(t[j],H[j],r,n,a,s,`${i}/${j}`,`${C}/${j}`);if(c[j]=!0,!Z.valid&&(J=a,A.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:C,error:"Items did not match schema."},...Z.errors),J))break}}if(Q!==void 0){const C=`${o}/items`;if(Array.isArray(Q)){const T=Math.min(Q.length,q);for(;j<T;j++){const Z=ce(t[j],Q[j],r,n,a,s,`${i}/${j}`,`${C}/${j}`);if(c[j]=!0,!Z.valid&&(J=a,A.push({instanceLocation:i,keyword:"items",keywordLocation:C,error:"Items did not match schema."},...Z.errors),J))break}}else for(;j<q;j++){const T=ce(t[j],Q,r,n,a,s,`${i}/${j}`,C);if(c[j]=!0,!T.valid&&(J=a,A.push({instanceLocation:i,keyword:"items",keywordLocation:C,error:"Items did not match schema."},...T.errors),J))break}if(!J&&Y!==void 0){const T=`${o}/additionalItems`;for(;j<q;j++){const Z=ce(t[j],Y,r,n,a,s,`${i}/${j}`,T);c[j]=!0,Z.valid||(J=a,A.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:T,error:"Items did not match additional items schema."},...Z.errors))}}}if(he!==void 0)if(q===0&&ne===void 0)A.push({instanceLocation:i,keyword:"contains",keywordLocation:`${o}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(ne!==void 0&&q<ne)A.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array has less items (${q}) than minContains (${ne}).`});else{const C=`${o}/contains`,T=A.length;let Z=0;for(let G=0;G<q;G++){const Ae=ce(t[G],he,r,n,a,s,`${i}/${G}`,C);Ae.valid?(c[G]=!0,Z++):A.push(...Ae.errors)}Z>=(ne||0)&&(A.length=T),ne===void 0&&Je===void 0&&Z===0?A.splice(T,0,{instanceLocation:i,keyword:"contains",keywordLocation:C,error:"Array does not contain item matching schema."}):ne!==void 0&&Z<ne?A.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array must contain at least ${ne} items matching schema. Only ${Z} items were found.`}):Je!==void 0&&Z>Je&&A.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${Je} items matching schema. ${Z} items were found.`})}if(!J&&se!==void 0){const C=`${o}/unevaluatedItems`;for(j;j<q;j++){if(c[j])continue;const T=ce(t[j],se,r,n,a,s,`${i}/${j}`,C);c[j]=!0,T.valid||A.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:C,error:"Items did not match unevaluated items schema."},...T.errors)}}if(Wu)for(let C=0;C<q;C++){const T=t[C],Z=typeof T=="object"&&T!==null;for(let G=0;G<q;G++){if(C===G)continue;const Ae=t[G];(T===Ae||Z&&(typeof Ae=="object"&&Ae!==null)&&Ft(T,Ae))&&(A.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${o}/uniqueItems`,error:`Duplicate items at indexes ${C} and ${G}.`}),C=Number.MAX_SAFE_INTEGER,G=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(r==="4"?(vt!==void 0&&(Yt===!0&&t<=vt||t<vt)&&A.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${t} is less than ${Yt?"or equal to ":""} ${vt}.`}),wt!==void 0&&(Xt===!0&&t>=wt||t>wt)&&A.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${t} is greater than ${Xt?"or equal to ":""} ${wt}.`})):(vt!==void 0&&t<vt&&A.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${t} is less than ${vt}.`}),wt!==void 0&&t>wt&&A.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${t} is greater than ${wt}.`}),Yt!==void 0&&t<=Yt&&A.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${t} is less than ${Yt}.`}),Xt!==void 0&&t>=Xt&&A.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${t} is greater than or equal to ${Xt}.`})),$r!==void 0){const q=t%$r;Math.abs(0-q)>=11920929e-14&&Math.abs($r-q)>=11920929e-14&&A.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${t} is not a multiple of ${$r}.`})}}else if(l==="string"){const q=Cr===void 0&&Nr===void 0?0:tg(t);Cr!==void 0&&q<Cr&&A.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${q} < ${Cr}).`}),Nr!==void 0&&q>Nr&&A.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${q} > ${Nr}).`}),Gs!==void 0&&!new RegExp(Gs,"u").test(t)&&A.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),oe!==void 0&&Vo[oe]&&!Vo[oe](t)&&A.push({instanceLocation:i,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${oe}".`})}return{valid:A.length===0,errors:A}}class rg{schema;draft;shortCircuit;lookup;constructor(e,r="2019-09",n=!0){this.schema=e,this.draft=r,this.shortCircuit=n,this.lookup=ht(e)}validate(e){return ce(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,r){r&&(e={...e,$id:r}),ht(e,this.lookup)}}var ng={};me(ng,{Validator:()=>rg,deepCompareStrict:()=>Ft,toJsonSchema:()=>Pu,validatesOnlyStrings:()=>Vr});function Pu(t){if(fe(t)){const e=nr(t,!0);if(st(e)){const r=as(e,!0);return Js(r)}else return Js(t)}return ge(t)?Im(t):t}function Vr(t){if(!t||typeof t!="object"||Object.keys(t).length===0||Array.isArray(t))return!1;if("type"in t)return typeof t.type=="string"?t.type==="string":Array.isArray(t.type)?t.type.every(e=>e==="string"):!1;if("enum"in t)return Array.isArray(t.enum)&&t.enum.length>0&&t.enum.every(e=>typeof e=="string");if("const"in t)return typeof t.const=="string";if("allOf"in t&&Array.isArray(t.allOf))return t.allOf.some(e=>Vr(e));if("anyOf"in t&&Array.isArray(t.anyOf)||"oneOf"in t&&Array.isArray(t.oneOf)){const e="anyOf"in t?t.anyOf:t.oneOf;return e.length>0&&e.every(r=>Vr(r))}if("not"in t)return!1;if("$ref"in t&&typeof t.$ref=="string"){const e=t.$ref,r=ht(t);return r[e]?Vr(r[e]):!1}return!1}var ag={};me(ag,{Graph:()=>Bs});function sg(t,e){if(t!==void 0&&!or(t))return t;if(Us(e))try{let r=e.getName();return r=r.startsWith("Runnable")?r.slice(8):r,r}catch{return e.getName()}else return e.name??"UnknownSchema"}function ig(t){return Us(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...Pu(t.data.schema),title:t.data.name}}}var Bs=class Mu{nodes={};edges=[];constructor(e){this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach((r,n)=>{e[r.id]=or(r.id)?n:r.id}),{nodes:Object.values(this.nodes).map(r=>({id:e[r.id],...ig(r)})),edges:this.edges.map(r=>{const n={source:e[r.source],target:e[r.target]};return typeof r.data<"u"&&(n.data=r.data),typeof r.conditional<"u"&&(n.conditional=r.conditional),n})}}addNode(e,r,n){if(r!==void 0&&this.nodes[r]!==void 0)throw new Error(`Node with id ${r} already exists`);const a=r??Te(),s={id:a,data:e,name:sg(r,e),metadata:n};return this.nodes[a]=s,s}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(r=>r.source!==e.id&&r.target!==e.id)}addEdge(e,r,n,a){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[r.id]===void 0)throw new Error(`Target node ${r.id} not in graph`);const s={source:e.id,target:r.id,data:n,conditional:a};return this.edges.push(s),s}firstNode(){return Jo(this)}lastNode(){return Wo(this)}extend(e,r=""){let n=r;Object.values(e.nodes).map(u=>u.id).every(or)&&(n="");const s=u=>n?`${n}:${u}`:u;Object.entries(e.nodes).forEach(([u,l])=>{this.nodes[s(u)]={...l,id:s(u)}});const i=e.edges.map(u=>({...u,source:s(u.source),target:s(u.target)}));this.edges=[...this.edges,...i];const o=e.firstNode(),c=e.lastNode();return[o?{id:s(o.id),data:o.data}:void 0,c?{id:s(c.id),data:c.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&Jo(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&Wo(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map(a=>[a.id,a.name])),r=new Map;Object.values(e).forEach(a=>{r.set(a,(r.get(a)||0)+1)});const n=a=>{const s=e[a];return or(a)&&r.get(s)===1?s:a};return new Mu({nodes:Object.fromEntries(Object.entries(this.nodes).map(([a,s])=>[n(a),{...s,id:n(a)}])),edges:this.edges.map(a=>({...a,source:n(a.source),target:n(a.target)}))})}drawMermaid(e){const{withStyles:r,curveStyle:n,nodeColors:a={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:s}=e??{},i=this.reid(),o=i.firstNode(),c=i.lastNode();return Fp(i.nodes,i.edges,{firstNode:o?.id,lastNode:c?.id,withStyles:r,curveStyle:n,nodeColors:a,wrapLabelNWords:s})}async drawMermaidPng(e){const r=this.drawMermaid(e);return Bp(r,{backgroundColor:e?.backgroundColor})}};function Jo(t,e=[]){const r=new Set(t.edges.filter(a=>!e.includes(a.source)).map(a=>a.target)),n=[];for(const a of Object.values(t.nodes))!e.includes(a.id)&&!r.has(a.id)&&n.push(a);return n.length===1?n[0]:void 0}function Wo(t,e=[]){const r=new Set(t.edges.filter(a=>!e.includes(a.target)).map(a=>a.source)),n=[];for(const a of Object.values(t.nodes))!e.includes(a.id)&&!r.has(a.id)&&n.push(a);return n.length===1?n[0]:void 0}function og(t){const e=new TextEncoder,r=new ReadableStream({async start(n){for await(const a of t)n.enqueue(e.encode(`event: data
71
+ - `)}`,new Error(S)}const W=`${o}/$ref`,k=ce(t,j,r,n,a,s,i,W,c);if(k.valid||A.push({instanceLocation:i,keyword:"$ref",keywordLocation:W,error:"A subschema had errors."},...k.errors),r==="4"||r==="7")return{valid:A.length===0,errors:A}}if(Array.isArray(p)){let q=p.length,j=!1;for(let W=0;W<q;W++)if(l===p[W]||p[W]==="integer"&&l==="number"&&t%1===0&&t===t){j=!0;break}j||A.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${p.join('", "')}".`})}else p==="integer"?(l!=="number"||t%1||t!==t)&&A.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${p}".`}):p!==void 0&&l!==p&&A.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${p}".`});if(g!==void 0&&(l==="object"||l==="array"?Ut(t,g)||A.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(g)}.`}):t!==g&&A.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(g)}.`})),m!==void 0&&(l==="object"||l==="array"?m.some(q=>Ut(t,q))||A.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(m)}.`}):m.some(q=>t===q)||A.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(m)}.`})),w!==void 0){const q=`${o}/not`;ce(t,w,r,n,a,s,i,q).valid&&A.push({instanceLocation:i,keyword:"not",keywordLocation:q,error:'Instance matched "not" schema.'})}let Pr=[];if(y!==void 0){const q=`${o}/anyOf`,j=A.length;let W=!1;for(let k=0;k<y.length;k++){const S=y[k],Z=Object.create(c),G=ce(t,S,r,n,a,h===!0?s:null,i,`${q}/${k}`,Z);A.push(...G.errors),W=W||G.valid,G.valid&&Pr.push(Z)}W?A.length=j:A.splice(j,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:q,error:"Instance does not match any subschemas."})}if(I!==void 0){const q=`${o}/allOf`,j=A.length;let W=!0;for(let k=0;k<I.length;k++){const S=I[k],Z=Object.create(c),G=ce(t,S,r,n,a,h===!0?s:null,i,`${q}/${k}`,Z);A.push(...G.errors),W=W&&G.valid,G.valid&&Pr.push(Z)}W?A.length=j:A.splice(j,0,{instanceLocation:i,keyword:"allOf",keywordLocation:q,error:"Instance does not match every subschema."})}if(C!==void 0){const q=`${o}/oneOf`,j=A.length,W=C.filter((k,S)=>{const Z=Object.create(c),G=ce(t,k,r,n,a,h===!0?s:null,i,`${q}/${S}`,Z);return A.push(...G.errors),G.valid&&Pr.push(Z),G.valid}).length;W===1?A.length=j:A.splice(j,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:q,error:`Instance does not match exactly one subschema (${W} matches).`})}if((l==="object"||l==="array")&&Object.assign(c,...Pr),B!==void 0){const q=`${o}/if`;if(ce(t,B,r,n,a,s,i,q,c).valid){if(z!==void 0){const W=ce(t,z,r,n,a,s,i,`${o}/then`,c);W.valid||A.push({instanceLocation:i,keyword:"if",keywordLocation:q,error:'Instance does not match "then" schema.'},...W.errors)}}else if(R!==void 0){const W=ce(t,R,r,n,a,s,i,`${o}/else`,c);W.valid||A.push({instanceLocation:i,keyword:"if",keywordLocation:q,error:'Instance does not match "else" schema.'},...W.errors)}}if(l==="object"){if(_!==void 0)for(const k of _)k in t||A.push({instanceLocation:i,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${k}".`});const q=Object.keys(t);if(x!==void 0&&q.length<x&&A.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${x} properties.`}),E!==void 0&&q.length>E&&A.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${E} properties.`}),U!==void 0){const k=`${o}/propertyNames`;for(const S in t){const Z=`${i}/${Be(S)}`,G=ce(S,U,r,n,a,s,Z,k);G.valid||A.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:k,error:`Property name "${S}" does not match schema.`},...G.errors)}}if(P!==void 0){const k=`${o}/dependantRequired`;for(const S in P)if(S in t){const Z=P[S];for(const G of Z)G in t||A.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:k,error:`Instance has "${S}" but does not have "${G}".`})}}if(F!==void 0)for(const k in F){const S=`${o}/dependentSchemas`;if(k in t){const Z=ce(t,F[k],r,n,a,s,i,`${S}/${Be(k)}`,c);Z.valid||A.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:S,error:`Instance has "${k}" but does not match dependant schema.`},...Z.errors)}}if(L!==void 0){const k=`${o}/dependencies`;for(const S in L)if(S in t){const Z=L[S];if(Array.isArray(Z))for(const G of Z)G in t||A.push({instanceLocation:i,keyword:"dependencies",keywordLocation:k,error:`Instance has "${S}" but does not have "${G}".`});else{const G=ce(t,Z,r,n,a,s,i,`${k}/${Be(S)}`);G.valid||A.push({instanceLocation:i,keyword:"dependencies",keywordLocation:k,error:`Instance has "${S}" but does not match dependant schema.`},...G.errors)}}}const j=Object.create(null);let W=!1;if(_e!==void 0){const k=`${o}/properties`;for(const S in _e){if(!(S in t))continue;const Z=`${i}/${Be(S)}`,G=ce(t[S],_e[S],r,n,a,s,Z,`${k}/${Be(S)}`);if(G.valid)c[S]=j[S]=!0;else if(W=a,A.push({instanceLocation:i,keyword:"properties",keywordLocation:k,error:`Property "${S}" does not match schema.`},...G.errors),W)break}}if(!W&&Ne!==void 0){const k=`${o}/patternProperties`;for(const S in Ne){const Z=new RegExp(S,"u"),G=Ne[S];for(const Ie in t){if(!Z.test(Ie))continue;const Gs=`${i}/${Be(Ie)}`,Hs=ce(t[Ie],G,r,n,a,s,Gs,`${k}/${Be(S)}`);Hs.valid?c[Ie]=j[Ie]=!0:(W=a,A.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:k,error:`Property "${Ie}" matches pattern "${S}" but does not match associated schema.`},...Hs.errors))}}}if(!W&&De!==void 0){const k=`${o}/additionalProperties`;for(const S in t){if(j[S])continue;const Z=`${i}/${Be(S)}`,G=ce(t[S],De,r,n,a,s,Z,k);G.valid?c[S]=!0:(W=a,A.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:k,error:`Property "${S}" does not match additional properties schema.`},...G.errors))}}else if(!W&&Nt!==void 0){const k=`${o}/unevaluatedProperties`;for(const S in t)if(!c[S]){const Z=`${i}/${Be(S)}`,G=ce(t[S],Nt,r,n,a,s,Z,k);G.valid?c[S]=!0:A.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:k,error:`Property "${S}" does not match unevaluated properties schema.`},...G.errors)}}}else if(l==="array"){bn!==void 0&&t.length>bn&&A.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${t.length} > ${bn}).`}),wn!==void 0&&t.length<wn&&A.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${t.length} < ${wn}).`});const q=t.length;let j=0,W=!1;if(H!==void 0){const k=`${o}/prefixItems`,S=Math.min(H.length,q);for(;j<S;j++){const Z=ce(t[j],H[j],r,n,a,s,`${i}/${j}`,`${k}/${j}`);if(c[j]=!0,!Z.valid&&(W=a,A.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:k,error:"Items did not match schema."},...Z.errors),W))break}}if(Q!==void 0){const k=`${o}/items`;if(Array.isArray(Q)){const S=Math.min(Q.length,q);for(;j<S;j++){const Z=ce(t[j],Q[j],r,n,a,s,`${i}/${j}`,`${k}/${j}`);if(c[j]=!0,!Z.valid&&(W=a,A.push({instanceLocation:i,keyword:"items",keywordLocation:k,error:"Items did not match schema."},...Z.errors),W))break}}else for(;j<q;j++){const S=ce(t[j],Q,r,n,a,s,`${i}/${j}`,k);if(c[j]=!0,!S.valid&&(W=a,A.push({instanceLocation:i,keyword:"items",keywordLocation:k,error:"Items did not match schema."},...S.errors),W))break}if(!W&&Y!==void 0){const S=`${o}/additionalItems`;for(;j<q;j++){const Z=ce(t[j],Y,r,n,a,s,`${i}/${j}`,S);c[j]=!0,Z.valid||(W=a,A.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:S,error:"Items did not match additional items schema."},...Z.errors))}}}if(he!==void 0)if(q===0&&ne===void 0)A.push({instanceLocation:i,keyword:"contains",keywordLocation:`${o}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(ne!==void 0&&q<ne)A.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array has less items (${q}) than minContains (${ne}).`});else{const k=`${o}/contains`,S=A.length;let Z=0;for(let G=0;G<q;G++){const Ie=ce(t[G],he,r,n,a,s,`${i}/${G}`,k);Ie.valid?(c[G]=!0,Z++):A.push(...Ie.errors)}Z>=(ne||0)&&(A.length=S),ne===void 0&&Ve===void 0&&Z===0?A.splice(S,0,{instanceLocation:i,keyword:"contains",keywordLocation:k,error:"Array does not contain item matching schema."}):ne!==void 0&&Z<ne?A.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array must contain at least ${ne} items matching schema. Only ${Z} items were found.`}):Ve!==void 0&&Z>Ve&&A.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${Ve} items matching schema. ${Z} items were found.`})}if(!W&&se!==void 0){const k=`${o}/unevaluatedItems`;for(j;j<q;j++){if(c[j])continue;const S=ce(t[j],se,r,n,a,s,`${i}/${j}`,k);c[j]=!0,S.valid||A.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:k,error:"Items did not match unevaluated items schema."},...S.errors)}}if(Vu)for(let k=0;k<q;k++){const S=t[k],Z=typeof S=="object"&&S!==null;for(let G=0;G<q;G++){if(k===G)continue;const Ie=t[G];(S===Ie||Z&&(typeof Ie=="object"&&Ie!==null)&&Ut(S,Ie))&&(A.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${o}/uniqueItems`,error:`Duplicate items at indexes ${k} and ${G}.`}),k=Number.MAX_SAFE_INTEGER,G=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(r==="4"?(yt!==void 0&&(Kt===!0&&t<=yt||t<yt)&&A.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${t} is less than ${Kt?"or equal to ":""} ${yt}.`}),vt!==void 0&&(Yt===!0&&t>=vt||t>vt)&&A.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${t} is greater than ${Yt?"or equal to ":""} ${vt}.`})):(yt!==void 0&&t<yt&&A.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${t} is less than ${yt}.`}),vt!==void 0&&t>vt&&A.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${t} is greater than ${vt}.`}),Kt!==void 0&&t<=Kt&&A.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${t} is less than ${Kt}.`}),Yt!==void 0&&t>=Yt&&A.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${t} is greater than or equal to ${Yt}.`})),$r!==void 0){const q=t%$r;Math.abs(0-q)>=11920929e-14&&Math.abs($r-q)>=11920929e-14&&A.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${t} is not a multiple of ${$r}.`})}}else if(l==="string"){const q=kr===void 0&&Cr===void 0?0:Ym(t);kr!==void 0&&q<kr&&A.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${q} < ${kr}).`}),Cr!==void 0&&q>Cr&&A.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${q} > ${Cr}).`}),qs!==void 0&&!new RegExp(qs,"u").test(t)&&A.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),oe!==void 0&&Ho[oe]&&!Ho[oe](t)&&A.push({instanceLocation:i,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${oe}".`})}return{valid:A.length===0,errors:A}}class Xm{schema;draft;shortCircuit;lookup;constructor(e,r="2019-09",n=!0){this.schema=e,this.draft=r,this.shortCircuit=n,this.lookup=ft(e)}validate(e){return ce(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,r){r&&(e={...e,$id:r}),ft(e,this.lookup)}}var Qm={};me(Qm,{Validator:()=>Xm,deepCompareStrict:()=>Ut,toJsonSchema:()=>Cu,validatesOnlyStrings:()=>Zr});function Cu(t){if(fe(t)){const e=rr(t,!0);if(at(e)){const r=ns(e,!0);return Zs(r)}else return Zs(t)}return ge(t)?Em(t):t}function Zr(t){if(!t||typeof t!="object"||Object.keys(t).length===0||Array.isArray(t))return!1;if("type"in t)return typeof t.type=="string"?t.type==="string":Array.isArray(t.type)?t.type.every(e=>e==="string"):!1;if("enum"in t)return Array.isArray(t.enum)&&t.enum.length>0&&t.enum.every(e=>typeof e=="string");if("const"in t)return typeof t.const=="string";if("allOf"in t&&Array.isArray(t.allOf))return t.allOf.some(e=>Zr(e));if("anyOf"in t&&Array.isArray(t.anyOf)||"oneOf"in t&&Array.isArray(t.oneOf)){const e="anyOf"in t?t.anyOf:t.oneOf;return e.length>0&&e.every(r=>Zr(r))}if("not"in t)return!1;if("$ref"in t&&typeof t.$ref=="string"){const e=t.$ref,r=ft(t);return r[e]?Zr(r[e]):!1}return!1}var eg={};me(eg,{Graph:()=>Fs});function tg(t,e){if(t!==void 0&&!ir(t))return t;if(Ds(e))try{let r=e.getName();return r=r.startsWith("Runnable")?r.slice(8):r,r}catch{return e.getName()}else return e.name??"UnknownSchema"}function rg(t){return Ds(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...Cu(t.data.schema),title:t.data.name}}}var Fs=class Nu{nodes={};edges=[];constructor(e){this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach((r,n)=>{e[r.id]=ir(r.id)?n:r.id}),{nodes:Object.values(this.nodes).map(r=>({id:e[r.id],...rg(r)})),edges:this.edges.map(r=>{const n={source:e[r.source],target:e[r.target]};return typeof r.data<"u"&&(n.data=r.data),typeof r.conditional<"u"&&(n.conditional=r.conditional),n})}}addNode(e,r,n){if(r!==void 0&&this.nodes[r]!==void 0)throw new Error(`Node with id ${r} already exists`);const a=r??Se(),s={id:a,data:e,name:tg(r,e),metadata:n};return this.nodes[a]=s,s}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(r=>r.source!==e.id&&r.target!==e.id)}addEdge(e,r,n,a){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[r.id]===void 0)throw new Error(`Target node ${r.id} not in graph`);const s={source:e.id,target:r.id,data:n,conditional:a};return this.edges.push(s),s}firstNode(){return Zo(this)}lastNode(){return Vo(this)}extend(e,r=""){let n=r;Object.values(e.nodes).map(u=>u.id).every(ir)&&(n="");const s=u=>n?`${n}:${u}`:u;Object.entries(e.nodes).forEach(([u,l])=>{this.nodes[s(u)]={...l,id:s(u)}});const i=e.edges.map(u=>({...u,source:s(u.source),target:s(u.target)}));this.edges=[...this.edges,...i];const o=e.firstNode(),c=e.lastNode();return[o?{id:s(o.id),data:o.data}:void 0,c?{id:s(c.id),data:c.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&Zo(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&Vo(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map(a=>[a.id,a.name])),r=new Map;Object.values(e).forEach(a=>{r.set(a,(r.get(a)||0)+1)});const n=a=>{const s=e[a];return ir(a)&&r.get(s)===1?s:a};return new Nu({nodes:Object.fromEntries(Object.entries(this.nodes).map(([a,s])=>[n(a),{...s,id:n(a)}])),edges:this.edges.map(a=>({...a,source:n(a.source),target:n(a.target)}))})}drawMermaid(e){const{withStyles:r,curveStyle:n,nodeColors:a={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:s}=e??{},i=this.reid(),o=i.firstNode(),c=i.lastNode();return Mp(i.nodes,i.edges,{firstNode:o?.id,lastNode:c?.id,withStyles:r,curveStyle:n,nodeColors:a,wrapLabelNWords:s})}async drawMermaidPng(e){const r=this.drawMermaid(e);return jp(r,{backgroundColor:e?.backgroundColor})}};function Zo(t,e=[]){const r=new Set(t.edges.filter(a=>!e.includes(a.source)).map(a=>a.target)),n=[];for(const a of Object.values(t.nodes))!e.includes(a.id)&&!r.has(a.id)&&n.push(a);return n.length===1?n[0]:void 0}function Vo(t,e=[]){const r=new Set(t.edges.filter(a=>!e.includes(a.target)).map(a=>a.source)),n=[];for(const a of Object.values(t.nodes))!e.includes(a.id)&&!r.has(a.id)&&n.push(a);return n.length===1?n[0]:void 0}function ng(t){const e=new TextEncoder,r=new ReadableStream({async start(n){for await(const a of t)n.enqueue(e.encode(`event: data
74
72
  data: ${JSON.stringify(a)}
75
73
 
76
74
  `));n.enqueue(e.encode(`event: end
77
75
 
78
- `)),n.close()}});return He.fromReadableStream(r)}function Ko(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}const cg=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function";function ss(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*Yo(t,e){for(;;){const{value:r,done:n}=ut.runWithConfig(Zt(t),e.next.bind(e),!0);if(n)break;yield r}}async function*is(t,e){const r=e[Symbol.asyncIterator]();for(;;){const{value:n,done:a}=await ut.runWithConfig(Zt(t),r.next.bind(e),!0);if(a)break;yield n}}function pe(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}var Ce=class extends hr{lc_runnable=!0;name;getName(t){const e=this.name??this.constructor.lc_name()??this.constructor.name;return t?`${e}${t}`:e}withRetry(t){return new Du({bound:this,kwargs:{},config:{},maxAttemptNumber:t?.stopAfterAttempt,...t})}withConfig(t){return new ln({bound:this,config:t,kwargs:{}})}withFallbacks(t){const e=Array.isArray(t)?t:t.fallbacks;return new dg({runnable:this,fallbacks:e})}_getOptionsList(t,e=0){if(Array.isArray(t)&&t.length!==e)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${t.length} options for ${e} inputs`);if(Array.isArray(t))return t.map(ie);if(e>1&&!Array.isArray(t)&&t.runId){console.warn("Provided runId will be used only for the first element of the batch.");const r=Object.fromEntries(Object.entries(t).filter(([n])=>n!=="runId"));return Array.from({length:e},(n,a)=>ie(a===0?t:r))}return Array.from({length:e},()=>ie(t))}async batch(t,e,r){const n=this._getOptionsList(e??{},t.length),a=n[0]?.maxConcurrency??r?.maxConcurrency,s=new Eu({maxConcurrency:a,onFailedAttempt:o=>{throw o}}),i=t.map((o,c)=>s.call(async()=>{try{return await this.invoke(o,n[c])}catch(u){if(r?.returnExceptions)return u;throw u}}));return Promise.all(i)}async*_streamIterator(t,e){yield this.invoke(t,e)}async stream(t,e){const r=ie(e),n=new Nt({generator:this._streamIterator(t,r),config:r});return await n.setup,He.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(t){let e;t===void 0?e=ie(t):e=ie({callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,runName:t.runName,configurable:t.configurable,recursionLimit:t.recursionLimit,maxConcurrency:t.maxConcurrency,runId:t.runId,timeout:t.timeout,signal:t.signal});const r={...t};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[e,r]}async _callWithConfig(t,e,r){const n=ie(r),s=await(await Ge(n))?.handleChainStart(this.toJSON(),pe(e,"input"),n.runId,n?.runType,void 0,void 0,n?.runName??this.getName());delete n.runId;let i;try{const o=t.call(this,e,n,s);i=await gt(o,r?.signal)}catch(o){throw await s?.handleChainError(o),o}return await s?.handleChainEnd(pe(i,"output")),i}async _batchWithConfig(t,e,r,n){const a=this._getOptionsList(r??{},e.length),s=await Promise.all(a.map(Ge)),i=await Promise.all(s.map(async(c,u)=>{const l=await c?.handleChainStart(this.toJSON(),pe(e[u],"input"),a[u].runId,a[u].runType,void 0,void 0,a[u].runName??this.getName());return delete a[u].runId,l}));let o;try{const c=t.call(this,e,a,i,n);o=await gt(c,a?.[0]?.signal)}catch(c){throw await Promise.all(i.map(u=>u?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(pe(o,"output")))),o}_concatOutputChunks(t,e){return js(t,e)}async*_transformStreamWithConfig(t,e,r){let n,a=!0,s,i=!0;const o=ie(r),c=await Ge(o),u=this;async function*l(){for await(const f of t){if(a)if(n===void 0)n=f;else try{n=u._concatOutputChunks(n,f)}catch{n=void 0,a=!1}yield f}}let d;try{const f=await gu(e.bind(this),l(),async()=>c?.handleChainStart(this.toJSON(),{input:""},o.runId,o.runType,void 0,void 0,o.runName??this.getName()),r?.signal,o);delete o.runId,d=f.setup;const h=d?.handlers.find(xp);let p=f.output;h!==void 0&&d!==void 0&&(p=h.tapOutputIterable(d.runId,p));const m=d?.handlers.find(vu);m!==void 0&&d!==void 0&&(p=m.tapOutputIterable(d.runId,p));for await(const g of p)if(yield g,i)if(s===void 0)s=g;else try{s=this._concatOutputChunks(s,g)}catch{s=void 0,i=!1}}catch(f){throw await d?.handleChainError(f,void 0,void 0,void 0,{inputs:pe(n,"input")}),f}await d?.handleChainEnd(s??{},void 0,void 0,void 0,{inputs:pe(n,"input")})}getGraph(t){const e=new Bs,r=e.addNode({name:`${this.getName()}Input`,schema:oi()}),n=e.addNode(this),a=e.addNode({name:`${this.getName()}Output`,schema:oi()});return e.addEdge(r,n),e.addEdge(n,a),e}pipe(t){return new Uu({first:this,last:bt(t)})}pick(t){return this.pipe(new hg(t))}assign(t){return this.pipe(new fg(new wn({steps:t})))}async*transform(t,e){let r;for await(const n of t)r===void 0?r=n:r=this._concatOutputChunks(r,n);yield*this._streamIterator(r,ie(e))}async*streamLog(t,e,r){const n=new ns({...r,autoClose:!1,_schemaFormat:"original"}),a=ie(e);yield*this._streamLog(t,n,a)}async*_streamLog(t,e,r){const{callbacks:n}=r;if(n===void 0)r.callbacks=[e];else if(Array.isArray(n))r.callbacks=n.concat([e]);else{const o=n.copy();o.addHandler(e,!0),r.callbacks=o}const a=this.stream(t,r);async function s(){try{const o=await a;for await(const c of o){const u=new rt({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await e.writer.write(u)}}finally{await e.writer.close()}}const i=s();try{for await(const o of e)yield o}finally{await i}}streamEvents(t,e,r){let n;if(e.version==="v1")n=this._streamEventsV1(t,e,r);else if(e.version==="v2")n=this._streamEventsV2(t,e,r);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return e.encoding==="text/event-stream"?og(n):He.fromAsyncGenerator(n)}async*_streamEventsV2(t,e,r){const n=new Ip({...r,autoClose:!1}),a=ie(e),s=a.runId??Te();a.runId=s;const i=a.callbacks;if(i===void 0)a.callbacks=[n];else if(Array.isArray(i))a.callbacks=i.concat(n);else{const h=i.copy();h.addHandler(n,!0),a.callbacks=h}const o=new AbortController,c=this;async function u(){let h,p=null;try{e?.signal?"any"in AbortSignal?h=AbortSignal.any([o.signal,e.signal]):(h=e.signal,p=()=>{o.abort()},e.signal.addEventListener("abort",p,{once:!0})):h=o.signal;const m=await c.stream(t,{...a,signal:h}),g=n.tapOutputIterable(s,m);for await(const y of g)if(o.signal.aborted)break}finally{await n.finish(),h&&p&&h.removeEventListener("abort",p)}}const l=u();let d=!1,f;try{for await(const h of n){if(!d){h.data.input=t,d=!0,f=h.run_id,yield h;continue}h.run_id===f&&h.event.endsWith("_end")&&h.data?.input&&delete h.data.input,yield h}}finally{o.abort(),await l}}async*_streamEventsV1(t,e,r){let n,a=!1;const s=ie(e),i=s.tags??[],o=s.metadata??{},c=s.runName??this.getName(),u=new ns({...r,autoClose:!1,_schemaFormat:"streaming_events"}),l=new kp({...r}),d=this._streamLog(t,u,s);for await(const h of d){if(n?n=n.concat(h):n=Ds.fromRunLogPatch(h),n.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!a){a=!0;const y={...n.state},v={run_id:y.id,event:`on_${y.type}_start`,name:c,tags:i,metadata:o,data:{input:t}};l.includeEvent(v,y.type)&&(yield v)}const p=h.ops.filter(y=>y.path.startsWith("/logs/")).map(y=>y.path.split("/")[2]),m=[...new Set(p)];for(const y of m){let v,_={};const E=n.state.logs[y];if(E.end_time===void 0?E.streamed_output.length>0?v="stream":v="start":v="end",v==="start")E.inputs!==void 0&&(_.input=E.inputs);else if(v==="end")E.inputs!==void 0&&(_.input=E.inputs),_.output=E.final_output;else if(v==="stream"){const $=E.streamed_output.length;if($!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${$} instead. Encountered in: "${E.name}"`);_={chunk:E.streamed_output[0]},E.streamed_output=[]}yield{event:`on_${E.type}_${v}`,name:E.name,run_id:E.id,tags:E.tags,metadata:E.metadata,data:_}}const{state:g}=n;if(g.streamed_output.length>0){const y=g.streamed_output.length;if(y!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${y} instead. Encountered in: "${g.name}"`);const v={chunk:g.streamed_output[0]};g.streamed_output=[];const _={event:`on_${g.type}_stream`,run_id:g.id,tags:i,metadata:o,name:c,data:v};l.includeEvent(_,g.type)&&(yield _)}}const f=n?.state;if(f!==void 0){const h={event:`on_${f.type}_end`,name:c,run_id:f.id,tags:i,metadata:o,data:{output:f.final_output}};l.includeEvent(h,f.type)&&(yield h)}}static isRunnable(t){return Us(t)}withListeners({onStart:t,onEnd:e,onError:r}){return new ln({bound:this,config:{},configFactories:[n=>({callbacks:[new Su({config:n,onStart:t,onEnd:e,onError:r})]})]})}asTool(t){return pg(this,t)}},ln=class Lu extends Ce{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(e){super(e),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){const r=Uo(this.config,...e);return Uo(r,...this.configFactories?await Promise.all(this.configFactories.map(async n=>await n(r))):[])}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new Du({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,r){return this.bound.invoke(e,await this._mergeConfig(r,this.kwargs))}async batch(e,r,n){const a=Array.isArray(r)?await Promise.all(r.map(async s=>this._mergeConfig(ie(s),this.kwargs))):await this._mergeConfig(ie(r),this.kwargs);return this.bound.batch(e,a,n)}_concatOutputChunks(e,r){return this.bound._concatOutputChunks(e,r)}async*_streamIterator(e,r){yield*this.bound._streamIterator(e,await this._mergeConfig(ie(r),this.kwargs))}async stream(e,r){return this.bound.stream(e,await this._mergeConfig(ie(r),this.kwargs))}async*transform(e,r){yield*this.bound.transform(e,await this._mergeConfig(ie(r),this.kwargs))}streamEvents(e,r,n){const a=this,s=async function*(){yield*a.bound.streamEvents(e,{...await a._mergeConfig(ie(r),a.kwargs),version:r.version},n)};return He.fromAsyncGenerator(s())}static isRunnableBinding(e){return e.bound&&Ce.isRunnable(e.bound)}withListeners({onStart:e,onEnd:r,onError:n}){return new Lu({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[a=>({callbacks:[new Su({config:a,onStart:e,onEnd:r,onError:n})]})]})}},Wg=class ju extends Ce{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(e){super(e),this.bound=e.bound}async invoke(e,r){return this._callWithConfig(this._invoke.bind(this),e,r)}async _invoke(e,r,n){return this.bound.batch(e,we(r,{callbacks:n?.getChild()}))}withListeners({onStart:e,onEnd:r,onError:n}){return new ju({bound:this.bound.withListeners({onStart:e,onEnd:r,onError:n})})}},Du=class extends ln{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(t){super(t),this.maxAttemptNumber=t.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=t.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(t,e,r){const n=t>1?`retry:attempt:${t}`:void 0;return we(e,{callbacks:r?.getChild(n)})}async _invoke(t,e,r){return tn(n=>super.invoke(t,this._patchConfigForRetry(n,e,r)),{onFailedAttempt:n=>this.onFailedAttempt(n,t),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(t,e){return this._callWithConfig(this._invoke.bind(this),t,e)}async _batch(t,e,r,n){const a={};try{await tn(async s=>{const i=t.map((d,f)=>f).filter(d=>a[d.toString()]===void 0||a[d.toString()]instanceof Error),o=i.map(d=>t[d]),c=i.map(d=>this._patchConfigForRetry(s,e?.[d],r?.[d])),u=await super.batch(o,c,{...n,returnExceptions:!0});let l;for(let d=0;d<u.length;d+=1){const f=u[d],h=i[d];f instanceof Error&&l===void 0&&(l=f,l.input=o[d]),a[h.toString()]=f}if(l)throw l;return u},{onFailedAttempt:s=>this.onFailedAttempt(s,s.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(s){if(n?.returnExceptions!==!0)throw s}return Object.keys(a).sort((s,i)=>parseInt(s,10)-parseInt(i,10)).map(s=>a[parseInt(s,10)])}async batch(t,e,r){return this._batchWithConfig(this._batch.bind(this),t,e,r)}},Uu=class ar extends Ce{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(e){super(e),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,r){const n=ie(r),s=await(await Ge(n))?.handleChainStart(this.toJSON(),pe(e,"input"),n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let i=e,o;try{const c=[this.first,...this.middle];for(let u=0;u<c.length;u+=1){const d=c[u].invoke(i,we(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${u+1}`)}));i=await gt(d,r?.signal)}if(r?.signal?.aborted)throw an(r.signal);o=await this.last.invoke(i,we(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(c){throw await s?.handleChainError(c),c}return await s?.handleChainEnd(pe(o,"output")),o}async batch(e,r,n){const a=this._getOptionsList(r??{},e.length),s=await Promise.all(a.map(Ge)),i=await Promise.all(s.map(async(c,u)=>{const l=await c?.handleChainStart(this.toJSON(),pe(e[u],"input"),a[u].runId,void 0,void 0,void 0,a[u].runName);return delete a[u].runId,l}));let o=e;try{for(let c=0;c<this.steps.length;c+=1){const l=this.steps[c].batch(o,i.map((d,f)=>{const h=d?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return we(a[f],{callbacks:h})}),n);o=await gt(l,a[0]?.signal)}}catch(c){throw await Promise.all(i.map(u=>u?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(pe(o,"output")))),o}_concatOutputChunks(e,r){return this.last._concatOutputChunks(e,r)}async*_streamIterator(e,r){const n=await Ge(r),{runId:a,...s}=r??{},i=await n?.handleChainStart(this.toJSON(),pe(e,"input"),a,void 0,void 0,void 0,s?.runName),o=[this.first,...this.middle,this.last];let c=!0,u;async function*l(){yield e}try{let d=o[0].transform(l(),we(s,{callbacks:i?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let f=1;f<o.length;f+=1)d=await o[f].transform(d,we(s,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${f+1}`)}));for await(const f of d)if(r?.signal?.throwIfAborted(),yield f,c)if(u===void 0)u=f;else try{u=this._concatOutputChunks(u,f)}catch{u=void 0,c=!1}}catch(d){throw await i?.handleChainError(d),d}await i?.handleChainEnd(pe(u,"output"))}getGraph(e){const r=new Bs;let n=null;return this.steps.forEach((a,s)=>{const i=a.getGraph(e);s!==0&&i.trimFirstNode(),s!==this.steps.length-1&&i.trimLastNode(),r.extend(i);const o=i.firstNode();if(!o)throw new Error(`Runnable ${a} has no first node`);n&&r.addEdge(n,o),n=i.lastNode()}),r}pipe(e){return ar.isRunnableSequence(e)?new ar({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new ar({first:this.first,middle:[...this.middle,this.last],last:bt(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&Ce.isRunnable(e)}static from([e,...r],n){let a={};return typeof n=="string"?a.name=n:n!==void 0&&(a=n),new ar({...a,first:bt(e),middle:r.slice(0,-1).map(bt),last:bt(r[r.length-1])})}},wn=class Fu extends Ce{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),this.steps={};for(const[r,n]of Object.entries(e.steps))this.steps[r]=bt(n)}static from(e){return new Fu({steps:e})}async invoke(e,r){const n=ie(r),s=await(await Ge(n))?.handleChainStart(this.toJSON(),{input:e},n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;const i={};try{const o=Object.entries(this.steps).map(async([c,u])=>{i[c]=await u.invoke(e,we(n,{callbacks:s?.getChild(`map:key:${c}`)}))});await gt(Promise.all(o),r?.signal)}catch(o){throw await s?.handleChainError(o),o}return await s?.handleChainEnd(i),i}async*_transform(e,r,n){const a={...this.steps},s=Ls(e,Object.keys(a).length),i=new Map(Object.entries(a).map(([o,c],u)=>{const l=c.transform(s[u],we(n,{callbacks:r?.getChild(`map:key:${o}`)}));return[o,l.next().then(d=>({key:o,gen:l,result:d}))]}));for(;i.size;){const o=Promise.race(i.values()),{key:c,result:u,gen:l}=await gt(o,n?.signal);i.delete(c),u.done||(yield{[c]:u.value},i.set(c,l.next().then(d=>({key:c,gen:l,result:d}))))}}transform(e,r){return this._transformStreamWithConfig(e,this._transform.bind(this),r)}async stream(e,r){async function*n(){yield e}const a=ie(r),s=new Nt({generator:this.transform(n(),a),config:a});return await s.setup,He.fromAsyncGenerator(s)}},ug=class Bu extends Ce{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(e){if(super(e),!Ms(e.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,r){const[n]=this._getOptionsList(r??{},1),a=await Ge(n),s=this.func(we(n,{callbacks:a}),e);return gt(s,n?.signal)}async*_streamIterator(e,r){const[n]=this._getOptionsList(r??{},1),a=await this.invoke(e,r);if(ss(a)){for await(const s of a)n?.signal?.throwIfAborted(),yield s;return}if(cg(a)){for(;;){n?.signal?.throwIfAborted();const s=a.next();if(s.done)break;yield s.value}return}yield a}static from(e){return new Bu({func:e})}};function lg(t){if(Ms(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var kr=class zu extends Ce{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(e){if(Ms(e.func))return ug.from(e.func);super(e),lg(e.func),this.func=e.func}static from(e){return new zu({func:e})}async _invoke(e,r,n){return new Promise((a,s)=>{const i=we(r,{callbacks:n?.getChild(),recursionLimit:(r?.recursionLimit??Pa)-1});ut.runWithConfig(Zt(i),async()=>{try{let o=await this.func(e,{...i});if(o&&Ce.isRunnable(o)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(e,{...i,recursionLimit:(i.recursionLimit??Pa)-1})}else if(ss(o)){let c;for await(const u of is(i,o))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}o=c}else if(Ko(o)){let c;for(const u of Yo(i,o))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}o=c}a(o)}catch(o){s(o)}})})}async invoke(e,r){return this._callWithConfig(this._invoke.bind(this),e,r)}async*_transform(e,r,n){let a;for await(const o of e)if(a===void 0)a=o;else try{a=this._concatOutputChunks(a,o)}catch{a=o}const s=we(n,{callbacks:r?.getChild(),recursionLimit:(n?.recursionLimit??Pa)-1}),i=await new Promise((o,c)=>{ut.runWithConfig(Zt(s),async()=>{try{const u=await this.func(a,{...s,config:s});o(u)}catch(u){c(u)}})});if(i&&Ce.isRunnable(i)){if(n?.recursionLimit===0)throw new Error("Recursion limit reached.");const o=await i.stream(a,s);for await(const c of o)yield c}else if(ss(i))for await(const o of is(s,i))n?.signal?.throwIfAborted(),yield o;else if(Ko(i))for(const o of Yo(s,i))n?.signal?.throwIfAborted(),yield o;else yield i}transform(e,r){return this._transformStreamWithConfig(e,this._transform.bind(this),r)}async stream(e,r){async function*n(){yield e}const a=ie(r),s=new Nt({generator:this.transform(n(),a),config:a});return await s.setup,He.fromAsyncGenerator(s)}},Kg=class extends wn{},dg=class extends Ce{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(t){super(t),this.runnable=t.runnable,this.fallbacks=t.fallbacks}*runnables(){yield this.runnable;for(const t of this.fallbacks)yield t}async invoke(t,e){const r=ie(e),n=await Ge(r),{runId:a,...s}=r,i=await n?.handleChainStart(this.toJSON(),pe(t,"input"),a,void 0,void 0,void 0,s?.runName),o=we(s,{callbacks:i?.getChild()});return await ut.runWithConfig(o,async()=>{let u;for(const l of this.runnables()){r?.signal?.throwIfAborted();try{const d=await l.invoke(t,o);return await i?.handleChainEnd(pe(d,"output")),d}catch(d){u===void 0&&(u=d)}}throw u===void 0?new Error("No error stored at end of fallback."):(await i?.handleChainError(u),u)})}async*_streamIterator(t,e){const r=ie(e),n=await Ge(r),{runId:a,...s}=r,i=await n?.handleChainStart(this.toJSON(),pe(t,"input"),a,void 0,void 0,void 0,s?.runName);let o,c;for(const l of this.runnables()){r?.signal?.throwIfAborted();const d=we(s,{callbacks:i?.getChild()});try{const f=await l.stream(t,d);c=is(d,f);break}catch(f){o===void 0&&(o=f)}}if(c===void 0){const l=o??new Error("No error stored at end of fallback.");throw await i?.handleChainError(l),l}let u;try{for await(const l of c){yield l;try{u=u===void 0?u:this._concatOutputChunks(u,l)}catch{u=void 0}}}catch(l){throw await i?.handleChainError(l),l}await i?.handleChainEnd(pe(u,"output"))}async batch(t,e,r){if(r?.returnExceptions)throw new Error("Not implemented.");const n=this._getOptionsList(e??{},t.length),a=await Promise.all(n.map(o=>Ge(o))),s=await Promise.all(a.map(async(o,c)=>{const u=await o?.handleChainStart(this.toJSON(),pe(t[c],"input"),n[c].runId,void 0,void 0,void 0,n[c].runName);return delete n[c].runId,u}));let i;for(const o of this.runnables()){n[0].signal?.throwIfAborted();try{const c=await o.batch(t,s.map((u,l)=>we(n[l],{callbacks:u?.getChild()})),r);return await Promise.all(s.map((u,l)=>u?.handleChainEnd(pe(c[l],"output")))),c}catch(c){i===void 0&&(i=c)}}throw i?(await Promise.all(s.map(o=>o?.handleChainError(i))),i):new Error("No error stored at end of fallbacks.")}};function bt(t){if(typeof t=="function")return new kr({func:t});if(Ce.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){const e={};for(const[r,n]of Object.entries(t))e[r]=bt(n);return new wn({steps:e})}else throw new Error(`Expected a Runnable, function or object.
79
- Instead got an unsupported type.`)}var fg=class extends Ce{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(t){t instanceof wn&&(t={mapper:t}),super(t),this.mapper=t.mapper}async invoke(t,e){const r=await this.mapper.invoke(t,e);return{...t,...r}}async*_transform(t,e,r){const n=this.mapper.getStepsKeys(),[a,s]=Ls(t),i=this.mapper.transform(s,we(r,{callbacks:e?.getChild()})),o=i.next();for await(const c of a){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);const u=Object.fromEntries(Object.entries(c).filter(([l])=>!n.includes(l)));Object.keys(u).length>0&&(yield u)}yield(await o).value;for await(const c of i)yield c}transform(t,e){return this._transformStreamWithConfig(t,this._transform.bind(this),e)}async stream(t,e){async function*r(){yield t}const n=ie(e),a=new Nt({generator:this.transform(r(),n),config:n});return await a.setup,He.fromAsyncGenerator(a)}},hg=class extends Ce{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(t){(typeof t=="string"||Array.isArray(t))&&(t={keys:t}),super(t),this.keys=t.keys}async _pick(t){if(typeof this.keys=="string")return t[this.keys];{const e=this.keys.map(r=>[r,t[r]]).filter(r=>r[1]!==void 0);return e.length===0?void 0:Object.fromEntries(e)}}async invoke(t,e){return this._callWithConfig(this._pick.bind(this),t,e)}async*_transform(t){for await(const e of t){const r=await this._pick(e);r!==void 0&&(yield r)}}transform(t,e){return this._transformStreamWithConfig(t,this._transform.bind(this),e)}async stream(t,e){async function*r(){yield t}const n=ie(e),a=new Nt({generator:this.transform(r(),n),config:n});return await a.setup,He.fromAsyncGenerator(a)}},Xo=class extends ln{name;description;schema;constructor(t){const e=Uu.from([kr.from(async r=>{let n;if(kc(r))try{n=await Np(this.schema,r.args)}catch{throw new md("Received tool input did not match expected schema",JSON.stringify(r.args))}else n=r;return n}).withConfig({runName:`${t.name}:parse_input`}),t.bound]).withConfig({runName:t.name});super({bound:e,config:t.config??{}}),this.name=t.name,this.description=t.description,this.schema=t.schema}static lc_name(){return"RunnableToolLike"}};function pg(t,e){const r=e.name??t.getName(),n=e.description??Pp(e.schema);return Mp(e.schema)?new Xo({name:r,description:n,schema:$l({input:kl()}).transform(a=>a.input),bound:t}):new Xo({name:r,description:n,schema:e.schema,bound:t})}const dn=(t,e)=>{const r=[...new Set(e?.map(a=>{if(typeof a=="string")return a;const s=new a({});if(!("getType"in s)||typeof s.getType!="function")throw new Error("Invalid type provided.");return s.getType()}))],n=t.getType();return r.some(a=>a===n)};function qu(t,e){return Array.isArray(t)?Qo(t,e):kr.from(r=>Qo(r,t))}function Qo(t,e={}){const{includeNames:r,excludeNames:n,includeTypes:a,excludeTypes:s,includeIds:i,excludeIds:o}=e,c=[];for(const u of t)if(!(n&&u.name&&n.includes(u.name))){{if(s&&dn(u,s))continue;if(o&&u.id&&o.includes(u.id))continue}a||i||r?(r&&u.name&&r.some(l=>l===u.name)||a&&dn(u,a)||i&&u.id&&i.some(l=>l===u.id))&&c.push(u):c.push(u)}return c}function Gu(t){return Array.isArray(t)?ec(t):kr.from(ec)}function ec(t){if(!t.length)return[];const e=[];for(const r of t){const n=r,a=e.pop();if(!a)e.push(n);else if(n.getType()==="tool"||n.getType()!==a.getType())e.push(a,n);else{const s=en(a),i=en(n),o=s.concat(i);typeof s.content=="string"&&typeof i.content=="string"&&(o.content=`${s.content}
80
- ${i.content}`),e.push(gg(o))}}return e}function Hu(t,e){if(Array.isArray(t)){const r=t;if(!e)throw new Error("Options parameter is required when providing messages.");return tc(r,e)}else{const r=t;return kr.from(n=>tc(n,r)).withConfig({runName:"trim_messages"})}}async function tc(t,e){const{maxTokens:r,tokenCounter:n,strategy:a="last",allowPartial:s=!1,endOn:i,startOn:o,includeSystem:c=!1,textSplitter:u}=e;if(o&&a==="first")throw new Error("`startOn` should only be specified if `strategy` is 'last'.");if(c&&a==="first")throw new Error("`includeSystem` should only be specified if `strategy` is 'last'.");let l;"getNumTokens"in n?l=async f=>(await Promise.all(f.map(p=>n.getNumTokens(p.content)))).reduce((p,m)=>p+m,0):l=async f=>n(f);let d=qs;if(u&&("splitText"in u?d=u.splitText:d=async f=>u(f)),a==="first")return Zu(t,{maxTokens:r,tokenCounter:l,textSplitter:d,partialStrategy:s?"first":void 0,endOn:i});if(a==="last")return mg(t,{maxTokens:r,tokenCounter:l,textSplitter:d,allowPartial:s,includeSystem:c,startOn:o,endOn:i});throw new Error(`Unrecognized strategy: '${a}'. Must be one of 'first' or 'last'.`)}async function Zu(t,e){const{maxTokens:r,tokenCounter:n,textSplitter:a,partialStrategy:s,endOn:i}=e;let o=[...t],c=0;for(let u=0;u<o.length;u+=1){const l=u>0?o.slice(0,-u):o;if(await n(l)<=r){c=o.length-u;break}}if(c<o.length&&s){let u=!1;if(Array.isArray(o[c].content)){const l=o[c];if(typeof l.content=="string")throw new Error("Expected content to be an array.");const d=l.content.length,f=s==="last"?[...l.content].reverse():l.content;for(let h=1;h<=d;h+=1){const p=s==="first"?f.slice(0,h):f.slice(-h),m=Object.fromEntries(Object.entries(l).filter(([v])=>v!=="type"&&!v.startsWith("lc_"))),g=zs(l.getType(),{...m,content:p}),y=[...o.slice(0,c),g];if(await n(y)<=r)o=y,c+=1,u=!0;else break}u&&s==="last"&&(l.content=[...f].reverse())}if(!u){const l=o[c];let d;if(Array.isArray(l.content)&&l.content.some(f=>typeof f=="string"||f.type==="text")?d=l.content.find(h=>h.type==="text"&&h.text)?.text:typeof l.content=="string"&&(d=l.content),d){const f=await a(d),h=f.length;s==="last"&&f.reverse();for(let p=0;p<h-1;p+=1)if(f.pop(),l.content=f.join(""),await n([...o.slice(0,c),l])<=r){s==="last"&&(l.content=[...f].reverse().join("")),o=[...o.slice(0,c),l],c+=1;break}}}}if(i){const u=Array.isArray(i)?i:[i];for(;c>0&&!dn(o[c-1],u);)c-=1}return o.slice(0,c)}async function mg(t,e){const{allowPartial:r=!1,includeSystem:n=!1,endOn:a,startOn:s,...i}=e;let o=t.map(l=>{const d=Object.fromEntries(Object.entries(l).filter(([f])=>f!=="type"&&!f.startsWith("lc_")));return zs(l.getType(),d,vs(l))});if(a){const l=Array.isArray(a)?a:[a];for(;o.length>0&&!dn(o[o.length-1],l);)o=o.slice(0,-1)}const c=n&&o[0]?.getType()==="system";let u=c?o.slice(0,1).concat(o.slice(1).reverse()):o.reverse();return u=await Zu(u,{...i,partialStrategy:r?"last":void 0,endOn:s}),c?[u[0],...u.slice(1).reverse()]:u.reverse()}const rc={human:{message:$t,messageChunk:Ir},ai:{message:It,messageChunk:kt},system:{message:ct,messageChunk:At},developer:{message:ct,messageChunk:At},tool:{message:Rt,messageChunk:Er},function:{message:Tr,messageChunk:xr},generic:{message:Jt,messageChunk:Sr},remove:{message:mr,messageChunk:mr}};function zs(t,e,r){let n,a;switch(t){case"human":r?n=new Ir(e):a=new $t(e);break;case"ai":if(r){let s={...e};"tool_calls"in s&&(s={...s,tool_call_chunks:s.tool_calls?.map(i=>({...i,type:"tool_call_chunk",index:void 0,args:JSON.stringify(i.args)}))}),n=new kt(s)}else a=new It(e);break;case"system":r?n=new At(e):a=new ct(e);break;case"developer":r?n=new At({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}}):a=new ct({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in e)r?n=new Er(e):a=new Rt(e);else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if(r)n=new xr(e);else{if(!e.name)throw new Error("FunctionMessage must have a 'name' field");a=new Tr(e)}break;case"generic":if("role"in e)r?n=new Sr(e):a=new Jt(e);else throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");break;default:throw new Error(`Unrecognized message type ${t}`)}if(r&&n)return n;if(a)return a;throw new Error(`Unrecognized message type ${t}`)}function gg(t){const e=t.getType();let r;const n=Object.fromEntries(Object.entries(t).filter(([a])=>!["type","tool_call_chunks"].includes(a)&&!a.startsWith("lc_")));if(e in rc&&(r=zs(e,n)),!r)throw new Error(`Unrecognized message chunk class ${e}. Supported classes are ${Object.keys(rc)}`);return r}function qs(t){const e=t.split(`
76
+ `)),n.close()}});return Ge.fromReadableStream(r)}function Wo(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}const ag=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function";function as(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*Jo(t,e){for(;;){const{value:r,done:n}=ct.runWithConfig(Ht(t),e.next.bind(e),!0);if(n)break;yield r}}async function*ss(t,e){const r=e[Symbol.asyncIterator]();for(;;){const{value:n,done:a}=await ct.runWithConfig(Ht(t),r.next.bind(e),!0);if(a)break;yield n}}function pe(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}var $e=class extends fr{lc_runnable=!0;name;getName(t){const e=this.name??this.constructor.lc_name()??this.constructor.name;return t?`${e}${t}`:e}withRetry(t){return new Mu({bound:this,kwargs:{},config:{},maxAttemptNumber:t?.stopAfterAttempt,...t})}withConfig(t){return new un({bound:this,config:t,kwargs:{}})}withFallbacks(t){const e=Array.isArray(t)?t:t.fallbacks;return new og({runnable:this,fallbacks:e})}_getOptionsList(t,e=0){if(Array.isArray(t)&&t.length!==e)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${t.length} options for ${e} inputs`);if(Array.isArray(t))return t.map(ie);if(e>1&&!Array.isArray(t)&&t.runId){console.warn("Provided runId will be used only for the first element of the batch.");const r=Object.fromEntries(Object.entries(t).filter(([n])=>n!=="runId"));return Array.from({length:e},(n,a)=>ie(a===0?t:r))}return Array.from({length:e},()=>ie(t))}async batch(t,e,r){const n=this._getOptionsList(e??{},t.length),a=n[0]?.maxConcurrency??r?.maxConcurrency,s=new wu({maxConcurrency:a,onFailedAttempt:o=>{throw o}}),i=t.map((o,c)=>s.call(async()=>{try{return await this.invoke(o,n[c])}catch(u){if(r?.returnExceptions)return u;throw u}}));return Promise.all(i)}async*_streamIterator(t,e){yield this.invoke(t,e)}async stream(t,e){const r=ie(e),n=new Ct({generator:this._streamIterator(t,r),config:r});return await n.setup,Ge.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(t){let e;t===void 0?e=ie(t):e=ie({callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,runName:t.runName,configurable:t.configurable,recursionLimit:t.recursionLimit,maxConcurrency:t.maxConcurrency,runId:t.runId,timeout:t.timeout,signal:t.signal});const r={...t};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[e,r]}async _callWithConfig(t,e,r){const n=ie(r),s=await(await qe(n))?.handleChainStart(this.toJSON(),pe(e,"input"),n.runId,n?.runType,void 0,void 0,n?.runName??this.getName());delete n.runId;let i;try{const o=t.call(this,e,n,s);i=await mt(o,r?.signal)}catch(o){throw await s?.handleChainError(o),o}return await s?.handleChainEnd(pe(i,"output")),i}async _batchWithConfig(t,e,r,n){const a=this._getOptionsList(r??{},e.length),s=await Promise.all(a.map(qe)),i=await Promise.all(s.map(async(c,u)=>{const l=await c?.handleChainStart(this.toJSON(),pe(e[u],"input"),a[u].runId,a[u].runType,void 0,void 0,a[u].runName??this.getName());return delete a[u].runId,l}));let o;try{const c=t.call(this,e,a,i,n);o=await mt(c,a?.[0]?.signal)}catch(c){throw await Promise.all(i.map(u=>u?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(pe(o,"output")))),o}_concatOutputChunks(t,e){return Ms(t,e)}async*_transformStreamWithConfig(t,e,r){let n,a=!0,s,i=!0;const o=ie(r),c=await qe(o),u=this;async function*l(){for await(const f of t){if(a)if(n===void 0)n=f;else try{n=u._concatOutputChunks(n,f)}catch{n=void 0,a=!1}yield f}}let d;try{const f=await pu(e.bind(this),l(),async()=>c?.handleChainStart(this.toJSON(),{input:""},o.runId,o.runType,void 0,void 0,o.runName??this.getName()),r?.signal,o);delete o.runId,d=f.setup;const h=d?.handlers.find(bp);let p=f.output;h!==void 0&&d!==void 0&&(p=h.tapOutputIterable(d.runId,p));const g=d?.handlers.find(_u);g!==void 0&&d!==void 0&&(p=g.tapOutputIterable(d.runId,p));for await(const m of p)if(yield m,i)if(s===void 0)s=m;else try{s=this._concatOutputChunks(s,m)}catch{s=void 0,i=!1}}catch(f){throw await d?.handleChainError(f,void 0,void 0,void 0,{inputs:pe(n,"input")}),f}await d?.handleChainEnd(s??{},void 0,void 0,void 0,{inputs:pe(n,"input")})}getGraph(t){const e=new Fs,r=e.addNode({name:`${this.getName()}Input`,schema:si()}),n=e.addNode(this),a=e.addNode({name:`${this.getName()}Output`,schema:si()});return e.addEdge(r,n),e.addEdge(n,a),e}pipe(t){return new ju({first:this,last:wt(t)})}pick(t){return this.pipe(new ug(t))}assign(t){return this.pipe(new cg(new vn({steps:t})))}async*transform(t,e){let r;for await(const n of t)r===void 0?r=n:r=this._concatOutputChunks(r,n);yield*this._streamIterator(r,ie(e))}async*streamLog(t,e,r){const n=new rs({...r,autoClose:!1,_schemaFormat:"original"}),a=ie(e);yield*this._streamLog(t,n,a)}async*_streamLog(t,e,r){const{callbacks:n}=r;if(n===void 0)r.callbacks=[e];else if(Array.isArray(n))r.callbacks=n.concat([e]);else{const o=n.copy();o.addHandler(e,!0),r.callbacks=o}const a=this.stream(t,r);async function s(){try{const o=await a;for await(const c of o){const u=new tt({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await e.writer.write(u)}}finally{await e.writer.close()}}const i=s();try{for await(const o of e)yield o}finally{await i}}streamEvents(t,e,r){let n;if(e.version==="v1")n=this._streamEventsV1(t,e,r);else if(e.version==="v2")n=this._streamEventsV2(t,e,r);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return e.encoding==="text/event-stream"?ng(n):Ge.fromAsyncGenerator(n)}async*_streamEventsV2(t,e,r){const n=new Ep({...r,autoClose:!1}),a=ie(e),s=a.runId??Se();a.runId=s;const i=a.callbacks;if(i===void 0)a.callbacks=[n];else if(Array.isArray(i))a.callbacks=i.concat(n);else{const h=i.copy();h.addHandler(n,!0),a.callbacks=h}const o=new AbortController,c=this;async function u(){let h,p=null;try{e?.signal?"any"in AbortSignal?h=AbortSignal.any([o.signal,e.signal]):(h=e.signal,p=()=>{o.abort()},e.signal.addEventListener("abort",p,{once:!0})):h=o.signal;const g=await c.stream(t,{...a,signal:h}),m=n.tapOutputIterable(s,g);for await(const _ of m)if(o.signal.aborted)break}finally{await n.finish(),h&&p&&h.removeEventListener("abort",p)}}const l=u();let d=!1,f;try{for await(const h of n){if(!d){h.data.input=t,d=!0,f=h.run_id,yield h;continue}h.run_id===f&&h.event.endsWith("_end")&&h.data?.input&&delete h.data.input,yield h}}finally{o.abort(),await l}}async*_streamEventsV1(t,e,r){let n,a=!1;const s=ie(e),i=s.tags??[],o=s.metadata??{},c=s.runName??this.getName(),u=new rs({...r,autoClose:!1,_schemaFormat:"streaming_events"}),l=new Ip({...r}),d=this._streamLog(t,u,s);for await(const h of d){if(n?n=n.concat(h):n=js.fromRunLogPatch(h),n.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!a){a=!0;const _={...n.state},w={run_id:_.id,event:`on_${_.type}_start`,name:c,tags:i,metadata:o,data:{input:t}};l.includeEvent(w,_.type)&&(yield w)}const p=h.ops.filter(_=>_.path.startsWith("/logs/")).map(_=>_.path.split("/")[2]),g=[...new Set(p)];for(const _ of g){let w,y={};const I=n.state.logs[_];if(I.end_time===void 0?I.streamed_output.length>0?w="stream":w="start":w="end",w==="start")I.inputs!==void 0&&(y.input=I.inputs);else if(w==="end")I.inputs!==void 0&&(y.input=I.inputs),y.output=I.final_output;else if(w==="stream"){const C=I.streamed_output.length;if(C!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${C} instead. Encountered in: "${I.name}"`);y={chunk:I.streamed_output[0]},I.streamed_output=[]}yield{event:`on_${I.type}_${w}`,name:I.name,run_id:I.id,tags:I.tags,metadata:I.metadata,data:y}}const{state:m}=n;if(m.streamed_output.length>0){const _=m.streamed_output.length;if(_!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${_} instead. Encountered in: "${m.name}"`);const w={chunk:m.streamed_output[0]};m.streamed_output=[];const y={event:`on_${m.type}_stream`,run_id:m.id,tags:i,metadata:o,name:c,data:w};l.includeEvent(y,m.type)&&(yield y)}}const f=n?.state;if(f!==void 0){const h={event:`on_${f.type}_end`,name:c,run_id:f.id,tags:i,metadata:o,data:{output:f.final_output}};l.includeEvent(h,f.type)&&(yield h)}}static isRunnable(t){return Ds(t)}withListeners({onStart:t,onEnd:e,onError:r}){return new un({bound:this,config:{},configFactories:[n=>({callbacks:[new bu({config:n,onStart:t,onEnd:e,onError:r})]})]})}asTool(t){return lg(this,t)}},un=class Pu extends $e{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(e){super(e),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){const r=jo(this.config,...e);return jo(r,...this.configFactories?await Promise.all(this.configFactories.map(async n=>await n(r))):[])}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new Mu({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,r){return this.bound.invoke(e,await this._mergeConfig(r,this.kwargs))}async batch(e,r,n){const a=Array.isArray(r)?await Promise.all(r.map(async s=>this._mergeConfig(ie(s),this.kwargs))):await this._mergeConfig(ie(r),this.kwargs);return this.bound.batch(e,a,n)}_concatOutputChunks(e,r){return this.bound._concatOutputChunks(e,r)}async*_streamIterator(e,r){yield*this.bound._streamIterator(e,await this._mergeConfig(ie(r),this.kwargs))}async stream(e,r){return this.bound.stream(e,await this._mergeConfig(ie(r),this.kwargs))}async*transform(e,r){yield*this.bound.transform(e,await this._mergeConfig(ie(r),this.kwargs))}streamEvents(e,r,n){const a=this,s=async function*(){yield*a.bound.streamEvents(e,{...await a._mergeConfig(ie(r),a.kwargs),version:r.version},n)};return Ge.fromAsyncGenerator(s())}static isRunnableBinding(e){return e.bound&&$e.isRunnable(e.bound)}withListeners({onStart:e,onEnd:r,onError:n}){return new Pu({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[a=>({callbacks:[new bu({config:a,onStart:e,onEnd:r,onError:n})]})]})}},Hg=class Lu extends $e{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(e){super(e),this.bound=e.bound}async invoke(e,r){return this._callWithConfig(this._invoke.bind(this),e,r)}async _invoke(e,r,n){return this.bound.batch(e,we(r,{callbacks:n?.getChild()}))}withListeners({onStart:e,onEnd:r,onError:n}){return new Lu({bound:this.bound.withListeners({onStart:e,onEnd:r,onError:n})})}},Mu=class extends un{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(t){super(t),this.maxAttemptNumber=t.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=t.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(t,e,r){const n=t>1?`retry:attempt:${t}`:void 0;return we(e,{callbacks:r?.getChild(n)})}async _invoke(t,e,r){return en(n=>super.invoke(t,this._patchConfigForRetry(n,e,r)),{onFailedAttempt:n=>this.onFailedAttempt(n,t),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(t,e){return this._callWithConfig(this._invoke.bind(this),t,e)}async _batch(t,e,r,n){const a={};try{await en(async s=>{const i=t.map((d,f)=>f).filter(d=>a[d.toString()]===void 0||a[d.toString()]instanceof Error),o=i.map(d=>t[d]),c=i.map(d=>this._patchConfigForRetry(s,e?.[d],r?.[d])),u=await super.batch(o,c,{...n,returnExceptions:!0});let l;for(let d=0;d<u.length;d+=1){const f=u[d],h=i[d];f instanceof Error&&l===void 0&&(l=f,l.input=o[d]),a[h.toString()]=f}if(l)throw l;return u},{onFailedAttempt:s=>this.onFailedAttempt(s,s.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(s){if(n?.returnExceptions!==!0)throw s}return Object.keys(a).sort((s,i)=>parseInt(s,10)-parseInt(i,10)).map(s=>a[parseInt(s,10)])}async batch(t,e,r){return this._batchWithConfig(this._batch.bind(this),t,e,r)}},ju=class nr extends $e{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(e){super(e),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,r){const n=ie(r),s=await(await qe(n))?.handleChainStart(this.toJSON(),pe(e,"input"),n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let i=e,o;try{const c=[this.first,...this.middle];for(let u=0;u<c.length;u+=1){const d=c[u].invoke(i,we(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${u+1}`)}));i=await mt(d,r?.signal)}if(r?.signal?.aborted)throw nn(r.signal);o=await this.last.invoke(i,we(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(c){throw await s?.handleChainError(c),c}return await s?.handleChainEnd(pe(o,"output")),o}async batch(e,r,n){const a=this._getOptionsList(r??{},e.length),s=await Promise.all(a.map(qe)),i=await Promise.all(s.map(async(c,u)=>{const l=await c?.handleChainStart(this.toJSON(),pe(e[u],"input"),a[u].runId,void 0,void 0,void 0,a[u].runName);return delete a[u].runId,l}));let o=e;try{for(let c=0;c<this.steps.length;c+=1){const l=this.steps[c].batch(o,i.map((d,f)=>{const h=d?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return we(a[f],{callbacks:h})}),n);o=await mt(l,a[0]?.signal)}}catch(c){throw await Promise.all(i.map(u=>u?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(pe(o,"output")))),o}_concatOutputChunks(e,r){return this.last._concatOutputChunks(e,r)}async*_streamIterator(e,r){const n=await qe(r),{runId:a,...s}=r??{},i=await n?.handleChainStart(this.toJSON(),pe(e,"input"),a,void 0,void 0,void 0,s?.runName),o=[this.first,...this.middle,this.last];let c=!0,u;async function*l(){yield e}try{let d=o[0].transform(l(),we(s,{callbacks:i?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let f=1;f<o.length;f+=1)d=await o[f].transform(d,we(s,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${f+1}`)}));for await(const f of d)if(r?.signal?.throwIfAborted(),yield f,c)if(u===void 0)u=f;else try{u=this._concatOutputChunks(u,f)}catch{u=void 0,c=!1}}catch(d){throw await i?.handleChainError(d),d}await i?.handleChainEnd(pe(u,"output"))}getGraph(e){const r=new Fs;let n=null;return this.steps.forEach((a,s)=>{const i=a.getGraph(e);s!==0&&i.trimFirstNode(),s!==this.steps.length-1&&i.trimLastNode(),r.extend(i);const o=i.firstNode();if(!o)throw new Error(`Runnable ${a} has no first node`);n&&r.addEdge(n,o),n=i.lastNode()}),r}pipe(e){return nr.isRunnableSequence(e)?new nr({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new nr({first:this.first,middle:[...this.middle,this.last],last:wt(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&$e.isRunnable(e)}static from([e,...r],n){let a={};return typeof n=="string"?a.name=n:n!==void 0&&(a=n),new nr({...a,first:wt(e),middle:r.slice(0,-1).map(wt),last:wt(r[r.length-1])})}},vn=class Du extends $e{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),this.steps={};for(const[r,n]of Object.entries(e.steps))this.steps[r]=wt(n)}static from(e){return new Du({steps:e})}async invoke(e,r){const n=ie(r),s=await(await qe(n))?.handleChainStart(this.toJSON(),{input:e},n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;const i={};try{const o=Object.entries(this.steps).map(async([c,u])=>{i[c]=await u.invoke(e,we(n,{callbacks:s?.getChild(`map:key:${c}`)}))});await mt(Promise.all(o),r?.signal)}catch(o){throw await s?.handleChainError(o),o}return await s?.handleChainEnd(i),i}async*_transform(e,r,n){const a={...this.steps},s=Ls(e,Object.keys(a).length),i=new Map(Object.entries(a).map(([o,c],u)=>{const l=c.transform(s[u],we(n,{callbacks:r?.getChild(`map:key:${o}`)}));return[o,l.next().then(d=>({key:o,gen:l,result:d}))]}));for(;i.size;){const o=Promise.race(i.values()),{key:c,result:u,gen:l}=await mt(o,n?.signal);i.delete(c),u.done||(yield{[c]:u.value},i.set(c,l.next().then(d=>({key:c,gen:l,result:d}))))}}transform(e,r){return this._transformStreamWithConfig(e,this._transform.bind(this),r)}async stream(e,r){async function*n(){yield e}const a=ie(r),s=new Ct({generator:this.transform(n(),a),config:a});return await s.setup,Ge.fromAsyncGenerator(s)}},sg=class Uu extends $e{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(e){if(super(e),!Ps(e.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,r){const[n]=this._getOptionsList(r??{},1),a=await qe(n),s=this.func(we(n,{callbacks:a}),e);return mt(s,n?.signal)}async*_streamIterator(e,r){const[n]=this._getOptionsList(r??{},1),a=await this.invoke(e,r);if(as(a)){for await(const s of a)n?.signal?.throwIfAborted(),yield s;return}if(ag(a)){for(;;){n?.signal?.throwIfAborted();const s=a.next();if(s.done)break;yield s.value}return}yield a}static from(e){return new Uu({func:e})}};function ig(t){if(Ps(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var Or=class Fu extends $e{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(e){if(Ps(e.func))return sg.from(e.func);super(e),ig(e.func),this.func=e.func}static from(e){return new Fu({func:e})}async _invoke(e,r,n){return new Promise((a,s)=>{const i=we(r,{callbacks:n?.getChild(),recursionLimit:(r?.recursionLimit??Na)-1});ct.runWithConfig(Ht(i),async()=>{try{let o=await this.func(e,{...i});if(o&&$e.isRunnable(o)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(e,{...i,recursionLimit:(i.recursionLimit??Na)-1})}else if(as(o)){let c;for await(const u of ss(i,o))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}o=c}else if(Wo(o)){let c;for(const u of Jo(i,o))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}o=c}a(o)}catch(o){s(o)}})})}async invoke(e,r){return this._callWithConfig(this._invoke.bind(this),e,r)}async*_transform(e,r,n){let a;for await(const o of e)if(a===void 0)a=o;else try{a=this._concatOutputChunks(a,o)}catch{a=o}const s=we(n,{callbacks:r?.getChild(),recursionLimit:(n?.recursionLimit??Na)-1}),i=await new Promise((o,c)=>{ct.runWithConfig(Ht(s),async()=>{try{const u=await this.func(a,{...s,config:s});o(u)}catch(u){c(u)}})});if(i&&$e.isRunnable(i)){if(n?.recursionLimit===0)throw new Error("Recursion limit reached.");const o=await i.stream(a,s);for await(const c of o)yield c}else if(as(i))for await(const o of ss(s,i))n?.signal?.throwIfAborted(),yield o;else if(Wo(i))for(const o of Jo(s,i))n?.signal?.throwIfAborted(),yield o;else yield i}transform(e,r){return this._transformStreamWithConfig(e,this._transform.bind(this),r)}async stream(e,r){async function*n(){yield e}const a=ie(r),s=new Ct({generator:this.transform(n(),a),config:a});return await s.setup,Ge.fromAsyncGenerator(s)}},Zg=class extends vn{},og=class extends $e{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(t){super(t),this.runnable=t.runnable,this.fallbacks=t.fallbacks}*runnables(){yield this.runnable;for(const t of this.fallbacks)yield t}async invoke(t,e){const r=ie(e),n=await qe(r),{runId:a,...s}=r,i=await n?.handleChainStart(this.toJSON(),pe(t,"input"),a,void 0,void 0,void 0,s?.runName),o=we(s,{callbacks:i?.getChild()});return await ct.runWithConfig(o,async()=>{let u;for(const l of this.runnables()){r?.signal?.throwIfAborted();try{const d=await l.invoke(t,o);return await i?.handleChainEnd(pe(d,"output")),d}catch(d){u===void 0&&(u=d)}}throw u===void 0?new Error("No error stored at end of fallback."):(await i?.handleChainError(u),u)})}async*_streamIterator(t,e){const r=ie(e),n=await qe(r),{runId:a,...s}=r,i=await n?.handleChainStart(this.toJSON(),pe(t,"input"),a,void 0,void 0,void 0,s?.runName);let o,c;for(const l of this.runnables()){r?.signal?.throwIfAborted();const d=we(s,{callbacks:i?.getChild()});try{const f=await l.stream(t,d);c=ss(d,f);break}catch(f){o===void 0&&(o=f)}}if(c===void 0){const l=o??new Error("No error stored at end of fallback.");throw await i?.handleChainError(l),l}let u;try{for await(const l of c){yield l;try{u=u===void 0?u:this._concatOutputChunks(u,l)}catch{u=void 0}}}catch(l){throw await i?.handleChainError(l),l}await i?.handleChainEnd(pe(u,"output"))}async batch(t,e,r){if(r?.returnExceptions)throw new Error("Not implemented.");const n=this._getOptionsList(e??{},t.length),a=await Promise.all(n.map(o=>qe(o))),s=await Promise.all(a.map(async(o,c)=>{const u=await o?.handleChainStart(this.toJSON(),pe(t[c],"input"),n[c].runId,void 0,void 0,void 0,n[c].runName);return delete n[c].runId,u}));let i;for(const o of this.runnables()){n[0].signal?.throwIfAborted();try{const c=await o.batch(t,s.map((u,l)=>we(n[l],{callbacks:u?.getChild()})),r);return await Promise.all(s.map((u,l)=>u?.handleChainEnd(pe(c[l],"output")))),c}catch(c){i===void 0&&(i=c)}}throw i?(await Promise.all(s.map(o=>o?.handleChainError(i))),i):new Error("No error stored at end of fallbacks.")}};function wt(t){if(typeof t=="function")return new Or({func:t});if($e.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){const e={};for(const[r,n]of Object.entries(t))e[r]=wt(n);return new vn({steps:e})}else throw new Error(`Expected a Runnable, function or object.
77
+ Instead got an unsupported type.`)}var cg=class extends $e{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(t){t instanceof vn&&(t={mapper:t}),super(t),this.mapper=t.mapper}async invoke(t,e){const r=await this.mapper.invoke(t,e);return{...t,...r}}async*_transform(t,e,r){const n=this.mapper.getStepsKeys(),[a,s]=Ls(t),i=this.mapper.transform(s,we(r,{callbacks:e?.getChild()})),o=i.next();for await(const c of a){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);const u=Object.fromEntries(Object.entries(c).filter(([l])=>!n.includes(l)));Object.keys(u).length>0&&(yield u)}yield(await o).value;for await(const c of i)yield c}transform(t,e){return this._transformStreamWithConfig(t,this._transform.bind(this),e)}async stream(t,e){async function*r(){yield t}const n=ie(e),a=new Ct({generator:this.transform(r(),n),config:n});return await a.setup,Ge.fromAsyncGenerator(a)}},ug=class extends $e{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(t){(typeof t=="string"||Array.isArray(t))&&(t={keys:t}),super(t),this.keys=t.keys}async _pick(t){if(typeof this.keys=="string")return t[this.keys];{const e=this.keys.map(r=>[r,t[r]]).filter(r=>r[1]!==void 0);return e.length===0?void 0:Object.fromEntries(e)}}async invoke(t,e){return this._callWithConfig(this._pick.bind(this),t,e)}async*_transform(t){for await(const e of t){const r=await this._pick(e);r!==void 0&&(yield r)}}transform(t,e){return this._transformStreamWithConfig(t,this._transform.bind(this),e)}async stream(t,e){async function*r(){yield t}const n=ie(e),a=new Ct({generator:this.transform(r(),n),config:n});return await a.setup,Ge.fromAsyncGenerator(a)}},Ko=class extends un{name;description;schema;constructor(t){const e=ju.from([Or.from(async r=>{let n;if(Rc(r))try{n=await Op(this.schema,r.args)}catch{throw new dd("Received tool input did not match expected schema",JSON.stringify(r.args))}else n=r;return n}).withConfig({runName:`${t.name}:parse_input`}),t.bound]).withConfig({runName:t.name});super({bound:e,config:t.config??{}}),this.name=t.name,this.description=t.description,this.schema=t.schema}static lc_name(){return"RunnableToolLike"}};function lg(t,e){const r=e.name??t.getName(),n=e.description??$p(e.schema);return kp(e.schema)?new Ko({name:r,description:n,schema:Al({input:Il()}).transform(a=>a.input),bound:t}):new Ko({name:r,description:n,schema:e.schema,bound:t})}const ln=(t,e)=>{const r=[...new Set(e?.map(a=>{if(typeof a=="string")return a;const s=new a({});if(!("getType"in s)||typeof s.getType!="function")throw new Error("Invalid type provided.");return s.getType()}))],n=t.getType();return r.some(a=>a===n)};function Bu(t,e){return Array.isArray(t)?Yo(t,e):Or.from(r=>Yo(r,t))}function Yo(t,e={}){const{includeNames:r,excludeNames:n,includeTypes:a,excludeTypes:s,includeIds:i,excludeIds:o}=e,c=[];for(const u of t)if(!(n&&u.name&&n.includes(u.name))){{if(s&&ln(u,s))continue;if(o&&u.id&&o.includes(u.id))continue}a||i||r?(r&&u.name&&r.some(l=>l===u.name)||a&&ln(u,a)||i&&u.id&&i.some(l=>l===u.id))&&c.push(u):c.push(u)}return c}function zu(t){return Array.isArray(t)?Xo(t):Or.from(Xo)}function Xo(t){if(!t.length)return[];const e=[];for(const r of t){const n=r,a=e.pop();if(!a)e.push(n);else if(n.getType()==="tool"||n.getType()!==a.getType())e.push(a,n);else{const s=Qr(a),i=Qr(n),o=s.concat(i);typeof s.content=="string"&&typeof i.content=="string"&&(o.content=`${s.content}
78
+ ${i.content}`),e.push(fg(o))}}return e}function qu(t,e){if(Array.isArray(t)){const r=t;if(!e)throw new Error("Options parameter is required when providing messages.");return Qo(r,e)}else{const r=t;return Or.from(n=>Qo(n,r)).withConfig({runName:"trim_messages"})}}async function Qo(t,e){const{maxTokens:r,tokenCounter:n,strategy:a="last",allowPartial:s=!1,endOn:i,startOn:o,includeSystem:c=!1,textSplitter:u}=e;if(o&&a==="first")throw new Error("`startOn` should only be specified if `strategy` is 'last'.");if(c&&a==="first")throw new Error("`includeSystem` should only be specified if `strategy` is 'last'.");let l;"getNumTokens"in n?l=async f=>(await Promise.all(f.map(p=>n.getNumTokens(p.content)))).reduce((p,g)=>p+g,0):l=async f=>n(f);let d=zs;if(u&&("splitText"in u?d=u.splitText:d=async f=>u(f)),a==="first")return Gu(t,{maxTokens:r,tokenCounter:l,textSplitter:d,partialStrategy:s?"first":void 0,endOn:i});if(a==="last")return dg(t,{maxTokens:r,tokenCounter:l,textSplitter:d,allowPartial:s,includeSystem:c,startOn:o,endOn:i});throw new Error(`Unrecognized strategy: '${a}'. Must be one of 'first' or 'last'.`)}async function Gu(t,e){const{maxTokens:r,tokenCounter:n,textSplitter:a,partialStrategy:s,endOn:i}=e;let o=[...t],c=0;for(let u=0;u<o.length;u+=1){const l=u>0?o.slice(0,-u):o;if(await n(l)<=r){c=o.length-u;break}}if(c<o.length&&s){let u=!1;if(Array.isArray(o[c].content)){const l=o[c];if(typeof l.content=="string")throw new Error("Expected content to be an array.");const d=l.content.length,f=s==="last"?[...l.content].reverse():l.content;for(let h=1;h<=d;h+=1){const p=s==="first"?f.slice(0,h):f.slice(-h),g=Object.fromEntries(Object.entries(l).filter(([w])=>w!=="type"&&!w.startsWith("lc_"))),m=Bs(l.getType(),{...g,content:p}),_=[...o.slice(0,c),m];if(await n(_)<=r)o=_,c+=1,u=!0;else break}u&&s==="last"&&(l.content=[...f].reverse())}if(!u){const l=o[c];let d;if(Array.isArray(l.content)&&l.content.some(f=>typeof f=="string"||f.type==="text")?d=l.content.find(h=>h.type==="text"&&h.text)?.text:typeof l.content=="string"&&(d=l.content),d){const f=await a(d),h=f.length;s==="last"&&f.reverse();for(let p=0;p<h-1;p+=1)if(f.pop(),l.content=f.join(""),await n([...o.slice(0,c),l])<=r){s==="last"&&(l.content=[...f].reverse().join("")),o=[...o.slice(0,c),l],c+=1;break}}}}if(i){const u=Array.isArray(i)?i:[i];for(;c>0&&!ln(o[c-1],u);)c-=1}return o.slice(0,c)}async function dg(t,e){const{allowPartial:r=!1,includeSystem:n=!1,endOn:a,startOn:s,...i}=e;let o=t.map(l=>{const d=Object.fromEntries(Object.entries(l).filter(([f])=>f!=="type"&&!f.startsWith("lc_")));return Bs(l.getType(),d,ys(l))});if(a){const l=Array.isArray(a)?a:[a];for(;o.length>0&&!ln(o[o.length-1],l);)o=o.slice(0,-1)}const c=n&&o[0]?.getType()==="system";let u=c?o.slice(0,1).concat(o.slice(1).reverse()):o.reverse();return u=await Gu(u,{...i,partialStrategy:r?"last":void 0,endOn:s}),c?[u[0],...u.slice(1).reverse()]:u.reverse()}const ec={human:{message:$t,messageChunk:xr},ai:{message:xt,messageChunk:Ot},system:{message:ot,messageChunk:It},developer:{message:ot,messageChunk:It},tool:{message:Rt,messageChunk:br},function:{message:Sr,messageChunk:Tr},generic:{message:Vt,messageChunk:Er},remove:{message:pr,messageChunk:pr}};function Bs(t,e,r){let n,a;switch(t){case"human":r?n=new xr(e):a=new $t(e);break;case"ai":if(r){let s={...e};"tool_calls"in s&&(s={...s,tool_call_chunks:s.tool_calls?.map(i=>({...i,type:"tool_call_chunk",index:void 0,args:JSON.stringify(i.args)}))}),n=new Ot(s)}else a=new xt(e);break;case"system":r?n=new It(e):a=new ot(e);break;case"developer":r?n=new It({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}}):a=new ot({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in e)r?n=new br(e):a=new Rt(e);else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if(r)n=new Tr(e);else{if(!e.name)throw new Error("FunctionMessage must have a 'name' field");a=new Sr(e)}break;case"generic":if("role"in e)r?n=new Er(e):a=new Vt(e);else throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");break;default:throw new Error(`Unrecognized message type ${t}`)}if(r&&n)return n;if(a)return a;throw new Error(`Unrecognized message type ${t}`)}function fg(t){const e=t.getType();let r;const n=Object.fromEntries(Object.entries(t).filter(([a])=>!["type","tool_call_chunks"].includes(a)&&!a.startsWith("lc_")));if(e in ec&&(r=Bs(e,n)),!r)throw new Error(`Unrecognized message chunk class ${e}. Supported classes are ${Object.keys(ec)}`);return r}function zs(t){const e=t.split(`
81
79
  `);return Promise.resolve([...e.slice(0,-1).map(r=>`${r}
82
- `),e[e.length-1]])}const yg=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"],_g=["image","video","audio","text-plain","file"],Vu=["text","reasoning",...yg,..._g];var Ju={};me(Ju,{AIMessage:()=>It,AIMessageChunk:()=>kt,BaseMessage:()=>tt,BaseMessageChunk:()=>_t,ChatMessage:()=>Jt,ChatMessageChunk:()=>Sr,FunctionMessage:()=>Tr,FunctionMessageChunk:()=>xr,HumanMessage:()=>$t,HumanMessageChunk:()=>Ir,KNOWN_BLOCK_TYPES:()=>Vu,RemoveMessage:()=>mr,SystemMessage:()=>ct,SystemMessageChunk:()=>At,ToolMessage:()=>Rt,ToolMessageChunk:()=>Er,_isMessageFieldWithRole:()=>_s,_mergeDicts:()=>ve,_mergeLists:()=>Vt,_mergeObj:()=>ys,_mergeStatus:()=>gs,coerceMessageLikeToMessage:()=>Cc,convertToChunk:()=>en,convertToOpenAIImageBlock:()=>uc,convertToProviderContentBlock:()=>dc,defaultTextSplitter:()=>qs,defaultToolCallParser:()=>hn,filterMessages:()=>qu,getBufferString:()=>Is,iife:()=>$c,isAIMessage:()=>vc,isAIMessageChunk:()=>wc,isBase64ContentBlock:()=>ls,isBaseMessage:()=>fn,isBaseMessageChunk:()=>vs,isChatMessage:()=>Ec,isChatMessageChunk:()=>Sc,isDataContentBlock:()=>ot,isDirectToolOutput:()=>Es,isFunctionMessage:()=>Tc,isFunctionMessageChunk:()=>xc,isHumanMessage:()=>Ic,isHumanMessageChunk:()=>Ac,isIDContentBlock:()=>ds,isMessage:()=>fs,isOpenAIToolCallArray:()=>mc,isPlainTextContentBlock:()=>cc,isSystemMessage:()=>Oc,isSystemMessageChunk:()=>Rc,isToolMessage:()=>Ss,isToolMessageChunk:()=>Ts,isURLContentBlock:()=>us,mapChatMessagesToStoredMessages:()=>Pc,mapStoredMessageToChatMessage:()=>As,mapStoredMessagesToChatMessages:()=>Nc,mergeContent:()=>yt,mergeMessageRuns:()=>Gu,mergeResponseMetadata:()=>ws,mergeUsageMetadata:()=>bs,parseBase64DataUrl:()=>Qr,parseMimeType:()=>lc,trimMessages:()=>Hu});const Yg=Object.freeze(Object.defineProperty({__proto__:null,AIMessage:It,AIMessageChunk:kt,BaseMessage:tt,BaseMessageChunk:_t,ChatMessage:Jt,ChatMessageChunk:Sr,FunctionMessage:Tr,FunctionMessageChunk:xr,HumanMessage:$t,HumanMessageChunk:Ir,KNOWN_BLOCK_TYPES:Vu,RemoveMessage:mr,SystemMessage:ct,SystemMessageChunk:At,ToolMessage:Rt,ToolMessageChunk:Er,_isMessageFieldWithRole:_s,_mergeDicts:ve,_mergeLists:Vt,_mergeObj:ys,_mergeStatus:gs,coerceMessageLikeToMessage:Cc,convertToChunk:en,convertToOpenAIImageBlock:uc,convertToProviderContentBlock:dc,defaultTextSplitter:qs,defaultToolCallParser:hn,filterMessages:qu,getBufferString:Is,iife:$c,isAIMessage:vc,isAIMessageChunk:wc,isBase64ContentBlock:ls,isBaseMessage:fn,isBaseMessageChunk:vs,isChatMessage:Ec,isChatMessageChunk:Sc,isDataContentBlock:ot,isDirectToolOutput:Es,isFunctionMessage:Tc,isFunctionMessageChunk:xc,isHumanMessage:Ic,isHumanMessageChunk:Ac,isIDContentBlock:ds,isMessage:fs,isOpenAIToolCallArray:mc,isPlainTextContentBlock:cc,isSystemMessage:Oc,isSystemMessageChunk:Rc,isToolMessage:Ss,isToolMessageChunk:Ts,isURLContentBlock:us,mapChatMessagesToStoredMessages:Pc,mapStoredMessageToChatMessage:As,mapStoredMessagesToChatMessages:Nc,mergeContent:yt,mergeMessageRuns:Gu,mergeResponseMetadata:ws,mergeUsageMetadata:bs,messages_exports:Ju,parseBase64DataUrl:Qr,parseMimeType:lc,trimMessages:Hu},Symbol.toStringTag,{value:"Module"}));export{qg as $,Eu as A,Tp as B,Ct as C,kt as D,Jt as E,Ss as F,cn as G,ot as H,dc as I,Qr as J,Et as K,Uu as L,pp as M,hp as N,jg as O,Ot as P,fe as Q,Sp as R,ge as S,md as T,Dg as U,st as V,xu as W,Cp as X,$p as Y,Fs as Z,me as _,vc as a,ng as a$,Gg as a0,Ug as a1,nr as a2,as as a3,Go as a4,Zg as a5,Jg as a6,Bg as a7,zg as a8,Pp as a9,pd as aA,vs as aB,en as aC,Ft as aD,vr as aE,Cg as aF,b as aG,Js as aH,Ir as aI,At as aJ,xr as aK,Er as aL,Sr as aM,lc as aN,$c as aO,xd as aP,zc as aQ,Sd as aR,Nt as aS,He as aT,rg as aU,yi as aV,yr as aW,ct as aX,tt as aY,Kt as aZ,dp as a_,qo as aa,Vg as ab,Hg as ac,Ce as ad,$t as ae,Is as af,hr as ag,As as ah,Cc as ai,fg as aj,wn as ak,wc as al,kr as am,us as an,ls as ao,uc as ap,bt as aq,Ge as ar,pe as as,ln as at,dg as au,Xo as av,Du as aw,hg as ax,Kg as ay,Wg as az,js as b,bd as b0,Ap as b1,Yh as b2,wp as b3,Hh as b4,Bh as b5,up as b6,ag as b7,Ep as b8,od as b9,Eg as bA,wg as bB,qu as bC,_t as bD,Yg as bE,Ju as ba,Bl as bb,tp as bc,sp as bd,Nd as be,hs as bf,Fl as bg,$g as bh,Ar as bi,Bs as bj,or as bk,Te as bl,Rl as bm,ee as bn,xg as bo,Og as bp,Sg as bq,oi as br,Ag as bs,Tg as bt,bg as bu,kg as bv,mr as bw,Hu as bx,Rg as by,Ig as bz,Md as c,ip as d,ie as e,kc as f,Tu as g,Np as h,Fg as i,Ng as j,Es as k,Rt as l,Uo as m,Mp as n,$l as o,yc as p,Vr as q,we as r,kl as s,ut as t,Zt as u,ce as v,an as w,Pu as x,fn as y,It as z};
80
+ `),e[e.length-1]])}const hg=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"],pg=["image","video","audio","text-plain","file"],Hu=["text","reasoning",...hg,...pg];var Zu={};me(Zu,{AIMessage:()=>xt,AIMessageChunk:()=>Ot,BaseMessage:()=>et,BaseMessageChunk:()=>_t,ChatMessage:()=>Vt,ChatMessageChunk:()=>Er,FunctionMessage:()=>Sr,FunctionMessageChunk:()=>Tr,HumanMessage:()=>$t,HumanMessageChunk:()=>xr,KNOWN_BLOCK_TYPES:()=>Hu,RemoveMessage:()=>pr,SystemMessage:()=>ot,SystemMessageChunk:()=>It,ToolMessage:()=>Rt,ToolMessageChunk:()=>br,_isMessageFieldWithRole:()=>_s,_mergeDicts:()=>ve,_mergeLists:()=>Zt,_mergeObj:()=>gs,_mergeStatus:()=>ms,coerceMessageLikeToMessage:()=>$c,convertToChunk:()=>Qr,convertToOpenAIImageBlock:()=>oc,convertToProviderContentBlock:()=>uc,defaultTextSplitter:()=>zs,defaultToolCallParser:()=>fn,filterMessages:()=>Bu,getBufferString:()=>xs,iife:()=>Oc,isAIMessage:()=>_c,isAIMessageChunk:()=>yc,isBase64ContentBlock:()=>us,isBaseMessage:()=>dn,isBaseMessageChunk:()=>ys,isChatMessage:()=>wc,isChatMessageChunk:()=>bc,isDataContentBlock:()=>it,isDirectToolOutput:()=>bs,isFunctionMessage:()=>Ec,isFunctionMessageChunk:()=>Sc,isHumanMessage:()=>Tc,isHumanMessageChunk:()=>xc,isIDContentBlock:()=>ls,isMessage:()=>ds,isOpenAIToolCallArray:()=>hc,isPlainTextContentBlock:()=>ic,isSystemMessage:()=>Ic,isSystemMessageChunk:()=>Ac,isToolMessage:()=>Es,isToolMessageChunk:()=>Ss,isURLContentBlock:()=>cs,mapChatMessagesToStoredMessages:()=>Cc,mapStoredMessageToChatMessage:()=>Is,mapStoredMessagesToChatMessages:()=>kc,mergeContent:()=>gt,mergeMessageRuns:()=>zu,mergeResponseMetadata:()=>vs,mergeUsageMetadata:()=>ws,parseBase64DataUrl:()=>Xr,parseMimeType:()=>cc,trimMessages:()=>qu});const Vg=Object.freeze(Object.defineProperty({__proto__:null,AIMessage:xt,AIMessageChunk:Ot,BaseMessage:et,BaseMessageChunk:_t,ChatMessage:Vt,ChatMessageChunk:Er,FunctionMessage:Sr,FunctionMessageChunk:Tr,HumanMessage:$t,HumanMessageChunk:xr,KNOWN_BLOCK_TYPES:Hu,RemoveMessage:pr,SystemMessage:ot,SystemMessageChunk:It,ToolMessage:Rt,ToolMessageChunk:br,_isMessageFieldWithRole:_s,_mergeDicts:ve,_mergeLists:Zt,_mergeObj:gs,_mergeStatus:ms,coerceMessageLikeToMessage:$c,convertToChunk:Qr,convertToOpenAIImageBlock:oc,convertToProviderContentBlock:uc,defaultTextSplitter:zs,defaultToolCallParser:fn,filterMessages:Bu,getBufferString:xs,iife:Oc,isAIMessage:_c,isAIMessageChunk:yc,isBase64ContentBlock:us,isBaseMessage:dn,isBaseMessageChunk:ys,isChatMessage:wc,isChatMessageChunk:bc,isDataContentBlock:it,isDirectToolOutput:bs,isFunctionMessage:Ec,isFunctionMessageChunk:Sc,isHumanMessage:Tc,isHumanMessageChunk:xc,isIDContentBlock:ls,isMessage:ds,isOpenAIToolCallArray:hc,isPlainTextContentBlock:ic,isSystemMessage:Ic,isSystemMessageChunk:Ac,isToolMessage:Es,isToolMessageChunk:Ss,isURLContentBlock:cs,mapChatMessagesToStoredMessages:Cc,mapStoredMessageToChatMessage:Is,mapStoredMessagesToChatMessages:kc,mergeContent:gt,mergeMessageRuns:zu,mergeResponseMetadata:vs,mergeUsageMetadata:ws,messages_exports:Zu,parseBase64DataUrl:Xr,parseMimeType:cc,trimMessages:qu},Symbol.toStringTag,{value:"Module"}));export{Ug as $,wu as A,wp as B,kt as C,Ot as D,Vt as E,Es as F,on as G,it as H,uc as I,Xr as J,bt as K,ju as L,lp as M,up as N,Ng as O,At as P,fe as Q,vp as R,ge as S,dd as T,Pg as U,at as V,Su as W,Rp as X,Ap as Y,Us as Z,me as _,_c as a,_d as a$,Fg as a0,Lg as a1,rr as a2,ns as a3,zo as a4,zg as a5,Gg as a6,jg as a7,Dg as a8,$p as a9,ld as aA,ys as aB,Qr as aC,Ut as aD,yr as aE,Rg as aF,b as aG,xr as aH,It as aI,Tr as aJ,br as aK,Er as aL,cc as aM,Oc as aN,bd as aO,Fc as aP,vd as aQ,Ct as aR,Ge as aS,Xm as aT,mi as aU,gr as aV,ot as aW,et as aX,Jt as aY,op as aZ,Qm as a_,Bo as aa,qg as ab,Bg as ac,$e as ad,$t as ae,xs as af,fr as ag,Is as ah,$c as ai,cg as aj,vn as ak,yc as al,Or as am,cs as an,us as ao,oc as ap,wt as aq,qe as ar,pe as as,un as at,og as au,Ko as av,Mu as aw,ug as ax,Zg as ay,Hg as az,Ms as b,Sp as b0,Vh as b1,gp as b2,Bh as b3,jh as b4,sp as b5,eg as b6,yp as b7,nd as b8,Zu as b9,gg as bA,Bu as bB,_t as bC,Vg as bD,jl as ba,Yh as bb,tp as bc,Od as bd,fs as be,Ml as bf,Ag as bg,Ir as bh,Fs as bi,ir as bj,Se as bk,xl as bl,ee as bm,bg as bn,Tg as bo,vg as bp,si as bq,Sg as br,wg as bs,_g as bt,Ig as bu,pr as bv,qu as bw,xg as bx,Eg as by,yg as bz,kd as c,rp as d,ie as e,Rc as f,Eu as g,Op as h,Mg as i,Og as j,bs as k,Rt as l,jo as m,kp as n,Al as o,mc as p,Zr as q,we as r,Il as s,ct as t,Ht as u,ce as v,nn as w,Cu as x,dn as y,xt as z};