@mcp-use/inspector 0.9.0-canary.4 → 0.9.0-canary.6

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.
Files changed (40) hide show
  1. package/dist/client/assets/__vite-browser-external-DFygW7-s.js +1 -0
  2. package/dist/client/assets/browser-C7T69h9H.js +408 -0
  3. package/dist/client/assets/display-A5IEINAP-PpmJDTVa.js +17 -0
  4. package/dist/client/assets/embeddings-DHqEojuq.js +1 -0
  5. package/dist/client/assets/index-BisjKad9.js +7 -0
  6. package/dist/client/assets/index-C1CCILMM.js +33 -0
  7. package/dist/client/assets/index-CHNXgq6o.css +1 -0
  8. package/dist/client/assets/index-CI3g_RcQ.js +8 -0
  9. package/dist/client/assets/index-Cx63umjv.js +152 -0
  10. package/dist/client/assets/index-DGYydIoI.js +2 -0
  11. package/dist/client/assets/index-DRz5BQNA.js +1 -0
  12. package/dist/client/assets/index-DoALAYox.js +25 -0
  13. package/dist/client/assets/index-IFdSquJo.js +1626 -0
  14. package/dist/client/assets/index-JiKw9JSs.js +5 -0
  15. package/dist/client/assets/index-OksJgzlF.js +20 -0
  16. package/dist/client/assets/path-C9FudP8b.js +1 -0
  17. package/dist/client/assets/transport-wrapper-browser-BI4dDu3b.js +1 -0
  18. package/dist/client/assets/util-t-trnxQI.js +1 -0
  19. package/dist/client/assets/winston-DCacaJQs.js +37 -0
  20. package/dist/client/index.html +3 -3
  21. package/package.json +5 -4
  22. package/dist/client/assets/__vite-browser-external-CHS79mP1.js +0 -8
  23. package/dist/client/assets/browser-CwknRi82.js +0 -17967
  24. package/dist/client/assets/display-A5IEINAP-DNDlZQ8k.js +0 -480
  25. package/dist/client/assets/embeddings-DSM58WFd.js +0 -26
  26. package/dist/client/assets/index-BMuvzxLw.js +0 -400
  27. package/dist/client/assets/index-BWKKRrN4.js +0 -43965
  28. package/dist/client/assets/index-Br7cLVs6.css +0 -5812
  29. package/dist/client/assets/index-BumNh2YP.js +0 -725
  30. package/dist/client/assets/index-D-pAR_RA.js +0 -26733
  31. package/dist/client/assets/index-DD0wWmuA.js +0 -9991
  32. package/dist/client/assets/index-DEA0KU_h.js +0 -105533
  33. package/dist/client/assets/index-DX0TIfSM.js +0 -102
  34. package/dist/client/assets/index-DctLeaKS.js +0 -2817
  35. package/dist/client/assets/index-DgPlosep.js +0 -1812
  36. package/dist/client/assets/index-DiEpOjl1.js +0 -5370
  37. package/dist/client/assets/path-QsnVvLoj.js +0 -62
  38. package/dist/client/assets/transport-wrapper-browser-ChPHVnHg.js +0 -165
  39. package/dist/client/assets/util-D59LNlyU.js +0 -23
  40. package/dist/client/assets/winston-B_texDHP.js +0 -12307
@@ -0,0 +1,152 @@
1
+ import{bj as Fl,bk as Ve,bl as Bl,bi as yr,bm as Lc,bn as Zt,bo as zl,bp as ql,bq as jc,bg as Vs,br as Gl,bs as Hl,bt as Vl,bu as Zl}from"./index-IFdSquJo.js";import{r as Jl}from"./index-DRz5BQNA.js";class Ri{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Ve,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},h=e._zod.parent;if(h)o.ref=h,this.process(h,d),this.seen.get(h).isParent=!0;else{const f=o.schema;switch(a.type){case"string":{const p=f;p.type="string";const{minimum:y,maximum:_,format:w,patterns:T,contentEncoding:E}=e._zod.bag;if(typeof y=="number"&&(p.minLength=y),typeof _=="number"&&(p.maxLength=_),w&&(p.format=s[w]??w,p.format===""&&delete p.format),E&&(p.contentEncoding=E),T&&T.size>0){const x=[...T];x.length===1?p.pattern=x[0].source:x.length>1&&(o.schema.allOf=[...x.map(R=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:R.source}))])}break}case"number":{const p=f,{minimum:y,maximum:_,format:w,multipleOf:T,exclusiveMaximum:E,exclusiveMinimum:x}=e._zod.bag;typeof w=="string"&&w.includes("int")?p.type="integer":p.type="number",typeof x=="number"&&(this.target==="draft-4"||this.target==="openapi-3.0"?(p.minimum=x,p.exclusiveMinimum=!0):p.exclusiveMinimum=x),typeof y=="number"&&(p.minimum=y,typeof x=="number"&&this.target!=="draft-4"&&(x>=y?delete p.minimum:delete p.exclusiveMinimum)),typeof E=="number"&&(this.target==="draft-4"||this.target==="openapi-3.0"?(p.maximum=E,p.exclusiveMaximum=!0):p.exclusiveMaximum=E),typeof _=="number"&&(p.maximum=_,typeof E=="number"&&this.target!=="draft-4"&&(E<=_?delete p.maximum:delete p.exclusiveMaximum)),typeof T=="number"&&(p.multipleOf=T);break}case"boolean":{const p=f;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"?(f.type="string",f.nullable=!0,f.enum=[null]):f.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":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const p=f,{minimum:y,maximum:_}=e._zod.bag;typeof y=="number"&&(p.minItems=y),typeof _=="number"&&(p.maxItems=_),p.type="array",p.items=this.process(a.element,{...d,path:[...d.path,"items"]});break}case"object":{const p=f;p.type="object",p.properties={};const y=a.shape;for(const T in y)p.properties[T]=this.process(y[T],{...d,path:[...d.path,"properties",T]});const _=new Set(Object.keys(y)),w=new Set([..._].filter(T=>{const E=a.shape[T]._zod;return this.io==="input"?E.optin===void 0:E.optout===void 0}));w.size>0&&(p.required=Array.from(w)),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=f,y=a.discriminator!==void 0,_=a.options.map((w,T)=>this.process(w,{...d,path:[...d.path,y?"oneOf":"anyOf",T]}));y?p.oneOf=_:p.anyOf=_;break}case"intersection":{const p=f,y=this.process(a.left,{...d,path:[...d.path,"allOf",0]}),_=this.process(a.right,{...d,path:[...d.path,"allOf",1]}),w=E=>"allOf"in E&&Object.keys(E).length===1,T=[...w(y)?y.allOf:[y],...w(_)?_.allOf:[_]];p.allOf=T;break}case"tuple":{const p=f;p.type="array";const y=this.target==="draft-2020-12"?"prefixItems":"items",_=this.target==="draft-2020-12"||this.target==="openapi-3.0"?"items":"additionalItems",w=a.items.map((R,j)=>this.process(R,{...d,path:[...d.path,y,j]})),T=a.rest?this.process(a.rest,{...d,path:[...d.path,_,...this.target==="openapi-3.0"?[a.items.length]:[]]}):null;this.target==="draft-2020-12"?(p.prefixItems=w,T&&(p.items=T)):this.target==="openapi-3.0"?(p.items={anyOf:w},T&&p.items.anyOf.push(T),p.minItems=w.length,T||(p.maxItems=w.length)):(p.items=w,T&&(p.additionalItems=T));const{minimum:E,maximum:x}=e._zod.bag;typeof E=="number"&&(p.minItems=E),typeof x=="number"&&(p.maxItems=x);break}case"record":{const p=f;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=f,y=Bl(a.entries);y.every(_=>typeof _=="number")&&(p.type="number"),y.every(_=>typeof _=="string")&&(p.type="string"),p.enum=y;break}case"literal":{const p=f,y=[];for(const _ of a.values)if(_===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof _=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");y.push(Number(_))}else y.push(_);if(y.length!==0)if(y.length===1){const _=y[0];p.type=_===null?"null":typeof _,this.target==="draft-4"||this.target==="openapi-3.0"?p.enum=[_]:p.const=_}else y.every(_=>typeof _=="number")&&(p.type="number"),y.every(_=>typeof _=="string")&&(p.type="string"),y.every(_=>typeof _=="boolean")&&(p.type="string"),y.every(_=>_===null)&&(p.type="null"),p.enum=y;break}case"file":{const p=f,y={type:"string",format:"binary",contentEncoding:"binary"},{minimum:_,maximum:w,mime:T}=e._zod.bag;_!==void 0&&(y.minLength=_),w!==void 0&&(y.maxLength=w),T?T.length===1?(y.contentMediaType=T[0],Object.assign(p,y)):p.anyOf=T.map(E=>({...y,contentMediaType:E})):Object.assign(p,y);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,f.nullable=!0):f.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(a.innerType,d),o.ref=a.innerType;break}case"success":{const p=f;p.type="boolean";break}case"default":{this.process(a.innerType,d),o.ref=a.innerType,f.default=JSON.parse(JSON.stringify(a.defaultValue));break}case"prefault":{this.process(a.innerType,d),o.ref=a.innerType,this.io==="input"&&(f._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")}f.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=f,y=e._zod.pattern;if(!y)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=y.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,f.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"&&De(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 y=n.external.registry.get(l[0])?.id,_=n.external.uri??(T=>T);if(y)return{ref:_(y)};const w=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=w,{defId:w,ref:`${_("__shared")}#/${d}/${w}`}}if(l[1]===a)return{ref:"#"};const f=`#/${d}/`,p=l[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:f+p}},i=l=>{if(l[1].schema.$ref)return;const d=l[1],{ref:h,defId:f}=s(l);d.def={...d.schema},f&&(d.defId=f);const p=d.schema;for(const y in p)delete p[y];p.$ref=h};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 f=n.external.registry.get(l[0])?.id;if(e!==l[0]&&f){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 h=this.seen.get(l),f=h.def??h.schema,p={...f};if(h.ref===null)return;const y=h.ref;if(h.ref=null,y){o(y,d);const _=this.seen.get(y).schema;_.$ref&&(d.target==="draft-7"||d.target==="draft-4"||d.target==="openapi-3.0")?(f.allOf=f.allOf??[],f.allOf.push(_)):(Object.assign(f,_),Object.assign(f,p))}h.isParent||this.override({zodSchema:l,jsonSchema:f,path:h.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 Ci(t,e){if(t instanceof Fl){const n=new Ri(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 Ri(e);return r.process(t),r.emit(t,e)}function De(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 De(n.element,r);if(n.type==="set")return De(n.valueType,r);if(n.type==="lazy")return De(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 De(n.innerType,r);if(n.type==="intersection")return De(n.left,r)||De(n.right,r);if(n.type==="record"||n.type==="map")return De(n.keyType,r)||De(n.valueType,r);if(n.type==="pipe")return De(n.in,r)||De(n.out,r);if(n.type==="object"){for(const a in n.shape)if(De(n.shape[a],r))return!0;return!1}if(n.type==="union"){for(const a of n.options)if(De(a,r))return!0;return!1}if(n.type==="tuple"){for(const a of n.items)if(De(a,r))return!0;return!!(n.rest&&De(n.rest,r))}return!1}var ue;(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})(ue||(ue={}));var Ni;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Ni||(Ni={}));const M=ue.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ct=t=>{switch(typeof t){case"undefined":return M.undefined;case"string":return M.string;case"number":return Number.isNaN(t)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":return Array.isArray(t)?M.array:t===null?M.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?M.promise:typeof Map<"u"&&t instanceof Map?M.map:typeof Set<"u"&&t instanceof Set?M.set:typeof Date<"u"&&t instanceof Date?M.date:M.object;default:return M.unknown}},I=ue.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 Qe 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 Qe))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ue.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()}}Qe.create=t=>new Qe(t);const Nr=(t,e)=>{let r;switch(t.code){case I.invalid_type:t.received===M.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case I.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ue.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:r=`Unrecognized key(s) in object: ${ue.joinValues(t.keys,", ")}`;break;case I.invalid_union:r="Invalid input";break;case I.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ue.joinValues(t.options)}`;break;case I.invalid_enum_value:r=`Invalid enum value. Expected ${ue.joinValues(t.options)}, received '${t.received}'`;break;case I.invalid_arguments:r="Invalid function arguments";break;case I.invalid_return_type:r="Invalid function return type";break;case I.invalid_date:r="Invalid date";break;case I.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}"`:ue.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case I.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 I.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 I.custom:r="Invalid input";break;case I.invalid_intersection_types:r="Intersection results could not be merged";break;case I.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case I.not_finite:r="Number must be finite";break;default:r=e.defaultError,ue.assertNever(t)}return{message:r}};let Wl=Nr;function ls(){return Wl}const ds=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,e){const r=ls(),n=ds({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Nr?void 0:Nr].filter(a=>!!a)});t.common.issues.push(n)}class Fe{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 X;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 Fe.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 X;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 X=Object.freeze({status:"aborted"}),xr=t=>({status:"dirty",value:t}),Ze=t=>({status:"valid",value:t}),$i=t=>t.status==="aborted",Pi=t=>t.status==="dirty",cr=t=>t.status==="valid",fn=t=>typeof Promise<"u"&&t instanceof Promise;var z;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(z||(z={}));class _t{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 Mi=(t,e)=>{if(cr(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 Qe(t.common.issues);return this._error=r,this._error}}};function ne(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 ie{get description(){return this._def.description}_getType(e){return Ct(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Ct(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Fe,ctx:{common:e.parent.common,data:e.data,parsedType:Ct(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(fn(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:Ct(e)},a=this._parseSync({data:e,path:n.path,parent:n});return Mi(n,a)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ct(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return cr(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=>cr(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:Ct(e)},a=this._parse({data:e,path:n.path,parent:n}),s=await(fn(a)?a:Promise.resolve(a));return Mi(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:I.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 dr({schema:this,typeName:A.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return $t.create(this,this._def)}nullable(){return hr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pt.create(this)}promise(){return Lr.create(this,this._def)}or(e){return mn.create([this,e],this._def)}and(e){return gn.create(this,e,this._def)}transform(e){return new dr({...ne(this._def),schema:this,typeName:A.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new gs({...ne(this._def),innerType:this,defaultValue:r,typeName:A.ZodDefault})}brand(){return new _d({typeName:A.ZodBranded,type:this,...ne(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new ys({...ne(this._def),innerType:this,catchValue:r,typeName:A.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Zs.create(this,e)}readonly(){return _s.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Kl=/^c[^\s-]{8,}$/i,Yl=/^[0-9a-z]+$/,Xl=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ql=/^[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,ed=/^[a-z0-9_-]{21}$/i,td=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,rd=/^[-+]?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)?)??$/,nd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ad="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Zn;const sd=/^(?:(?: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])$/,id=/^(?:(?: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])$/,od=/^(([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]))$/,cd=/^(([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])$/,ud=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ld=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Dc="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dd=new RegExp(`^${Dc}$`);function Uc(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 hd(t){return new RegExp(`^${Uc(t)}$`)}function fd(t){let e=`${Dc}T${Uc(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 pd(t,e){return!!((e==="v4"||!e)&&sd.test(t)||(e==="v6"||!e)&&od.test(t))}function md(t,e){if(!td.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 gd(t,e){return!!((e==="v4"||!e)&&id.test(t)||(e==="v6"||!e)&&cd.test(t))}class Et extends ie{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){const s=this._getOrReturnCtx(e);return $(s,{code:I.invalid_type,expected:M.string,received:s.parsedType}),X}const n=new Fe;let a;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(a=this._getOrReturnCtx(e,a),$(a,{code:I.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),$(a,{code:I.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?$(a,{code:I.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&$(a,{code:I.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")nd.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"email",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Zn||(Zn=new RegExp(ad,"u")),Zn.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"emoji",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Ql.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"uuid",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")ed.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"nanoid",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Kl.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"cuid",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")Yl.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"cuid2",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Xl.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"ulid",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{a=this._getOrReturnCtx(e,a),$(a,{validation:"url",code:I.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),$(a,{validation:"regex",code:I.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),$(a,{code:I.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),$(a,{code:I.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(a=this._getOrReturnCtx(e,a),$(a,{code:I.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?fd(s).test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{code:I.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?dd.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{code:I.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?hd(s).test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{code:I.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?rd.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"duration",code:I.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?pd(e.data,s.version)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"ip",code:I.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?md(e.data,s.alg)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"jwt",code:I.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?gd(e.data,s.version)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"cidr",code:I.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?ud.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"base64",code:I.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?ld.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"base64url",code:I.invalid_string,message:s.message}),n.dirty()):ue.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(a=>e.test(a),{validation:r,code:I.invalid_string,...z.errToObj(n)})}_addCheck(e){return new Et({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...z.errToObj(e)})}url(e){return this._addCheck({kind:"url",...z.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...z.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...z.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...z.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...z.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...z.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...z.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...z.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...z.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...z.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...z.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...z.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,...z.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,...z.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...z.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...z.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...z.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...z.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...z.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...z.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...z.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...z.errToObj(r)})}nonempty(e){return this.min(1,z.errToObj(e))}trim(){return new Et({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Et({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Et({...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}}Et.create=t=>new Et({checks:[],typeName:A.ZodString,coerce:t?.coerce??!1,...ne(t)});function yd(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 ur extends ie{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)!==M.number){const s=this._getOrReturnCtx(e);return $(s,{code:I.invalid_type,expected:M.number,received:s.parsedType}),X}let n;const a=new Fe;for(const s of this._def.checks)s.kind==="int"?ue.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),$(n,{code:I.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),$(n,{code:I.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),$(n,{code:I.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty()):s.kind==="multipleOf"?yd(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),$(n,{code:I.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),$(n,{code:I.not_finite,message:s.message}),a.dirty()):ue.assertNever(s);return{status:a.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,z.toString(r))}gt(e,r){return this.setLimit("min",e,!1,z.toString(r))}lte(e,r){return this.setLimit("max",e,!0,z.toString(r))}lt(e,r){return this.setLimit("max",e,!1,z.toString(r))}setLimit(e,r,n,a){return new ur({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:z.toString(a)}]})}_addCheck(e){return new ur({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:z.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:z.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:z.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:z.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:z.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"&&ue.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)}}ur.create=t=>new ur({checks:[],typeName:A.ZodNumber,coerce:t?.coerce||!1,...ne(t)});class $r extends ie{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)!==M.bigint)return this._getInvalidInput(e);let n;const a=new Fe;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),$(n,{code:I.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),$(n,{code:I.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),$(n,{code:I.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):ue.assertNever(s);return{status:a.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return $(r,{code:I.invalid_type,expected:M.bigint,received:r.parsedType}),X}gte(e,r){return this.setLimit("min",e,!0,z.toString(r))}gt(e,r){return this.setLimit("min",e,!1,z.toString(r))}lte(e,r){return this.setLimit("max",e,!0,z.toString(r))}lt(e,r){return this.setLimit("max",e,!1,z.toString(r))}setLimit(e,r,n,a){return new $r({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:z.toString(a)}]})}_addCheck(e){return new $r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:z.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:z.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}}$r.create=t=>new $r({checks:[],typeName:A.ZodBigInt,coerce:t?.coerce??!1,...ne(t)});class hs extends ie{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){const n=this._getOrReturnCtx(e);return $(n,{code:I.invalid_type,expected:M.boolean,received:n.parsedType}),X}return Ze(e.data)}}hs.create=t=>new hs({typeName:A.ZodBoolean,coerce:t?.coerce||!1,...ne(t)});class pn extends ie{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){const s=this._getOrReturnCtx(e);return $(s,{code:I.invalid_type,expected:M.date,received:s.parsedType}),X}if(Number.isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return $(s,{code:I.invalid_date}),X}const n=new Fe;let a;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(a=this._getOrReturnCtx(e,a),$(a,{code:I.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),$(a,{code:I.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ue.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new pn({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:z.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:z.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}}pn.create=t=>new pn({checks:[],coerce:t?.coerce||!1,typeName:A.ZodDate,...ne(t)});class Li extends ie{_parse(e){if(this._getType(e)!==M.symbol){const n=this._getOrReturnCtx(e);return $(n,{code:I.invalid_type,expected:M.symbol,received:n.parsedType}),X}return Ze(e.data)}}Li.create=t=>new Li({typeName:A.ZodSymbol,...ne(t)});class fs extends ie{_parse(e){if(this._getType(e)!==M.undefined){const n=this._getOrReturnCtx(e);return $(n,{code:I.invalid_type,expected:M.undefined,received:n.parsedType}),X}return Ze(e.data)}}fs.create=t=>new fs({typeName:A.ZodUndefined,...ne(t)});class ji extends ie{_parse(e){if(this._getType(e)!==M.null){const n=this._getOrReturnCtx(e);return $(n,{code:I.invalid_type,expected:M.null,received:n.parsedType}),X}return Ze(e.data)}}ji.create=t=>new ji({typeName:A.ZodNull,...ne(t)});class Pr extends ie{constructor(){super(...arguments),this._any=!0}_parse(e){return Ze(e.data)}}Pr.create=t=>new Pr({typeName:A.ZodAny,...ne(t)});class or extends ie{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ze(e.data)}}or.create=t=>new or({typeName:A.ZodUnknown,...ne(t)});class Mt extends ie{_parse(e){const r=this._getOrReturnCtx(e);return $(r,{code:I.invalid_type,expected:M.never,received:r.parsedType}),X}}Mt.create=t=>new Mt({typeName:A.ZodNever,...ne(t)});class Di extends ie{_parse(e){if(this._getType(e)!==M.undefined){const n=this._getOrReturnCtx(e);return $(n,{code:I.invalid_type,expected:M.void,received:n.parsedType}),X}return Ze(e.data)}}Di.create=t=>new Di({typeName:A.ZodVoid,...ne(t)});class pt extends ie{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),a=this._def;if(r.parsedType!==M.array)return $(r,{code:I.invalid_type,expected:M.array,received:r.parsedType}),X;if(a.exactLength!==null){const i=r.data.length>a.exactLength.value,o=r.data.length<a.exactLength.value;(i||o)&&($(r,{code:i?I.too_big:I.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&&($(r,{code:I.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&&($(r,{code:I.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 _t(r,i,r.path,o)))).then(i=>Fe.mergeArray(n,i));const s=[...r.data].map((i,o)=>a.type._parseSync(new _t(r,i,r.path,o)));return Fe.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new pt({...this._def,minLength:{value:e,message:z.toString(r)}})}max(e,r){return new pt({...this._def,maxLength:{value:e,message:z.toString(r)}})}length(e,r){return new pt({...this._def,exactLength:{value:e,message:z.toString(r)}})}nonempty(e){return this.min(1,e)}}pt.create=(t,e)=>new pt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:A.ZodArray,...ne(e)});function rr(t){if(t instanceof Ae){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=$t.create(rr(n))}return new Ae({...t._def,shape:()=>e})}else return t instanceof pt?new pt({...t._def,type:rr(t.element)}):t instanceof $t?$t.create(rr(t.unwrap())):t instanceof hr?hr.create(rr(t.unwrap())):t instanceof xt?xt.create(t.items.map(e=>rr(e))):t}class Ae extends ie{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=ue.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==M.object){const u=this._getOrReturnCtx(e);return $(u,{code:I.invalid_type,expected:M.object,received:u.parsedType}),X}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 _t(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&&($(a,{code:I.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 _t(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,h=await l.value;u.push({key:d,value:h,alwaysSet:l.alwaysSet})}return u}).then(u=>Fe.mergeObjectSync(n,u)):Fe.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return z.errToObj,new Ae({...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:z.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new Ae({...this._def,unknownKeys:"strip"})}passthrough(){return new Ae({...this._def,unknownKeys:"passthrough"})}extend(e){return new Ae({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Ae({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:A.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new Ae({...this._def,catchall:e})}pick(e){const r={};for(const n of ue.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new Ae({...this._def,shape:()=>r})}omit(e){const r={};for(const n of ue.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new Ae({...this._def,shape:()=>r})}deepPartial(){return rr(this)}partial(e){const r={};for(const n of ue.objectKeys(this.shape)){const a=this.shape[n];e&&!e[n]?r[n]=a:r[n]=a.optional()}return new Ae({...this._def,shape:()=>r})}required(e){const r={};for(const n of ue.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof $t;)s=s._def.innerType;r[n]=s}return new Ae({...this._def,shape:()=>r})}keyof(){return Fc(ue.objectKeys(this.shape))}}Ae.create=(t,e)=>new Ae({shape:()=>t,unknownKeys:"strip",catchall:Mt.create(),typeName:A.ZodObject,...ne(e)});Ae.strictCreate=(t,e)=>new Ae({shape:()=>t,unknownKeys:"strict",catchall:Mt.create(),typeName:A.ZodObject,...ne(e)});Ae.lazycreate=(t,e)=>new Ae({shape:t,unknownKeys:"strip",catchall:Mt.create(),typeName:A.ZodObject,...ne(e)});class mn extends ie{_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 Qe(o.ctx.common.issues));return $(r,{code:I.invalid_union,unionErrors:i}),X}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 Qe(c));return $(r,{code:I.invalid_union,unionErrors:o}),X}}get options(){return this._def.options}}mn.create=(t,e)=>new mn({options:t,typeName:A.ZodUnion,...ne(e)});function ps(t,e){const r=Ct(t),n=Ct(e);if(t===e)return{valid:!0,data:t};if(r===M.object&&n===M.object){const a=ue.objectKeys(e),s=ue.objectKeys(t).filter(o=>a.indexOf(o)!==-1),i={...t,...e};for(const o of s){const c=ps(t[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(r===M.array&&n===M.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=ps(i,o);if(!c.valid)return{valid:!1};a.push(c.data)}return{valid:!0,data:a}}else return r===M.date&&n===M.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class gn extends ie{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),a=(s,i)=>{if($i(s)||$i(i))return X;const o=ps(s.value,i.value);return o.valid?((Pi(s)||Pi(i))&&r.dirty(),{status:r.value,value:o.data}):($(n,{code:I.invalid_intersection_types}),X)};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}))}}gn.create=(t,e,r)=>new gn({left:t,right:e,typeName:A.ZodIntersection,...ne(r)});class xt extends ie{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return $(n,{code:I.invalid_type,expected:M.array,received:n.parsedType}),X;if(n.data.length<this._def.items.length)return $(n,{code:I.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),X;!this._def.rest&&n.data.length>this._def.items.length&&($(n,{code:I.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 _t(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Fe.mergeArray(r,i)):Fe.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new xt({...this._def,rest:e})}}xt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new xt({items:t,typeName:A.ZodTuple,rest:null,...ne(e)})};class yn extends ie{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!==M.object)return $(n,{code:I.invalid_type,expected:M.object,received:n.parsedType}),X;const a=[],s=this._def.keyType,i=this._def.valueType;for(const o in n.data)a.push({key:s._parse(new _t(n,o,n.path,o)),value:i._parse(new _t(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?Fe.mergeObjectAsync(r,a):Fe.mergeObjectSync(r,a)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ie?new yn({keyType:e,valueType:r,typeName:A.ZodRecord,...ne(n)}):new yn({keyType:Et.create(),valueType:e,typeName:A.ZodRecord,...ne(r)})}}class Ui extends ie{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!==M.map)return $(n,{code:I.invalid_type,expected:M.map,received:n.parsedType}),X;const a=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([o,c],u)=>({key:a._parse(new _t(n,o,n.path,[u,"key"])),value:s._parse(new _t(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 X;(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 X;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(u.value,l.value)}return{status:r.value,value:o}}}}Ui.create=(t,e,r)=>new Ui({valueType:e,keyType:t,typeName:A.ZodMap,...ne(r)});class Mr extends ie{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return $(n,{code:I.invalid_type,expected:M.set,received:n.parsedType}),X;const a=this._def;a.minSize!==null&&n.data.size<a.minSize.value&&($(n,{code:I.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&&($(n,{code:I.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 X;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 _t(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,r){return new Mr({...this._def,minSize:{value:e,message:z.toString(r)}})}max(e,r){return new Mr({...this._def,maxSize:{value:e,message:z.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}Mr.create=(t,e)=>new Mr({valueType:t,minSize:null,maxSize:null,typeName:A.ZodSet,...ne(e)});class Or extends ie{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.function)return $(r,{code:I.invalid_type,expected:M.function,received:r.parsedType}),X;function n(o,c){return ds({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ls(),Nr].filter(u=>!!u),issueData:{code:I.invalid_arguments,argumentsError:c}})}function a(o,c){return ds({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ls(),Nr].filter(u=>!!u),issueData:{code:I.invalid_return_type,returnTypeError:c}})}const s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Lr){const o=this;return Ze(async function(...c){const u=new Qe([]),l=await o._def.args.parseAsync(c,s).catch(f=>{throw u.addIssue(n(c,f)),u}),d=await Reflect.apply(i,this,l);return await o._def.returns._def.type.parseAsync(d,s).catch(f=>{throw u.addIssue(a(d,f)),u})})}else{const o=this;return Ze(function(...c){const u=o._def.args.safeParse(c,s);if(!u.success)throw new Qe([n(c,u.error)]);const l=Reflect.apply(i,this,u.data),d=o._def.returns.safeParse(l,s);if(!d.success)throw new Qe([a(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Or({...this._def,args:xt.create(e).rest(or.create())})}returns(e){return new Or({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new Or({args:e||xt.create([]).rest(or.create()),returns:r||or.create(),typeName:A.ZodFunction,...ne(n)})}}class Fi extends ie{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})}}Fi.create=(t,e)=>new Fi({getter:t,typeName:A.ZodLazy,...ne(e)});class ms extends ie{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return $(r,{received:r.data,code:I.invalid_literal,expected:this._def.value}),X}return{status:"valid",value:e.data}}get value(){return this._def.value}}ms.create=(t,e)=>new ms({value:t,typeName:A.ZodLiteral,...ne(e)});function Fc(t,e){return new lr({values:t,typeName:A.ZodEnum,...ne(e)})}class lr extends ie{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return $(r,{expected:ue.joinValues(n),received:r.parsedType,code:I.invalid_type}),X}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 $(r,{received:r.data,code:I.invalid_enum_value,options:n}),X}return Ze(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 lr.create(e,{...this._def,...r})}exclude(e,r=this._def){return lr.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}lr.create=Fc;class Bi extends ie{_parse(e){const r=ue.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){const a=ue.objectValues(r);return $(n,{expected:ue.joinValues(a),received:n.parsedType,code:I.invalid_type}),X}if(this._cache||(this._cache=new Set(ue.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const a=ue.objectValues(r);return $(n,{received:n.data,code:I.invalid_enum_value,options:a}),X}return Ze(e.data)}get enum(){return this._def.values}}Bi.create=(t,e)=>new Bi({values:t,typeName:A.ZodNativeEnum,...ne(e)});class Lr extends ie{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.promise&&r.common.async===!1)return $(r,{code:I.invalid_type,expected:M.promise,received:r.parsedType}),X;const n=r.parsedType===M.promise?r.data:Promise.resolve(r.data);return Ze(n.then(a=>this._def.type.parseAsync(a,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Lr.create=(t,e)=>new Lr({type:t,typeName:A.ZodPromise,...ne(e)});class dr extends ie{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===A.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=>{$(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 X;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?X:c.status==="dirty"||r.value==="dirty"?xr(c.value):c});{if(r.value==="aborted")return X;const o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?X:o.status==="dirty"||r.value==="dirty"?xr(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"?X:(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"?X:(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(!cr(i))return X;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=>cr(i)?Promise.resolve(a.transform(i.value,s)).then(o=>({status:r.value,value:o})):X);ue.assertNever(a)}}dr.create=(t,e,r)=>new dr({schema:t,typeName:A.ZodEffects,effect:e,...ne(r)});dr.createWithPreprocess=(t,e,r)=>new dr({schema:e,effect:{type:"preprocess",transform:t},typeName:A.ZodEffects,...ne(r)});class $t extends ie{_parse(e){return this._getType(e)===M.undefined?Ze(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}$t.create=(t,e)=>new $t({innerType:t,typeName:A.ZodOptional,...ne(e)});class hr extends ie{_parse(e){return this._getType(e)===M.null?Ze(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}hr.create=(t,e)=>new hr({innerType:t,typeName:A.ZodNullable,...ne(e)});class gs extends ie{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}gs.create=(t,e)=>new gs({innerType:t,typeName:A.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ne(e)});class ys extends ie{_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 fn(a)?a.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Qe(n.common.issues)},input:n.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Qe(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}ys.create=(t,e)=>new ys({innerType:t,typeName:A.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ne(e)});class zi extends ie{_parse(e){if(this._getType(e)!==M.nan){const n=this._getOrReturnCtx(e);return $(n,{code:I.invalid_type,expected:M.nan,received:n.parsedType}),X}return{status:"valid",value:e.data}}}zi.create=t=>new zi({typeName:A.ZodNaN,...ne(t)});class _d extends ie{_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 Zs extends ie{_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"?X:s.status==="dirty"?(r.dirty(),xr(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"?X: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 Zs({in:e,out:r,typeName:A.ZodPipeline})}}class _s extends ie{_parse(e){const r=this._def.innerType._parse(e),n=a=>(cr(a)&&(a.value=Object.freeze(a.value)),a);return fn(r)?r.then(a=>n(a)):n(r)}unwrap(){return this._def.innerType}}_s.create=(t,e)=>new _s({innerType:t,typeName:A.ZodReadonly,...ne(e)});function qi(t,e){const r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function vd(t,e={},r){return t?Pr.create().superRefine((n,a)=>{const s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){const o=qi(e,n),c=o.fatal??r??!0;a.addIssue({code:"custom",...o,fatal:c})}});if(!s){const i=qi(e,n),o=i.fatal??r??!0;a.addIssue({code:"custom",...i,fatal:o})}}):Pr.create()}var A;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(A||(A={}));const E_=(t,e={message:`Input not instance of ${t.name}`})=>vd(r=>r instanceof t,e),Js=Et.create,T_=ur.create,S_=hs.create,x_=fs.create,Gi=Pr.create;or.create;Mt.create;const I_=pt.create,Ws=Ae.create,A_=mn.create;gn.create;xt.create;const O_=yn.create,k_=Or.create,R_=ms.create,C_=lr.create,N_=Lr.create;$t.create;hr.create;var wd=Object.defineProperty,pe=(t,e)=>{for(var r in e)wd(t,r,{get:e[r],enumerable:!0})};function Lt(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 Ks(t){return Lt(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function Ys(t){return Lt(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function bd(t){return Lt(t)&&t.source_type==="text"&&"text"in t&&typeof t.text=="string"}function Bc(t){return Lt(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}function zc(t){if(Lt(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 Ed(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 vs({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 Td(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 qc(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}var Jn,Hi;function Sd(){return Hi||(Hi=1,Jn=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()}),Jn}var xd=Sd();const Id=yr(xd);var Xr={exports:{}},Vi;function Ad(){if(Vi)return Xr.exports;Vi=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=(h,f,p)=>{let y=!1,_=!1,w=!1;for(let T=0;T<h.length;T++){const E=h[T];y&&t.test(E)?(h=h.slice(0,T)+"-"+h.slice(T),y=!1,w=_,_=!0,T++):_&&w&&e.test(E)?(h=h.slice(0,T-1)+"-"+h.slice(T-1),w=_,_=!1,y=!0):(y=f(E)===E&&p(E)!==E,w=_,_=p(E)===E&&f(E)!==E)}return h},u=(h,f)=>(r.lastIndex=0,h.replace(r,p=>f(p))),l=(h,f)=>(i.lastIndex=0,o.lastIndex=0,h.replace(i,(p,y)=>f(y)).replace(o,p=>f(p))),d=(h,f)=>{if(!(typeof h=="string"||Array.isArray(h)))throw new TypeError("Expected the input to be `string | string[]`");if(f={pascalCase:!1,preserveConsecutiveUppercase:!1,...f},Array.isArray(h)?h=h.map(w=>w.trim()).filter(w=>w.length).join("-"):h=h.trim(),h.length===0)return"";const p=f.locale===!1?w=>w.toLowerCase():w=>w.toLocaleLowerCase(f.locale),y=f.locale===!1?w=>w.toUpperCase():w=>w.toLocaleUpperCase(f.locale);return h.length===1?f.pascalCase?y(h):p(h):(h!==p(h)&&(h=c(h,p,y)),h=h.replace(s,""),f.preserveConsecutiveUppercase?h=u(h,p):h=p(h),f.pascalCase&&(h=y(h.charAt(0))+h.slice(1)),l(h,y))};return Xr.exports=d,Xr.exports.default=d,Xr.exports}var Od=Ad();const kd=yr(Od);function Rd(t,e){return e?.[t]||Id(t)}function $_(t,e){return e?.[t]||kd(t)}function Cd(t,e,r){const n={};for(const a in t)Object.hasOwn(t,a)&&(n[e(a,r)]=t[a]);return n}var Nd={};pe(Nd,{Serializable:()=>fr,get_lc_unique_name:()=>Xs});function Zi(t){return Array.isArray(t)?[...t]:{...t}}function $d(t,e){const r=Zi(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]=Zi(o[c]),o=o[c]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[a]})}return r}function Xs(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 Gc{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Xs(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 Gc||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:Cd(Object.keys(r).length?$d(n,r):n,Rd,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function V(t,e){return te(t)&&t.type===e}function te(t){return typeof t=="object"&&t!==null}function mt(t){return Array.isArray(t)}function L(t){return typeof t=="string"}function st(t){return typeof t=="number"}function Qs(t){return t instanceof Uint8Array}function Ji(t){try{return JSON.parse(t)}catch{return}}const jr=t=>t();function Pd(t){if(t.type==="char_location"&&L(t.document_title)&&st(t.start_char_index)&&st(t.end_char_index)&&L(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"&&L(t.document_title)&&st(t.start_page_number)&&st(t.end_page_number)&&L(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"&&L(t.document_title)&&st(t.start_block_index)&&st(t.end_block_index)&&L(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"&&L(t.url)&&L(t.title)&&L(t.encrypted_index)&&L(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"&&L(t.source)&&L(t.title)&&st(t.start_block_index)&&st(t.end_block_index)&&L(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(V(t,"document")&&te(t.source)&&"type"in t.source){if(t.source.type==="base64"&&L(t.source.media_type)&&L(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&L(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&L(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&L(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(V(t,"image")&&te(t.source)&&"type"in t.source){if(t.source.type==="base64"&&L(t.source.media_type)&&L(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&L(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&L(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}function Md(t){function*e(){for(const r of t){const n=Hc(r);n?yield n:yield r}}return Array.from(e())}function Wi(t){function*e(){const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r){if(V(n,"text")&&L(n.text)){const{text:a,citations:s,...i}=n;if(mt(s)&&s.length){const o=s.reduce((c,u)=>{const l=Pd(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(V(n,"thinking")&&L(n.thinking)){const{thinking:a,signature:s,...i}=n;yield{...i,type:"reasoning",reasoning:a,signature:s};continue}else if(V(n,"redacted_thinking")){yield{type:"non_standard",value:n};continue}else if(V(n,"tool_use")&&L(n.name)&&L(n.id)){yield{type:"tool_call",id:n.id,name:n.name,args:n.input};continue}else if(V(n,"input_json_delta")){if(jd(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(V(n,"server_tool_use")&&L(n.name)&&L(n.id)){const{name:a,id:s}=n;if(a==="web_search"){const i=jr(()=>{if(typeof n.input=="string")return n.input;if(te(n.input)&&L(n.input.query))return n.input.query;if(L(n.partial_json)){const o=Ji(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=jr(()=>{if(typeof n.input=="string")return n.input;if(te(n.input)&&L(n.input.code))return n.input.code;if(L(n.partial_json)){const o=Ji(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(V(n,"web_search_tool_result")&&L(n.tool_use_id)&&mt(n.content)){const{content:a,tool_use_id:s}=n,i=a.reduce((o,c)=>V(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(V(n,"code_execution_tool_result")&&L(n.tool_use_id)&&te(n.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(V(n,"mcp_tool_use")){yield{id:n.id,type:"server_tool_call",name:"mcp_tool_use",args:n.input};continue}else if(V(n,"mcp_tool_result")&&L(n.tool_use_id)&&te(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(V(n,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:n.input};continue}else if(V(n,"search_result")){yield{id:n.id,type:"non_standard",value:n};continue}else if(V(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 Ld={translateContent:Wi,translateContentChunk:Wi};function jd(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}function Dd(t){return Ks(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:Ys(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:Bc(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}function Ud(t){return t.map(Dd)}function Fd(t){return!!(V(t,"image_url")&&te(t.image_url)||V(t,"input_audio")&&te(t.input_audio)||V(t,"file")&&te(t.file))}function Bd(t){if(V(t,"image_url")&&te(t.image_url)&&L(t.image_url.url)){const e=vs({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(V(t,"input_audio")&&te(t.input_audio)&&L(t.input_audio.data)&&L(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(V(t,"file")&&te(t.file)&&L(t.file.data)){const e=vs({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(L(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}function zd(t){const e=[];typeof t.content=="string"?e.push({type:"text",text:t.content}):e.push(...ei(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 qd(t){const e=[];typeof t.content=="string"?e.push({type:"text",text:t.content}):e.push(...ei(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 ei(t){const e=[];for(const r of t)Fd(r)?e.push(Bd(r)):e.push(r);return e}function Gd(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 Vc(t){function*e(){te(t.additional_kwargs?.reasoning)&&mt(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((a,s)=>te(s)&&L(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(V(n,"text")){const{text:a,annotations:s,...i}=n;Array.isArray(s)?yield{...i,type:"text",text:String(a),annotations:s.map(Gd)}: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(te(t.additional_kwargs)&&mt(t.additional_kwargs.tool_outputs))for(const n of t.additional_kwargs.tool_outputs){if(V(n,"web_search_call")){yield{id:n.id,type:"server_tool_call",name:"web_search",args:{query:n.query}};continue}else if(V(n,"file_search_call")){yield{id:n.id,type:"server_tool_call",name:"file_search",args:{query:n.query}};continue}else if(V(n,"computer_call")){yield{type:"non_standard",value:n};continue}else if(V(n,"code_interpreter_call")){if(L(n.code)&&(yield{id:n.id,type:"server_tool_call",name:"code_interpreter",args:{code:n.code}}),mt(n.outputs)){const a=jr(()=>{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(V(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(V(n,"mcp_call")){yield{id:n.id,type:"server_tool_call",name:"mcp_call",args:n.input};continue}else if(V(n,"mcp_list_tools")){yield{id:n.id,type:"server_tool_call",name:"mcp_list_tools",args:n.input};continue}else if(V(n,"mcp_approval_request")){yield{type:"non_standard",value:n};continue}else if(V(n,"image_generation_call")){yield{type:"non_standard",value:n};continue}te(n)&&(yield{type:"non_standard",value:n})}}return Array.from(e())}function Hd(t){function*e(){yield*Vc(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 Vd={translateContent:t=>typeof t.content=="string"?zd(t):Vc(t),translateContentChunk:t=>typeof t.content=="string"?qd(t):Hd(t)};function Zd(t,e="pretty"){return e==="pretty"?Jd(t):JSON.stringify(t)}function Jd(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 Wn=Symbol.for("langchain.message");function Kt(t,e){return typeof t=="string"?t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.some(r=>Lt(r))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e]:Array.isArray(e)?qr(t,e)??[...t,...e]:e===""?t:Array.isArray(t)&&t.some(r=>Lt(r))?[...t,{type:"file",source_type:"text",text:e}]:[...t,{type:"text",text:e}]}function Zc(t,e){return t==="error"||e==="error"?"error":"success"}function Wd(t,e){function r(n,a){if(typeof n!="object"||n===null||n===void 0)return n;if(a>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(i=>r(i,a+1));const s={};for(const i of Object.keys(n))s[i]=r(n[i],a+1);return s}return JSON.stringify(r(t,0),null,2)}var At=class extends fr{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[Wn]=!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[Ud,ei,Md].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&&Wn in t&&t[Wn]===!0&&qc(t)}_updateId(t){this.id=t,this.lc_kwargs.id=t}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](t){if(t===null)return this;const e=Wd(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return Zd(this,t)}};function Kd(t){return Array.isArray(t)&&t.every(e=>typeof e.index=="number")}function Me(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]=Me(r[n],a);else if(Array.isArray(r[n]))r[n]=qr(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 qr(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]=Me(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 Jc(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
+ 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 qr(t,e);if(typeof t=="object"&&typeof e=="object")return Me(t,e);if(t===e)return t;throw new Error(`Can not merge objects of different types.
7
+ Left ${t}
8
+ Right ${e}`)}var Yt=class extends At{static isInstance(t){return super.isInstance(t)&&"concat"in t&&typeof t.concat=="function"}};function Wc(t){return typeof t.role=="string"}function Tt(t){return typeof t?._getType=="function"}function ti(t){return Tt(t)&&typeof t.concat=="function"}function Kc(t,e){return Me(t??{},e??{})}function Yc(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 Yd(t,e){const r={...Yc(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 Xd(t,e){const r={...Yc(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(r.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),r}function Xc(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:Yd(t?.input_token_details,e?.input_token_details),output_token_details:Xd(t?.output_token_details,e?.output_token_details)}}var Qd={};pe(Qd,{ToolMessage:()=>_r,ToolMessageChunk:()=>Rn,defaultToolCallParser:()=>ri,isDirectToolOutput:()=>Qc,isToolMessage:()=>eu,isToolMessageChunk:()=>tu});function Qc(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}var _r=class extends At{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}}},Rn=class extends Yt{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:Kt(this.content,t.content),additional_kwargs:Me(this.additional_kwargs,t.additional_kwargs),response_metadata:Me(this.response_metadata,t.response_metadata),artifact:Jc(this.artifact,t.artifact),tool_call_id:this.tool_call_id,id:this.id??t.id,status:Zc(this.status,t.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function ri(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 eu(t){return typeof t=="object"&&t!==null&&"getType"in t&&typeof t.getType=="function"&&t.getType()==="tool"}function tu(t){return t._getType()==="tool"}function ws(t,e=ni){t=t.trim();const r=t.indexOf("```");if(r===-1)return e(t);let n=t.substring(r+3);n.startsWith(`json
9
+ `)?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 ni(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 ai(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 eh(t){if(te(t.document)&&te(t.document.source)){const e=te(t.document)&&L(t.document.format)?t.document.format:"",r=ai(e);if(te(t.document.source)){if(te(t.document.source.s3Location)&&L(t.document.source.s3Location.uri))return{type:"file",mimeType:r,fileId:t.document.source.s3Location.uri};if(Qs(t.document.source.bytes))return{type:"file",mimeType:r,data:t.document.source.bytes};if(L(t.document.source.text))return{type:"file",mimeType:r,data:Buffer.from(t.document.source.text).toString("base64")};if(mt(t.document.source.content)){const n=t.document.source.content.reduce((a,s)=>te(s)&&L(s.text)?a+s.text:a,"");return{type:"file",mimeType:r,data:n}}}}return{type:"non_standard",value:t}}function th(t){if(V(t,"image")&&te(t.image)){const e=te(t.image)&&L(t.image.format)?t.image.format:"",r=ai(e);if(te(t.image.source)){if(te(t.image.source.s3Location)&&L(t.image.source.s3Location.uri))return{type:"image",mimeType:r,fileId:t.image.source.s3Location.uri};if(Qs(t.image.source.bytes))return{type:"image",mimeType:r,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}function rh(t){if(V(t,"video")&&te(t.video)){const e=te(t.video)&&L(t.video.format)?t.video.format:"",r=ai(e);if(te(t.video.source)){if(te(t.video.source.s3Location)&&L(t.video.source.s3Location.uri))return{type:"video",mimeType:r,fileId:t.video.source.s3Location.uri};if(Qs(t.video.source.bytes))return{type:"video",mimeType:r,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}function Ki(t){function*e(){const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r){if(V(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(V(n,"citations_content")&&te(n.citationsContent)){const a=mt(n.citationsContent.content)?n.citationsContent.content.reduce((i,o)=>te(o)&&L(o.text)?i+o.text:i,""):"",s=mt(n.citationsContent.citations)?n.citationsContent.citations.reduce((i,o)=>{if(te(o)){const c=mt(o.sourceContent)?o.sourceContent.reduce((l,d)=>te(d)&&L(d.text)?l+d.text:l,""):"",u=jr(()=>{if(te(o.location)){const l=o.location.documentChar||o.location.documentPage||o.location.documentChunk;if(te(l))return{source:st(l.documentIndex)?l.documentIndex.toString():void 0,startIndex:st(l.start)?l.start:void 0,endIndex:st(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(V(n,"document")&&te(n.document)){yield eh(n);continue}else if(V(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(V(n,"image")&&te(n.image)){yield th(n);continue}else if(V(n,"reasoning_content")&&L(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(V(n,"text")&&L(n.text)){yield{type:"text",text:n.text};continue}else if(V(n,"tool_result")){yield{type:"non_standard",value:n};continue}else{if(V(n,"tool_call"))continue;if(V(n,"video")&&te(n.video)){yield rh(n);continue}}yield{type:"non_standard",value:n}}}return Array.from(e())}const nh={translateContent:Ki,translateContentChunk:Ki};function Yi(t){function*e(){const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r){if(V(n,"text")&&L(n.text)){yield{type:"text",text:n.text};continue}else if(V(n,"inlineData")&&te(n.inlineData)&&L(n.inlineData.mimeType)&&L(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(V(n,"functionCall")&&te(n.functionCall)&&L(n.functionCall.name)&&te(n.functionCall.args)){yield{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(V(n,"functionResponse")){yield{type:"non_standard",value:n};continue}else if(V(n,"fileData")&&te(n.fileData)&&L(n.fileData.mimeType)&&L(n.fileData.fileUri)){yield{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(V(n,"executableCode")){yield{type:"non_standard",value:n};continue}else if(V(n,"codeExecutionResult")){yield{type:"non_standard",value:n};continue}yield{type:"non_standard",value:n}}}return Array.from(e())}const ah={translateContent:Yi,translateContentChunk:Yi};function Xi(t){function*e(){const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r){if(V(n,"reasoning")&&L(n.reasoning)){const a=jr(()=>{const s=r.indexOf(n);if(mt(t.additional_kwargs?.signatures)&&s>=0)return t.additional_kwargs.signatures.at(s)});L(a)?yield{type:"reasoning",reasoning:n.reasoning,signature:a}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(V(n,"text")&&L(n.text)){yield{type:"text",text:n.text};continue}else if(V(n,"image_url")){if(L(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(V(n,"media")&&L(n.mimeType)&&L(n.data)){yield{type:"file",mimeType:n.mimeType,data:n.data};continue}yield{type:"non_standard",value:n}}}return Array.from(e())}const sh={translateContent:Xi,translateContentChunk:Xi};globalThis.lc_block_translators_registry??=new Map([["anthropic",Ld],["bedrock-converse",nh],["google-genai",ah],["google-vertexai",sh],["openai",Vd]]);function ru(t){return globalThis.lc_block_translators_registry.get(t)}var jt=class extends At{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
+
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]=ri(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=ru(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 nu(t){return t._getType()==="ai"}function bs(t){return t._getType()==="ai"}var Xt=class extends Yt{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(h=>h.args||"").join(""),l=u.length?u:"{}",d=i[0]?.id;try{if(o=ni(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=ru(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:Kt(this.content,t.content),additional_kwargs:Me(this.additional_kwargs,t.additional_kwargs),response_metadata:Kc(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=qr(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=Xc(this.usage_metadata,t.usage_metadata));const r=this.constructor;return new r(e)}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}},Gr=class au extends At{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return au}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}}},Cn=class extends Yt{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:Kt(this.content,t.content),additional_kwargs:Me(this.additional_kwargs,t.additional_kwargs),response_metadata:Me(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 ih(t){return t._getType()==="generic"}function oh(t){return t._getType()==="generic"}var Nn=class extends At{static lc_name(){return"FunctionMessage"}type="function";name;constructor(t){super(t),this.name=t.name}},$n=class extends Yt{static lc_name(){return"FunctionMessageChunk"}type="function";concat(t){const e=this.constructor;return new e({content:Kt(this.content,t.content),additional_kwargs:Me(this.additional_kwargs,t.additional_kwargs),response_metadata:Me(this.response_metadata,t.response_metadata),name:this.name??"",id:this.id??t.id})}};function ch(t){return t._getType()==="function"}function uh(t){return t._getType()==="function"}var Ot=class extends At{static lc_name(){return"HumanMessage"}type="human";constructor(t){super(t)}static isInstance(t){return super.isInstance(t)&&t.type==="human"}},Pn=class extends Yt{static lc_name(){return"HumanMessageChunk"}type="human";constructor(t){super(t)}concat(t){const e=this.constructor;return new e({content:Kt(this.content,t.content),additional_kwargs:Me(this.additional_kwargs,t.additional_kwargs),response_metadata:Me(this.response_metadata,t.response_metadata),id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="human"}};function lh(t){return t.getType()==="human"}function dh(t){return t.getType()==="human"}var Dt=class extends At{static lc_name(){return"SystemMessage"}type="system";constructor(t){super(t)}static isInstance(t){return super.isInstance(t)&&t.type==="system"}},pr=class extends Yt{static lc_name(){return"SystemMessageChunk"}type="system";constructor(t){super(t)}concat(t){const e=this.constructor;return new e({content:Kt(this.content,t.content),additional_kwargs:Me(this.additional_kwargs,t.additional_kwargs),response_metadata:Me(this.response_metadata,t.response_metadata),id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="system"}};function hh(t){return t._getType()==="system"}function fh(t){return t._getType()==="system"}var _n=class extends At{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 su(t,e){return t.lc_error_code=e,t.message=`${t.message}
14
+
15
+ Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
16
+ `,t}function iu(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function P_(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 ph=class extends Error{output;constructor(t,e){super(t),this.output=e}};const mh=t=>t();function gh(t){return iu(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 yh(t){return typeof t=="object"&&t!=null&&t.lc===1&&Array.isArray(t.id)&&t.kwargs!=null&&typeof t.kwargs=="object"}function Kn(t){let e,r;if(yh(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 Ot(r);if(e==="ai"||e==="assistant"){const{tool_calls:n,...a}=r;if(!Array.isArray(n))return new jt(r);const s=n.map(gh);return new jt({...a,tool_calls:s})}else{if(e==="system")return new Dt(r);if(e==="developer")return new Dt({...r,additional_kwargs:{...r.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in r)return new _r({...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 _n({...r,id:r.id});throw su(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
17
+
18
+ Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function kr(t){if(typeof t=="string")return new Ot(t);if(Tt(t))return t;if(Array.isArray(t)){const[e,r]=t;return Kn({type:e,content:r})}else if(Wc(t)){const{role:e,...r}=t;return Kn({...r,type:e})}else return Kn(t)}function si(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 _h(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 ii(t){const e=_h(t);switch(e.type){case"human":return new Ot(e.data);case"ai":return new jt(e.data);case"system":return new Dt(e.data);case"function":if(e.data.name===void 0)throw new Error("Name must be defined for function messages");return new Nn(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 _r(e.data);case"generic":if(e.data.role===void 0)throw new Error("Role must be defined for chat messages");return new Gr(e.data);default:throw new Error(`Got unexpected type: ${e.type}`)}}function vh(t){return t.map(ii)}function wh(t){return t.map(e=>e.toDict())}function vn(t){const e=t._getType();if(e==="human")return new Pn({...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 Xt({...r})}else{if(e==="system")return new pr({...t});if(e==="function")return new $n({...t});if(Gr.isInstance(t))return new Cn({...t});throw new Error("Unknown message type.")}}const ou=Symbol.for("ls:tracing_async_local_storage"),Rr=Symbol.for("lc:context_variables"),bh=t=>{globalThis[ou]=t},Dr=()=>globalThis[ou];var Eh={},Th={};pe(Th,{getEnv:()=>hu,getEnvironmentVariable:()=>Pt,getRuntimeEnvironment:()=>fu,isBrowser:()=>cu,isDeno:()=>Mn,isJsDom:()=>lu,isNode:()=>du,isWebWorker:()=>uu});const cu=()=>typeof window<"u"&&typeof window.document<"u",uu=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",lu=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Mn=()=>typeof Deno<"u",du=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Mn(),hu=()=>{let t;return cu()?t="browser":du()?t="node":uu()?t="webworker":lu()?t="jsdom":Mn()?t="deno":t="other",t};let Yn;function fu(){return Yn===void 0&&(Yn={library:"langchain-js",runtime:hu()}),Yn}function Pt(t){try{return typeof process<"u"?Eh?.[t]:Mn()?Deno?.env.get(t):void 0}catch{return}}const Sh=/^(?:[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 Cr(t){return typeof t=="string"&&Sh.test(t)}function xh(t){if(!Cr(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 Pe=[];for(var Xn=0;Xn<256;++Xn)Pe.push((Xn+256).toString(16).slice(1));function pu(t,e=0){return(Pe[t[e+0]]+Pe[t[e+1]]+Pe[t[e+2]]+Pe[t[e+3]]+"-"+Pe[t[e+4]]+Pe[t[e+5]]+"-"+Pe[t[e+6]]+Pe[t[e+7]]+"-"+Pe[t[e+8]]+Pe[t[e+9]]+"-"+Pe[t[e+10]]+Pe[t[e+11]]+Pe[t[e+12]]+Pe[t[e+13]]+Pe[t[e+14]]+Pe[t[e+15]]).toLowerCase()}var Qr,Ih=new Uint8Array(16);function Ah(){if(!Qr&&(Qr=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Qr))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Qr(Ih)}function Oh(t){t=unescape(encodeURIComponent(t));for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var kh="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Rh="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Ch(t,e,r){function n(a,s,i,o){var c;if(typeof a=="string"&&(a=Oh(a)),typeof s=="string"&&(s=xh(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 pu(u)}try{n.name=t}catch{}return n.DNS=kh,n.URL=Rh,n}var Nh=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Qi={randomUUID:Nh};function Ue(t,e,r){if(Qi.randomUUID&&!t)return Qi.randomUUID();t=t||{};var n=t.random||(t.rng||Ah)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,pu(n)}function $h(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 Qn(t,e){return t<<e|t>>>32-e}function Ph(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 h=new Uint32Array(80),f=0;f<16;++f)h[f]=o[d][f];for(var p=16;p<80;++p)h[p]=Qn(h[p-3]^h[p-8]^h[p-14]^h[p-16],1);for(var y=r[0],_=r[1],w=r[2],T=r[3],E=r[4],x=0;x<80;++x){var R=Math.floor(x/20),j=Qn(y,5)+$h(R,_,w,T)+E+e[R]+h[x]>>>0;E=T,T=w,w=Qn(_,30)>>>0,_=y,y=j}r[0]=r[0]+y>>>0,r[1]=r[1]+_>>>0,r[2]=r[2]+w>>>0,r[3]=r[3]+T>>>0,r[4]=r[4]+E>>>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 eo=Ch("v5",80,Ph),Mh={};pe(Mh,{BaseCallbackHandler:()=>Hr,callbackHandlerPrefersStreaming:()=>mu,isBaseCallbackHandler:()=>gu});var Lh=class{};function mu(t){return"lc_prefer_streaming"in t&&t.lc_prefer_streaming}var Hr=class extends Lh{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,Xs(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Pt("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 Hr{name=Ue();constructor(){super(),Object.assign(this,t)}}return new e}};const gu=t=>{const e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},jh="gen_ai.operation.name",Dh="gen_ai.system",to="gen_ai.request.model",Uh="gen_ai.response.model",ro="gen_ai.usage.input_tokens",no="gen_ai.usage.output_tokens",ao="gen_ai.usage.total_tokens",Fh="gen_ai.request.max_tokens",Bh="gen_ai.request.temperature",zh="gen_ai.request.top_p",qh="gen_ai.request.frequency_penalty",Gh="gen_ai.request.presence_penalty",Hh="gen_ai.response.finish_reasons",Vh="gen_ai.prompt",Zh="gen_ai.completion",Jh="gen_ai.request.extra_query",Wh="gen_ai.request.extra_body",Kh="gen_ai.serialized.name",Yh="gen_ai.serialized.signature",Xh="gen_ai.serialized.doc",Qh="gen_ai.response.id",ef="gen_ai.response.service_tier",tf="gen_ai.response.system_fingerprint",rf="gen_ai.usage.input_token_details",nf="gen_ai.usage.output_token_details",af="langsmith.trace.session_id",sf="langsmith.trace.session_name",of="langsmith.span.kind",cf="langsmith.trace.name",uf="langsmith.metadata",so="langsmith.span.tags",lf="langsmith.request.streaming",df="langsmith.request.headers",hf=(...t)=>fetch(...t),yu=Symbol.for("ls:fetch_implementation"),ff=()=>{const t=globalThis[yu];return t?typeof t=="function"&&"Headers"in t&&"Request"in t&&"Response"in t:!1},pf=t=>async(...e)=>{if(t||He("DEBUG")==="true"){const[n,a]=e;console.log(`→ ${a?.method||"GET"} ${n}`)}const r=await(globalThis[yu]??hf)(...e);return(t||He("DEBUG")==="true")&&console.log(`← ${r.status} ${r.statusText} ${r.url}`),r},_u=()=>He("PROJECT")??vt("LANGCHAIN_SESSION")??"default",vu="0.3.79";var Es={};let ht;const mf=()=>typeof window<"u"&&typeof window.document<"u",gf=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",yf=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),wu=()=>typeof Deno<"u",_f=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!wu(),bu=()=>ht||(typeof Bun<"u"?ht="bun":mf()?ht="browser":_f()?ht="node":gf()?ht="webworker":yf()?ht="jsdom":wu()?ht="deno":ht="other",ht);let ea;function Eu(){if(ea===void 0){const t=bu(),e=wf();ea={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:vu,...e}}return ea}function Tu(){const t=vf(),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 vf(){const t={};try{if(typeof process<"u"&&Es)for(const[e,r]of Object.entries(Es))(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 vt(t){try{return typeof process<"u"?Es?.[t]:void 0}catch{return}}function He(t){return vt(`LANGSMITH_${t}`)||vt(`LANGCHAIN_${t}`)}let ta;function wf(){if(ta!==void 0)return ta;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=vt(r);n!==void 0&&(e[r]=n)}return ta=e,e}function Su(){return vt("OTEL_ENABLED")==="true"||He("OTEL_ENABLED")==="true"}class bf{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...r){!this.hasWarned&&Su()&&(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 Ef{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new bf})}getTracer(e,r){return this.mockTracer}getActiveSpan(){}setSpan(e,r){return e}getSpan(e){}setSpanContext(e,r){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}}class Tf{active(){return{}}with(e,r){return r()}}const ra=Symbol.for("ls:otel_trace"),na=Symbol.for("ls:otel_context"),io=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),Sf=new Ef,xf=new Tf;class If{getTraceInstance(){return globalThis[ra]??Sf}getContextInstance(){return globalThis[na]??xf}initializeGlobalInstances(e){globalThis[ra]===void 0&&(globalThis[ra]=e.trace),globalThis[na]===void 0&&(globalThis[na]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[io]=e}getDefaultOTLPTracerComponents(){return globalThis[io]??void 0}}const oi=new If;function xu(){return oi.getTraceInstance()}function Af(){return oi.getContextInstance()}function Of(){return oi.getDefaultOTLPTracerComponents()}const kf={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function Rf(t){return kf[t]||t}class Cf{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&&xu().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(of,r.run_type);const o=Rf(r.run_type||"chain");e.setAttribute(jh,o)}"name"in r&&r.name&&e.setAttribute(cf,r.name),"session_id"in r&&r.session_id&&e.setAttribute(af,r.session_id),"session_name"in r&&r.session_name&&e.setAttribute(sf,r.session_name),this.setGenAiSystem(e,r);const a=this.extractModelName(r);a&&e.setAttribute(to,a),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&e.setAttribute(ro,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&e.setAttribute(no,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&e.setAttribute(ao,r.total_tokens),this.setInvocationParameters(e,r);const s=r.extra?.metadata||{};for(const[o,c]of Object.entries(s))c!=null&&e.setAttribute(`${uf}.${o}`,String(c));const i=r.tags;if(i&&Array.isArray(i)?e.setAttribute(so,i.join(", ")):i&&e.setAttribute(so,String(i)),"serialized"in r&&typeof r.serialized=="object"){const o=r.serialized;o.name&&e.setAttribute(Kh,String(o.name)),o.signature&&e.setAttribute(Yh,String(o.signature)),o.doc&&e.setAttribute(Xh,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(Dh,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(Fh,n.max_tokens),n.temperature!==void 0&&e.setAttribute(Bh,n.temperature),n.top_p!==void 0&&e.setAttribute(zh,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(qh,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(Gh,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(to,n.model),n.stream!==void 0&&e.setAttribute(lf,n.stream),n.extra_headers&&e.setAttribute(df,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(Jh,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(Wh,JSON.stringify(n.extra_body))),e.setAttribute(Vh,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(ro,a[0]),e.setAttribute(no,a[1]),e.setAttribute(ao,a[0]+a[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(Uh,String(n.model)),n.id&&e.setAttribute(Qh,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(Hh,s.join(", "))}if(n.service_tier&&e.setAttribute(ef,n.service_tier),n.system_fingerprint&&e.setAttribute(tf,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){const s=n.usage_metadata;s.input_token_details&&e.setAttribute(rf,JSON.stringify(s.input_token_details)),s.output_token_details&&e.setAttribute(nf,JSON.stringify(s.output_token_details))}}e.setAttribute(Zh,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 Tr={exports:{}},aa={},sa,oo;function Nf(){if(oo)return sa;oo=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 sa=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},sa}var co;function $f(){return co||(co=1,(function(t){var e=Nf();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),h=Array.prototype.slice.call(arguments,1),f=h.pop();h.push(function(p){d.retry(p)||(p&&(arguments[0]=d.mainError()),f.apply(this,arguments))}),d.attempt(function(){l.apply(r,h)})}).bind(r,c),r[o].options=n}}})(aa)),aa}var ia,uo;function Pf(){return uo||(uo=1,ia=$f()),ia}var lo;function Mf(){if(lo)return Tr.exports;lo=1;const t=Pf(),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(h){if(!(h instanceof Error)){u(new TypeError(`Non-error was thrown: "${h}". You should only throw errors.`));return}if(h instanceof r)l.stop(),u(h.originalError);else if(h instanceof TypeError&&!a(h.message))l.stop(),u(h);else{n(h,d,o);try{await o.onFailedAttempt(h)}catch(f){u(f);return}l.retry(h)||u(l.mainError())}}})});return Tr.exports=s,Tr.exports.default=s,Tr.exports.AbortError=r,Tr.exports}var Lf=Mf();const wn=yr(Lf);var en={},oa={exports:{}},ho;function jf(){return ho||(ho=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,h){if(typeof l!="function")throw new TypeError("The listener must be a function");var f=new a(l,d||c,h),p=r?r+u:u;return c._events[p]?c._events[p].fn?c._events[p]=[c._events[p],f]:c._events[p].push(f):(c._events[p]=f,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 h=0,f=d.length,p=new Array(f);h<f;h++)p[h]=d[h].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,h,f,p){var y=r?r+u:u;if(!this._events[y])return!1;var _=this._events[y],w=arguments.length,T,E;if(_.fn){switch(_.once&&this.removeListener(u,_.fn,void 0,!0),w){case 1:return _.fn.call(_.context),!0;case 2:return _.fn.call(_.context,l),!0;case 3:return _.fn.call(_.context,l,d),!0;case 4:return _.fn.call(_.context,l,d,h),!0;case 5:return _.fn.call(_.context,l,d,h,f),!0;case 6:return _.fn.call(_.context,l,d,h,f,p),!0}for(E=1,T=new Array(w-1);E<w;E++)T[E-1]=arguments[E];_.fn.apply(_.context,T)}else{var x=_.length,R;for(E=0;E<x;E++)switch(_[E].once&&this.removeListener(u,_[E].fn,void 0,!0),w){case 1:_[E].fn.call(_[E].context);break;case 2:_[E].fn.call(_[E].context,l);break;case 3:_[E].fn.call(_[E].context,l,d);break;case 4:_[E].fn.call(_[E].context,l,d,h);break;default:if(!T)for(R=1,T=new Array(w-1);R<w;R++)T[R-1]=arguments[R];_[E].fn.apply(_[E].context,T)}}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,h){var f=r?r+u:u;if(!this._events[f])return this;if(!l)return i(this,f),this;var p=this._events[f];if(p.fn)p.fn===l&&(!h||p.once)&&(!d||p.context===d)&&i(this,f);else{for(var y=0,_=[],w=p.length;y<w;y++)(p[y].fn!==l||h&&!p[y].once||d&&p[y].context!==d)&&_.push(p[y]);_.length?this._events[f]=_.length===1?_[0]:_:i(this,f)}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})(oa)),oa.exports}var Sr={exports:{}},ca,fo;function Df(){return fo||(fo=1,ca=(t,e)=>(e=e||(()=>{}),t.then(r=>new Promise(n=>{n(e())}).then(()=>r),r=>new Promise(n=>{n(e())}).then(()=>{throw r})))),ca}var po;function Uf(){if(po)return Sr.exports;po=1;const t=Df();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 Sr.exports=r,Sr.exports.default=r,Sr.exports.TimeoutError=e,Sr.exports}var tn={},rn={},mo;function Ff(){if(mo)return rn;mo=1,Object.defineProperty(rn,"__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 rn.default=t,rn}var go;function Bf(){if(go)return tn;go=1,Object.defineProperty(tn,"__esModule",{value:!0});const t=Ff();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 tn.default=e,tn}var yo;function zf(){if(yo)return en;yo=1,Object.defineProperty(en,"__esModule",{value:!0});const t=jf(),e=Uf(),r=Bf(),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 h=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 h)}catch(h){l(h)}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 en.default=s,en}var qf=zf();const St=yr(qf),Gf=[429,500,502,503,504];let _o=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 St?this.queue=new St.default({concurrency:this.maxConcurrency}):this.queue=new St({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...r){const n=this.onFailedResponseHook;return this.queue.add(()=>wn(()=>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&&!Gf.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 vo(t){return typeof t?._getType=="function"}function wo(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 Hf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function re(t,e){if(!Hf.test(t)){const r=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(r)}return t}const bo={};function Ts(t){bo[t]||(console.warn(t),bo[t]=!0)}var nn={exports:{}},ua,Eo;function Ln(){if(Eo)return ua;Eo=1;const t="2.0.0",e=256,r=Number.MAX_SAFE_INTEGER||9007199254740991,n=16,a=e-6;return ua={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},ua}var la,To;function jn(){if(To)return la;To=1;var t={};return la=typeof process=="object"&&t&&t.NODE_DEBUG&&/\bsemver\b/i.test(t.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{},la}var So;function Vr(){return So||(So=1,(function(t,e){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:a}=Ln(),s=jn();e=t.exports={};const i=e.re=[],o=e.safeRe=[],c=e.src=[],u=e.safeSrc=[],l=e.t={};let d=0;const h="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",a],[h,n]],p=_=>{for(const[w,T]of f)_=_.split(`${w}*`).join(`${w}{0,${T}}`).split(`${w}+`).join(`${w}{1,${T}}`);return _},y=(_,w,T)=>{const E=p(w),x=d++;s(_,x,w),l[_]=x,c[x]=w,u[x]=E,i[x]=new RegExp(w,T?"g":void 0),o[x]=new RegExp(E,T?"g":void 0)};y("NUMERICIDENTIFIER","0|[1-9]\\d*"),y("NUMERICIDENTIFIERLOOSE","\\d+"),y("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${h}*`),y("MAINVERSION",`(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})`),y("MAINVERSIONLOOSE",`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})`),y("PRERELEASEIDENTIFIER",`(?:${c[l.NONNUMERICIDENTIFIER]}|${c[l.NUMERICIDENTIFIER]})`),y("PRERELEASEIDENTIFIERLOOSE",`(?:${c[l.NONNUMERICIDENTIFIER]}|${c[l.NUMERICIDENTIFIERLOOSE]})`),y("PRERELEASE",`(?:-(${c[l.PRERELEASEIDENTIFIER]}(?:\\.${c[l.PRERELEASEIDENTIFIER]})*))`),y("PRERELEASELOOSE",`(?:-?(${c[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[l.PRERELEASEIDENTIFIERLOOSE]})*))`),y("BUILDIDENTIFIER",`${h}+`),y("BUILD",`(?:\\+(${c[l.BUILDIDENTIFIER]}(?:\\.${c[l.BUILDIDENTIFIER]})*))`),y("FULLPLAIN",`v?${c[l.MAINVERSION]}${c[l.PRERELEASE]}?${c[l.BUILD]}?`),y("FULL",`^${c[l.FULLPLAIN]}$`),y("LOOSEPLAIN",`[v=\\s]*${c[l.MAINVERSIONLOOSE]}${c[l.PRERELEASELOOSE]}?${c[l.BUILD]}?`),y("LOOSE",`^${c[l.LOOSEPLAIN]}$`),y("GTLT","((?:<|>)?=?)"),y("XRANGEIDENTIFIERLOOSE",`${c[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),y("XRANGEIDENTIFIER",`${c[l.NUMERICIDENTIFIER]}|x|X|\\*`),y("XRANGEPLAIN",`[v=\\s]*(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:${c[l.PRERELEASE]})?${c[l.BUILD]}?)?)?`),y("XRANGEPLAINLOOSE",`[v=\\s]*(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:${c[l.PRERELEASELOOSE]})?${c[l.BUILD]}?)?)?`),y("XRANGE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAIN]}$`),y("XRANGELOOSE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAINLOOSE]}$`),y("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),y("COERCE",`${c[l.COERCEPLAIN]}(?:$|[^\\d])`),y("COERCEFULL",c[l.COERCEPLAIN]+`(?:${c[l.PRERELEASE]})?(?:${c[l.BUILD]})?(?:$|[^\\d])`),y("COERCERTL",c[l.COERCE],!0),y("COERCERTLFULL",c[l.COERCEFULL],!0),y("LONETILDE","(?:~>?)"),y("TILDETRIM",`(\\s*)${c[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",y("TILDE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAIN]}$`),y("TILDELOOSE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAINLOOSE]}$`),y("LONECARET","(?:\\^)"),y("CARETTRIM",`(\\s*)${c[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",y("CARET",`^${c[l.LONECARET]}${c[l.XRANGEPLAIN]}$`),y("CARETLOOSE",`^${c[l.LONECARET]}${c[l.XRANGEPLAINLOOSE]}$`),y("COMPARATORLOOSE",`^${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]})$|^$`),y("COMPARATOR",`^${c[l.GTLT]}\\s*(${c[l.FULLPLAIN]})$|^$`),y("COMPARATORTRIM",`(\\s*)${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]}|${c[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",y("HYPHENRANGE",`^\\s*(${c[l.XRANGEPLAIN]})\\s+-\\s+(${c[l.XRANGEPLAIN]})\\s*$`),y("HYPHENRANGELOOSE",`^\\s*(${c[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[l.XRANGEPLAINLOOSE]})\\s*$`),y("STAR","(<|>)?=?\\s*\\*"),y("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),y("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(nn,nn.exports)),nn.exports}var da,xo;function ci(){if(xo)return da;xo=1;const t=Object.freeze({loose:!0}),e=Object.freeze({});return da=n=>n?typeof n!="object"?t:n:e,da}var ha,Io;function Iu(){if(Io)return ha;Io=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 ha={compareIdentifiers:e,rcompareIdentifiers:(n,a)=>e(a,n)},ha}var fa,Ao;function Be(){if(Ao)return fa;Ao=1;const t=jn(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:r}=Ln(),{safeRe:n,t:a}=Vr(),s=ci(),{compareIdentifiers:i}=Iu();class o{constructor(u,l){if(l=s(l),u instanceof o){if(u.loose===!!l.loose&&u.includePrerelease===!!l.includePrerelease)return u;u=u.version}else if(typeof u!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof u}".`);if(u.length>e)throw new TypeError(`version is longer than ${e} characters`);t("SemVer",u,l),this.options=l,this.loose=!!l.loose,this.includePrerelease=!!l.includePrerelease;const d=u.trim().match(l.loose?n[a.LOOSE]:n[a.FULL]);if(!d)throw new TypeError(`Invalid Version: ${u}`);if(this.raw=u,this.major=+d[1],this.minor=+d[2],this.patch=+d[3],this.major>r||this.major<0)throw new TypeError("Invalid major version");if(this.minor>r||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>r||this.patch<0)throw new TypeError("Invalid patch version");d[4]?this.prerelease=d[4].split(".").map(h=>{if(/^[0-9]+$/.test(h)){const f=+h;if(f>=0&&f<r)return f}return h}):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],h=u.prerelease[l];if(t("prerelease compare",l,d,h),d===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(d===void 0)return-1;if(d===h)continue;return i(d,h)}while(++l)}compareBuild(u){u instanceof o||(u=new o(u,this.options));let l=0;do{const d=this.build[l],h=u.build[l];if(t("build compare",l,d,h),d===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(d===void 0)return-1;if(d===h)continue;return i(d,h)}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 h=`-${l}`.match(this.options.loose?n[a.PRERELEASELOOSE]:n[a.PRERELEASE]);if(!h||h[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 h=Number(d)?1:0;if(this.prerelease.length===0)this.prerelease=[h];else{let f=this.prerelease.length;for(;--f>=0;)typeof this.prerelease[f]=="number"&&(this.prerelease[f]++,f=-2);if(f===-1){if(l===this.prerelease.join(".")&&d===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(h)}}if(l){let f=[l,h];d===!1&&(f=[l]),i(this.prerelease[0],l)===0?isNaN(this.prerelease[1])&&(this.prerelease=f):this.prerelease=f}break}default:throw new Error(`invalid increment argument: ${u}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return fa=o,fa}var pa,Oo;function vr(){if(Oo)return pa;Oo=1;const t=Be();return pa=(r,n,a=!1)=>{if(r instanceof t)return r;try{return new t(r,n)}catch(s){if(!a)return null;throw s}},pa}var ma,ko;function Vf(){if(ko)return ma;ko=1;const t=vr();return ma=(r,n)=>{const a=t(r,n);return a?a.version:null},ma}var ga,Ro;function Zf(){if(Ro)return ga;Ro=1;const t=vr();return ga=(r,n)=>{const a=t(r.trim().replace(/^[=v]+/,""),n);return a?a.version:null},ga}var ya,Co;function Jf(){if(Co)return ya;Co=1;const t=Be();return ya=(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}},ya}var _a,No;function Wf(){if(No)return _a;No=1;const t=vr();return _a=(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 h=l?"pre":"";return a.major!==s.major?h+"major":a.minor!==s.minor?h+"minor":a.patch!==s.patch?h+"patch":"prerelease"},_a}var va,$o;function Kf(){if($o)return va;$o=1;const t=Be();return va=(r,n)=>new t(r,n).major,va}var wa,Po;function Yf(){if(Po)return wa;Po=1;const t=Be();return wa=(r,n)=>new t(r,n).minor,wa}var ba,Mo;function Xf(){if(Mo)return ba;Mo=1;const t=Be();return ba=(r,n)=>new t(r,n).patch,ba}var Ea,Lo;function Qf(){if(Lo)return Ea;Lo=1;const t=vr();return Ea=(r,n)=>{const a=t(r,n);return a&&a.prerelease.length?a.prerelease:null},Ea}var Ta,jo;function lt(){if(jo)return Ta;jo=1;const t=Be();return Ta=(r,n,a)=>new t(r,a).compare(new t(n,a)),Ta}var Sa,Do;function ep(){if(Do)return Sa;Do=1;const t=lt();return Sa=(r,n,a)=>t(n,r,a),Sa}var xa,Uo;function tp(){if(Uo)return xa;Uo=1;const t=lt();return xa=(r,n)=>t(r,n,!0),xa}var Ia,Fo;function ui(){if(Fo)return Ia;Fo=1;const t=Be();return Ia=(r,n,a)=>{const s=new t(r,a),i=new t(n,a);return s.compare(i)||s.compareBuild(i)},Ia}var Aa,Bo;function rp(){if(Bo)return Aa;Bo=1;const t=ui();return Aa=(r,n)=>r.sort((a,s)=>t(a,s,n)),Aa}var Oa,zo;function np(){if(zo)return Oa;zo=1;const t=ui();return Oa=(r,n)=>r.sort((a,s)=>t(s,a,n)),Oa}var ka,qo;function Dn(){if(qo)return ka;qo=1;const t=lt();return ka=(r,n,a)=>t(r,n,a)>0,ka}var Ra,Go;function li(){if(Go)return Ra;Go=1;const t=lt();return Ra=(r,n,a)=>t(r,n,a)<0,Ra}var Ca,Ho;function Au(){if(Ho)return Ca;Ho=1;const t=lt();return Ca=(r,n,a)=>t(r,n,a)===0,Ca}var Na,Vo;function Ou(){if(Vo)return Na;Vo=1;const t=lt();return Na=(r,n,a)=>t(r,n,a)!==0,Na}var $a,Zo;function di(){if(Zo)return $a;Zo=1;const t=lt();return $a=(r,n,a)=>t(r,n,a)>=0,$a}var Pa,Jo;function hi(){if(Jo)return Pa;Jo=1;const t=lt();return Pa=(r,n,a)=>t(r,n,a)<=0,Pa}var Ma,Wo;function ku(){if(Wo)return Ma;Wo=1;const t=Au(),e=Ou(),r=Dn(),n=di(),a=li(),s=hi();return Ma=(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}`)}},Ma}var La,Ko;function ap(){if(Ko)return La;Ko=1;const t=Be(),e=vr(),{safeRe:r,t:n}=Vr();return La=(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 f=i.includePrerelease?r[n.COERCERTLFULL]:r[n.COERCERTL];let p;for(;(p=f.exec(s))&&(!o||o.index+o[0].length!==s.length);)(!o||p.index+p[0].length!==o.index+o[0].length)&&(o=p),f.lastIndex=p.index+p[1].length+p[2].length;f.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]}`:"",h=i.includePrerelease&&o[6]?`+${o[6]}`:"";return e(`${c}.${u}.${l}${d}${h}`,i)},La}var ja,Yo;function sp(){if(Yo)return ja;Yo=1;class t{constructor(){this.max=1e3,this.map=new Map}get(r){const n=this.map.get(r);if(n!==void 0)return this.map.delete(r),this.map.set(r,n),n}delete(r){return this.map.delete(r)}set(r,n){if(!this.delete(r)&&n!==void 0){if(this.map.size>=this.max){const s=this.map.keys().next().value;this.delete(s)}this.map.set(r,n)}return this}}return ja=t,ja}var Da,Xo;function dt(){if(Xo)return Da;Xo=1;const t=/\s+/g;class e{constructor(O,k){if(k=a(k),O instanceof e)return O.loose===!!k.loose&&O.includePrerelease===!!k.includePrerelease?O:new e(O.raw,k);if(O instanceof s)return this.raw=O.value,this.set=[[O]],this.formatted=void 0,this;if(this.options=k,this.loose=!!k.loose,this.includePrerelease=!!k.includePrerelease,this.raw=O.trim().replace(t," "),this.set=this.raw.split("||").map(B=>this.parseRange(B.trim())).filter(B=>B.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const B=this.set[0];if(this.set=this.set.filter(q=>!y(q[0])),this.set.length===0)this.set=[B];else if(this.set.length>1){for(const q of this.set)if(q.length===1&&_(q[0])){this.set=[q];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let O=0;O<this.set.length;O++){O>0&&(this.formatted+="||");const k=this.set[O];for(let B=0;B<k.length;B++)B>0&&(this.formatted+=" "),this.formatted+=k[B].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(O){const B=((this.options.includePrerelease&&f)|(this.options.loose&&p))+":"+O,q=n.get(B);if(q)return q;const F=this.options.loose,Z=F?c[u.HYPHENRANGELOOSE]:c[u.HYPHENRANGE];O=O.replace(Z,Ne(this.options.includePrerelease)),i("hyphen replace",O),O=O.replace(c[u.COMPARATORTRIM],l),i("comparator trim",O),O=O.replace(c[u.TILDETRIM],d),i("tilde trim",O),O=O.replace(c[u.CARETTRIM],h),i("caret trim",O);let ae=O.split(" ").map(ce=>T(ce,this.options)).join(" ").split(/\s+/).map(ce=>oe(ce,this.options));F&&(ae=ae.filter(ce=>(i("loose invalid filter",ce,this.options),!!ce.match(c[u.COMPARATORLOOSE])))),i("range list",ae);const ee=new Map,le=ae.map(ce=>new s(ce,this.options));for(const ce of le){if(y(ce))return[ce];ee.set(ce.value,ce)}ee.size>1&&ee.has("")&&ee.delete("");const Te=[...ee.values()];return n.set(B,Te),Te}intersects(O,k){if(!(O instanceof e))throw new TypeError("a Range is required");return this.set.some(B=>w(B,k)&&O.set.some(q=>w(q,k)&&B.every(F=>q.every(Z=>F.intersects(Z,k)))))}test(O){if(!O)return!1;if(typeof O=="string")try{O=new o(O,this.options)}catch{return!1}for(let k=0;k<this.set.length;k++)if(wt(this.set[k],O,this.options))return!0;return!1}}Da=e;const r=sp(),n=new r,a=ci(),s=Un(),i=jn(),o=Be(),{safeRe:c,t:u,comparatorTrimReplace:l,tildeTrimReplace:d,caretTrimReplace:h}=Vr(),{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:p}=Ln(),y=C=>C.value==="<0.0.0-0",_=C=>C.value==="",w=(C,O)=>{let k=!0;const B=C.slice();let q=B.pop();for(;k&&B.length;)k=B.every(F=>q.intersects(F,O)),q=B.pop();return k},T=(C,O)=>(C=C.replace(c[u.BUILD],""),i("comp",C,O),C=j(C,O),i("caret",C),C=x(C,O),i("tildes",C),C=v(C,O),i("xrange",C),C=_e(C,O),i("stars",C),C),E=C=>!C||C.toLowerCase()==="x"||C==="*",x=(C,O)=>C.trim().split(/\s+/).map(k=>R(k,O)).join(" "),R=(C,O)=>{const k=O.loose?c[u.TILDELOOSE]:c[u.TILDE];return C.replace(k,(B,q,F,Z,ae)=>{i("tilde",C,B,q,F,Z,ae);let ee;return E(q)?ee="":E(F)?ee=`>=${q}.0.0 <${+q+1}.0.0-0`:E(Z)?ee=`>=${q}.${F}.0 <${q}.${+F+1}.0-0`:ae?(i("replaceTilde pr",ae),ee=`>=${q}.${F}.${Z}-${ae} <${q}.${+F+1}.0-0`):ee=`>=${q}.${F}.${Z} <${q}.${+F+1}.0-0`,i("tilde return",ee),ee})},j=(C,O)=>C.trim().split(/\s+/).map(k=>J(k,O)).join(" "),J=(C,O)=>{i("caret",C,O);const k=O.loose?c[u.CARETLOOSE]:c[u.CARET],B=O.includePrerelease?"-0":"";return C.replace(k,(q,F,Z,ae,ee)=>{i("caret",C,q,F,Z,ae,ee);let le;return E(F)?le="":E(Z)?le=`>=${F}.0.0${B} <${+F+1}.0.0-0`:E(ae)?F==="0"?le=`>=${F}.${Z}.0${B} <${F}.${+Z+1}.0-0`:le=`>=${F}.${Z}.0${B} <${+F+1}.0.0-0`:ee?(i("replaceCaret pr",ee),F==="0"?Z==="0"?le=`>=${F}.${Z}.${ae}-${ee} <${F}.${Z}.${+ae+1}-0`:le=`>=${F}.${Z}.${ae}-${ee} <${F}.${+Z+1}.0-0`:le=`>=${F}.${Z}.${ae}-${ee} <${+F+1}.0.0-0`):(i("no pr"),F==="0"?Z==="0"?le=`>=${F}.${Z}.${ae}${B} <${F}.${Z}.${+ae+1}-0`:le=`>=${F}.${Z}.${ae}${B} <${F}.${+Z+1}.0-0`:le=`>=${F}.${Z}.${ae} <${+F+1}.0.0-0`),i("caret return",le),le})},v=(C,O)=>(i("replaceXRanges",C,O),C.split(/\s+/).map(k=>ge(k,O)).join(" ")),ge=(C,O)=>{C=C.trim();const k=O.loose?c[u.XRANGELOOSE]:c[u.XRANGE];return C.replace(k,(B,q,F,Z,ae,ee)=>{i("xRange",C,B,q,F,Z,ae,ee);const le=E(F),Te=le||E(Z),ce=Te||E(ae),g=ce;return q==="="&&g&&(q=""),ee=O.includePrerelease?"-0":"",le?q===">"||q==="<"?B="<0.0.0-0":B="*":q&&g?(Te&&(Z=0),ae=0,q===">"?(q=">=",Te?(F=+F+1,Z=0,ae=0):(Z=+Z+1,ae=0)):q==="<="&&(q="<",Te?F=+F+1:Z=+Z+1),q==="<"&&(ee="-0"),B=`${q+F}.${Z}.${ae}${ee}`):Te?B=`>=${F}.0.0${ee} <${+F+1}.0.0-0`:ce&&(B=`>=${F}.${Z}.0${ee} <${F}.${+Z+1}.0-0`),i("xRange return",B),B})},_e=(C,O)=>(i("replaceStars",C,O),C.trim().replace(c[u.STAR],"")),oe=(C,O)=>(i("replaceGTE0",C,O),C.trim().replace(c[O.includePrerelease?u.GTE0PRE:u.GTE0],"")),Ne=C=>(O,k,B,q,F,Z,ae,ee,le,Te,ce,g)=>(E(B)?k="":E(q)?k=`>=${B}.0.0${C?"-0":""}`:E(F)?k=`>=${B}.${q}.0${C?"-0":""}`:Z?k=`>=${k}`:k=`>=${k}${C?"-0":""}`,E(le)?ee="":E(Te)?ee=`<${+le+1}.0.0-0`:E(ce)?ee=`<${le}.${+Te+1}.0-0`:g?ee=`<=${le}.${Te}.${ce}-${g}`:C?ee=`<${le}.${Te}.${+ce+1}-0`:ee=`<=${ee}`,`${k} ${ee}`.trim()),wt=(C,O,k)=>{for(let B=0;B<C.length;B++)if(!C[B].test(O))return!1;if(O.prerelease.length&&!k.includePrerelease){for(let B=0;B<C.length;B++)if(i(C[B].semver),C[B].semver!==s.ANY&&C[B].semver.prerelease.length>0){const q=C[B].semver;if(q.major===O.major&&q.minor===O.minor&&q.patch===O.patch)return!0}return!1}return!0};return Da}var Ua,Qo;function Un(){if(Qo)return Ua;Qo=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],h=l.match(d);if(!h)throw new TypeError(`Invalid comparator: ${l}`);this.operator=h[1]!==void 0?h[1]:"",this.operator==="="&&(this.operator=""),h[2]?this.semver=new o(h[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(">")))}}Ua=e;const r=ci(),{safeRe:n,t:a}=Vr(),s=ku(),i=jn(),o=Be(),c=dt();return Ua}var Fa,ec;function Fn(){if(ec)return Fa;ec=1;const t=dt();return Fa=(r,n,a)=>{try{n=new t(n,a)}catch{return!1}return n.test(r)},Fa}var Ba,tc;function ip(){if(tc)return Ba;tc=1;const t=dt();return Ba=(r,n)=>new t(r,n).set.map(a=>a.map(s=>s.value).join(" ").trim().split(" ")),Ba}var za,rc;function op(){if(rc)return za;rc=1;const t=Be(),e=dt();return za=(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},za}var qa,nc;function cp(){if(nc)return qa;nc=1;const t=Be(),e=dt();return qa=(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},qa}var Ga,ac;function up(){if(ac)return Ga;ac=1;const t=Be(),e=dt(),r=Dn();return Ga=(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},Ga}var Ha,sc;function lp(){if(sc)return Ha;sc=1;const t=dt();return Ha=(r,n)=>{try{return new t(r,n).range||"*"}catch{return null}},Ha}var Va,ic;function fi(){if(ic)return Va;ic=1;const t=Be(),e=Un(),{ANY:r}=e,n=dt(),a=Fn(),s=Dn(),i=li(),o=hi(),c=di();return Va=(l,d,h,f)=>{l=new t(l,f),d=new n(d,f);let p,y,_,w,T;switch(h){case">":p=s,y=o,_=i,w=">",T=">=";break;case"<":p=i,y=c,_=s,w="<",T="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(a(l,d,f))return!1;for(let E=0;E<d.set.length;++E){const x=d.set[E];let R=null,j=null;if(x.forEach(J=>{J.semver===r&&(J=new e(">=0.0.0")),R=R||J,j=j||J,p(J.semver,R.semver,f)?R=J:_(J.semver,j.semver,f)&&(j=J)}),R.operator===w||R.operator===T||(!j.operator||j.operator===w)&&y(l,j.semver))return!1;if(j.operator===T&&_(l,j.semver))return!1}return!0},Va}var Za,oc;function dp(){if(oc)return Za;oc=1;const t=fi();return Za=(r,n,a)=>t(r,n,">",a),Za}var Ja,cc;function hp(){if(cc)return Ja;cc=1;const t=fi();return Ja=(r,n,a)=>t(r,n,"<",a),Ja}var Wa,uc;function fp(){if(uc)return Wa;uc=1;const t=dt();return Wa=(r,n,a)=>(r=new t(r,a),n=new t(n,a),r.intersects(n,a)),Wa}var Ka,lc;function pp(){if(lc)return Ka;lc=1;const t=Fn(),e=lt();return Ka=(r,n,a)=>{const s=[];let i=null,o=null;const c=r.sort((h,f)=>e(h,f,a));for(const h of c)t(h,n,a)?(o=h,i||(i=h)):(o&&s.push([i,o]),o=null,i=null);i&&s.push([i,null]);const u=[];for(const[h,f]of s)h===f?u.push(h):!f&&h===c[0]?u.push("*"):f?h===c[0]?u.push(`<=${f}`):u.push(`${h} - ${f}`):u.push(`>=${h}`);const l=u.join(" || "),d=typeof n.raw=="string"?n.raw:String(n);return l.length<d.length?l:n},Ka}var Ya,dc;function mp(){if(dc)return Ya;dc=1;const t=dt(),e=Un(),{ANY:r}=e,n=Fn(),a=lt(),s=(d,h,f={})=>{if(d===h)return!0;d=new t(d,f),h=new t(h,f);let p=!1;e:for(const y of d.set){for(const _ of h.set){const w=c(y,_,f);if(p=p||w!==null,w)continue e}if(p)return!1}return!0},i=[new e(">=0.0.0-0")],o=[new e(">=0.0.0")],c=(d,h,f)=>{if(d===h)return!0;if(d.length===1&&d[0].semver===r){if(h.length===1&&h[0].semver===r)return!0;f.includePrerelease?d=i:d=o}if(h.length===1&&h[0].semver===r){if(f.includePrerelease)return!0;h=o}const p=new Set;let y,_;for(const v of d)v.operator===">"||v.operator===">="?y=u(y,v,f):v.operator==="<"||v.operator==="<="?_=l(_,v,f):p.add(v.semver);if(p.size>1)return null;let w;if(y&&_){if(w=a(y.semver,_.semver,f),w>0)return null;if(w===0&&(y.operator!==">="||_.operator!=="<="))return null}for(const v of p){if(y&&!n(v,String(y),f)||_&&!n(v,String(_),f))return null;for(const ge of h)if(!n(v,String(ge),f))return!1;return!0}let T,E,x,R,j=_&&!f.includePrerelease&&_.semver.prerelease.length?_.semver:!1,J=y&&!f.includePrerelease&&y.semver.prerelease.length?y.semver:!1;j&&j.prerelease.length===1&&_.operator==="<"&&j.prerelease[0]===0&&(j=!1);for(const v of h){if(R=R||v.operator===">"||v.operator===">=",x=x||v.operator==="<"||v.operator==="<=",y){if(J&&v.semver.prerelease&&v.semver.prerelease.length&&v.semver.major===J.major&&v.semver.minor===J.minor&&v.semver.patch===J.patch&&(J=!1),v.operator===">"||v.operator===">="){if(T=u(y,v,f),T===v&&T!==y)return!1}else if(y.operator===">="&&!n(y.semver,String(v),f))return!1}if(_){if(j&&v.semver.prerelease&&v.semver.prerelease.length&&v.semver.major===j.major&&v.semver.minor===j.minor&&v.semver.patch===j.patch&&(j=!1),v.operator==="<"||v.operator==="<="){if(E=l(_,v,f),E===v&&E!==_)return!1}else if(_.operator==="<="&&!n(_.semver,String(v),f))return!1}if(!v.operator&&(_||y)&&w!==0)return!1}return!(y&&x&&!_&&w!==0||_&&R&&!y&&w!==0||J||j)},u=(d,h,f)=>{if(!d)return h;const p=a(d.semver,h.semver,f);return p>0?d:p<0||h.operator===">"&&d.operator===">="?h:d},l=(d,h,f)=>{if(!d)return h;const p=a(d.semver,h.semver,f);return p<0?d:p>0||h.operator==="<"&&d.operator==="<="?h:d};return Ya=s,Ya}var Xa,hc;function gp(){if(hc)return Xa;hc=1;const t=Vr(),e=Ln(),r=Be(),n=Iu(),a=vr(),s=Vf(),i=Zf(),o=Jf(),c=Wf(),u=Kf(),l=Yf(),d=Xf(),h=Qf(),f=lt(),p=ep(),y=tp(),_=ui(),w=rp(),T=np(),E=Dn(),x=li(),R=Au(),j=Ou(),J=di(),v=hi(),ge=ku(),_e=ap(),oe=Un(),Ne=dt(),wt=Fn(),C=ip(),O=op(),k=cp(),B=up(),q=lp(),F=fi(),Z=dp(),ae=hp(),ee=fp(),le=pp(),Te=mp();return Xa={parse:a,valid:s,clean:i,inc:o,diff:c,major:u,minor:l,patch:d,prerelease:h,compare:f,rcompare:p,compareLoose:y,compareBuild:_,sort:w,rsort:T,gt:E,lt:x,eq:R,neq:j,gte:J,lte:v,cmp:ge,coerce:_e,Comparator:oe,Range:Ne,satisfies:wt,toComparators:C,maxSatisfying:O,minSatisfying:k,minVersion:B,validRange:q,outside:F,gtr:Z,ltr:ae,intersects:ee,simplifyRange:le,subset:Te,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},Xa}gp();function kt(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 yp 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 G(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 yp(a);const s=new Error(a);throw s.status=t.status,s}const Ru="ERR_CONFLICTING_ENDPOINTS";class _p 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:Ru}),this.name="ConflictingEndpointsError"}}function vp(t){return typeof t=="object"&&t!==null&&t.code===Ru}var fc="[...]",wp={result:"[Circular]"},bn=[],ar=[];const bp=new TextEncoder;function Ep(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function an(t){return bp.encode(t)}function Cu(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 Tp(t){return function(e,r){return Cu(r)}}function We(t,e,r,n,a){try{const s=JSON.stringify(t,Tp(r),n);return an(s)}catch(s){if(!s.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
20
+ Context: ${e}`:""}`),an("[Unserializable]");He("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=Ep()),Ss(t,"",0,[],void 0,0,a);let i;try{ar.length===0?i=JSON.stringify(t,r,n):i=JSON.stringify(t,Sp(r),n)}catch{return an("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;bn.length!==0;){const o=bn.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return an(i)}}function Qa(t,e,r,n){var a=Object.getOwnPropertyDescriptor(n,r);a.get!==void 0?a.configurable?(Object.defineProperty(n,r,{value:t}),bn.push([n,r,e,a])):ar.push([e,r,t]):(n[r]=t,bn.push([n,r,e]))}function Ss(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){Qa(wp,t,e,a);return}if(typeof i.depthLimit<"u"&&s>i.depthLimit){Qa(fc,t,e,a);return}if(typeof i.edgesLimit<"u"&&r+1>i.edgesLimit){Qa(fc,t,e,a);return}if(n.push(t),Array.isArray(t))for(o=0;o<t.length;o++)Ss(t[o],o,o,n,t,s,i);else{t=Cu(t);var c=Object.keys(t);for(o=0;o<c.length;o++){var u=c[o];Ss(t[u],u,o,n,t,s,i)}}n.pop()}}function Sp(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(ar.length>0)for(var n=0;n<ar.length;n++){var a=ar[n];if(a[1]===e&&a[0]===r){r=a[2],ar.splice(n,1);break}}return t.call(this,e,r)}}function pc(t,e){const r=Eu(),n=e??Tu(),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 xp=t=>{const e=t?.toString()??He("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},Ip=t=>{const r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};async function Ap(t){const e=[];for await(const r of t)e.push(r);return e}function sn(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const Op=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 mc(t){return typeof t=="number"?Number(t.toFixed(4)):t}class kp{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=We(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 Rp=24*1024*1024,Cp=1e4,Np=100,gc="https://api.smith.langchain.com";class Ur{get _fetch(){return this.fetchImplementation||pf(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 kp}),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:vt("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:vt("LANGSMITH_DEBUG")==="true"});const r=Ur.getDefaultClientConfig();if(this.tracingSampleRate=xp(e.tracingSamplingRate),this.apiUrl=sn(e.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=sn(e.apiKey??r.apiKey),this.webUrl=sn(e.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=sn(e.workspaceId??He("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new _o({...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 _o({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:Op,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,Su()&&(this.langSmithToOTELTranslator=new Cf),this.cachedLSEnvVarsForMetadata=Tu()}static getDefaultClientConfig(){const e=He("API_KEY"),r=He("ENDPOINT")??gc,n=He("HIDE_INPUTS")==="true",a=He("HIDE_OUTPUTS")==="true";return{apiUrl:r,apiKey:e,webUrl:void 0,hideInputs:n,hideOutputs:a}}getHostUrl(){return this.webUrl?this.webUrl:Ip(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/${vu}`};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 G(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 G(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 G(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??Rp}async _getBatchSizeLimit(){const e=await this._ensureServerInfo();return this.batchSizeLimit??e.batch_ingest_config?.size_limit??Np}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,h=l.apiKey??this.apiKey,p=l.apiKey===this.apiKey&&l.apiUrl===this.apiUrl?"default":`${d}|${h}`;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=pc(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(Cp),...this.fetchOptions});return await G(n,"get server info"),n})).json();return this.debug&&console.log(`
22
+ === LangSmith Server Configuration ===
23
+ `+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=xu(),r=Af();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=pc(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=We(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 G(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(We(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 G(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 h=await this.prepareRunCreateOrUpdateInputs(d);h.id!==void 0&&h.attachments!==void 0&&(a[h.id]=h.attachments),delete h.attachments,s.push(h)}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((f,p)=>(p.id&&(f[p.id]=p),f),{}),h=[];for(const f of i)f.id!==void 0&&d[f.id]?d[f.id]={...d[f.id],...f}:h.push(f);s=Object.values(d),i=h}if(s.length===0&&i.length===0)return;const u=[],l=[];for(const[d,h]of[["post",s],["patch",i]])for(const f of h){const{inputs:p,outputs:y,events:_,extra:w,error:T,serialized:E,attachments:x,...R}=f,j={inputs:p,outputs:y,events:_,extra:w,error:T,serialized:E},J=We(R,`Serializing for multipart ingestion of run with id: ${R.id}`);l.push({name:`${d}.${R.id}`,payload:new Blob([J],{type:`application/json; length=${J.length}`})});for(const[v,ge]of Object.entries(j)){if(ge===void 0)continue;const _e=We(ge,`Serializing ${v} for multipart ingestion of run with id: ${R.id}`);l.push({name:`${d}.${R.id}.${v}`,payload:new Blob([_e],{type:`application/json; length=${_e.length}`})})}if(R.id!==void 0){const v=a[R.id];if(v){delete a[R.id];for(const[ge,_e]of Object.entries(v)){let oe,Ne;if(Array.isArray(_e)?[oe,Ne]=_e:(oe=_e.mimeType,Ne=_e.data),ge.includes(".")){console.warn(`Skipping attachment '${ge}' for run ${R.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${R.id}.${ge}`,payload:new Blob([Ne],{type:`${oe}; length=${Ne.byteLength}`})})}}}u.push(`trace=${R.trace_id},id=${R.id}`)}await this._sendMultipartRequest(l,u.join("; "),n)}async _createNodeFetchBody(e,r){const n=[];for(const i of e)n.push(new Blob([`--${r}\r
25
+ `])),n.push(new Blob([`Content-Disposition: form-data; name="${i.name}"\r
26
+ `,`Content-Type: ${i.payload.type}\r
27
+ \r
28
+ `])),n.push(i.payload),n.push(new Blob([`\r
29
+ `]));return n.push(new Blob([`--${r}--\r
30
+ `])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,r){const n=new TextEncoder;return new ReadableStream({async start(s){const i=async o=>{typeof o=="string"?s.enqueue(n.encode(o)):s.enqueue(o)};for(const o of e){await i(`--${r}\r
31
+ `),await i(`Content-Disposition: form-data; name="${o.name}"\r
32
+ `),await i(`Content-Type: ${o.payload.type}\r
33
+ \r
34
+ `);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
+ `)}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 h=l;n?.useGzip&&typeof l=="object"&&"pipeThrough"in l&&(h=l.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");const f=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:h,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(f,"Failed to send multipart request",!0),f});try{let u,l=!1;!s&&!this.multipartStreamingDisabled&&bu()!=="bun"?(l=!0,u=await c(o)):u=await c(i),(!this.multipartStreamingDisabled||l)&&u.status===422&&(n?.apiUrl??this.apiUrl)!==gc&&(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
+
38
+ Context: ${r}`)}}async updateRun(e,r,n){re(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=We(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 G(o,"update run",!0),o})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){re(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:He("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 Ap(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:h,query:f,filter:p,traceFilter:y,treeFilter:_,limit:w,select:T,order:E}=e;let x=[];if(r&&(x=Array.isArray(r)?r:[r]),n){const v=Array.isArray(n)?n:[n],ge=await Promise.all(v.map(_e=>this.readProject({projectName:_e}).then(oe=>oe.id)));x.push(...ge)}const R=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],j={session:x.length?x:null,run_type:l,reference_example:i,query:f,filter:p,trace_filter:y,tree_filter:_,execution_order:c,parent_run:a,start_time:o?o.toISOString():null,error:d,id:h,limit:w,trace:s,select:T||R,is_root:u,order:E};j.select.includes("child_run_ids")&&Ts("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let J=0;for await(const v of this._getCursorPaginatedList("/runs/query",j))if(w){if(J>=w)break;if(v.length+J>w){yield*v.slice(0,w-J);break}J+=v.length,yield*v}else yield*v}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 h=Number(u)||0;const f="/runs/group",p=`${this.apiUrl}${f}`;for(;;){const y={...d,offset:h},_=Object.fromEntries(Object.entries(y).filter(([j,J])=>J!==void 0)),w=JSON.stringify(_),E=await(await this.caller.call(async()=>{const j=await this._fetch(p,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:w});return await G(j,`Failed to fetch ${f}`),j})).json(),{groups:x,total:R}=E;if(x.length===0)break;for(const j of x)yield j;if(h+=x.length,h>=R)break}}async getRunStats({id:e,trace:r,parentRun:n,runType:a,projectNames:s,projectIds:i,referenceExampleIds:o,startTime:c,endTime:u,error:l,query:d,filter:h,traceFilter:f,treeFilter:p,isRoot:y,dataSourceType:_}){let w=i||[];s&&(w=[...i||[],...await Promise.all(s.map(J=>this.readProject({projectName:J}).then(v=>v.id)))]);const E=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:a,session:w,reference_example:o,start_time:c,end_time:u,error:l,query:d,filter:h,trace_filter:f,tree_filter:p,is_root:y,data_source_type:_}).filter(([J,v])=>v!==void 0)),x=JSON.stringify(E);return await(await this.caller.call(async()=>{const J=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:x});return await G(J,"get run stats"),J})).json()}async shareRun(e,{shareId:r}={}){const n={run_id:e,share_token:r||Ue()};re(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 G(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){re(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 G(r,"unshare run",!0),r})}async readRunSharedLink(e){re(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 G(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 re(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 G(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),re(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 G(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};re(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 G(o,"share dataset"),o})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){re(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 G(r,"unshare dataset",!0),r})}async readSharedDataset(e){return re(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 G(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 G(o,"list shared examples"),o}),i=await s.json();if(!s.ok)throw"detail"in i?new Error(`Failed to list shared examples.
39
+ Status: ${s.status}
40
+ 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 G(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 h=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 G(h,"update project"),h})).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)re(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 G(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)re(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,re(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 G(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(h=>{u.append("input_keys",h)}),a.forEach(h=>{u.append("output_keys",h)}),s&&u.append("description",s),i&&u.append("data_type",i),o&&u.append("name",o),await(await this.caller.call(async()=>{const h=await this._fetch(c,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await G(h,"upload CSV"),h})).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 G(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)re(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;re(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 G(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;re(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 G(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)re(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 G(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),re(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 G(c,"index dataset"),c})).json()}async similarExamples(e,r,n,{filter:a}={}){const s={limit:n,inputs:e};a!==void 0&&(s.filter=a),re(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 G(u,"fetch similar examples"),u})).json()).examples}async createExample(e,r,n){if(yc(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;yc(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]??Ue())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];const T=e;let E=T[0].dataset_id;const x=T[0].dataset_name;if(E===void 0&&x===void 0)throw new Error("Must provide either datasetName or datasetId");if(E!==void 0&&x!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");E===void 0&&(E=(await this.readDataset({datasetName:x})).id);const R=await this._uploadExamplesMultipart(E,T);return await Promise.all(R.example_ids.map(J=>this.readExample(J)))}const{inputs:r,outputs:n,metadata:a,splits:s,sourceRunIds:i,useSourceRunIOs:o,useSourceRunAttachments:c,attachments:u,exampleIds:l,datasetId:d,datasetName:h}=e;if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let f=d;const p=h;if(f===void 0&&p===void 0)throw new Error("Must provide either datasetName or datasetId");if(f!==void 0&&p!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");f===void 0&&(f=(await this.readDataset({datasetName:p})).id);const y=r.map((T,E)=>({dataset_id:f,inputs:T,outputs:n?.[E],metadata:a?.[E],split:s?.[E],id:l?.[E],attachments:u?.[E],source_run_id:i?.[E],use_source_run_io:o?.[E],use_source_run_attachments:c?.[E]})),_=await this._uploadExamplesMultipart(f,y);return await Promise.all(_.example_ids.map(T=>this.readExample(T)))}async createLLMExample(e,r,n){return this.createExample({input:e},{output:r},n)}async createChatExample(e,r,n){const a=e.map(i=>vo(i)?wo(i):i),s=vo(r)?wo(r):r;return this.createExample({input:a},{output:s},n)}async readExample(e){re(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 h;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)h=e;else if(r!==void 0)h=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");const f=new URLSearchParams({dataset:h}),p=a?typeof a=="string"?a:a?.toISOString():void 0;p&&f.append("as_of",p);const y=i??!0;if(f.append("inline_s3_urls",y.toString()),n!==void 0)for(const w of n)f.append("id",w);if(s!==void 0)for(const w of s)f.append("splits",w);if(o!==void 0){const w=JSON.stringify(o);f.append("metadata",w)}c!==void 0&&f.append("limit",c.toString()),u!==void 0&&f.append("offset",u.toString()),l!==void 0&&f.append("filter",l),d===!0&&["attachment_urls","outputs","metadata"].forEach(w=>f.append("select",w));let _=0;for await(const w of this._getPaginated("/examples",f)){for(const T of w){const{attachment_urls:E,...x}=T,R=x;E&&(R.attachments=Object.entries(E).reduce((j,[J,v])=>(j[J.slice(11)]={presigned_url:v.presigned_url,mime_type:v.mime_type||void 0},j),{})),yield R,_++}if(c!==void 0&&_>=c)break}}async deleteExample(e){re(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 G(n,`delete ${r}`,!0),n})}async updateExample(e,r){let n;r?n=e:n=e.id,re(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,re(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 G(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,re(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,re(i);const o={split_name:n,examples:a.map(u=>(re(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 G(u,"update dataset splits",!0),u})}async evaluateRun(e,r,{sourceInfo:n,loadChildRuns:a,referenceExample:s}={loadChildRuns:!1}){Ts("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:h,comparativeExperimentId:f}){if(!e&&!h)throw new Error("One of runId or projectId must be provided");if(e&&h)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&&re(p.metadata.__run.run_id);const y={id:l??Ue(),run_id:e,key:r,score:mc(n),value:a,correction:s,comment:i,feedback_source:p,comparative_experiment_id:f,feedbackConfig:d,session_id:h},_=JSON.stringify(y),w=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const T=await this._fetch(w,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:_});return await G(T,"create feedback",!0),T}),y}async updateFeedback(e,{score:r,value:n,correction:a,comment:s}){const i={};r!=null&&(i.score=mc(r)),n!=null&&(i.value=n),a!=null&&(i.correction=a),s!=null&&(i.comment=s),re(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 G(c,"update feedback",!0),c})}async readFeedback(e){re(e);const r=`/feedback/${e}`;return await this._get(r)}async deleteFeedback(e){re(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 G(n,`delete ${r}`,!0),n})}async*listFeedback({runIds:e,feedbackKeys:r,feedbackSourceTypes:n}={}){const a=new URLSearchParams;if(e)for(const s of e)re(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 G(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 G(d,"create comparative experiment"),d})).json()}async*listPresignedFeedbackTokens(e){re(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)=>{re(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||Ue(),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 G(u,"create annotation queue"),u})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${re(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(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/${re(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await G(o,"update annotation queue",!0),o})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${re(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(r,"delete annotation queue",!0),r})}async addRunsToAnnotationQueue(e,r){const n=JSON.stringify(r.map((a,s)=>re(a,`runIds[${s}]`).toString()));await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/annotation-queues/${re(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await G(a,"add runs to annotation queue",!0),a})}async getRunFromAnnotationQueue(e,r){const n=`/annotation-queues/${re(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 G(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/${re(e,"queueId")}/runs/${re(r,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(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/${re(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(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
+
44
+ Current tenant: ${n.tenant_handle}
45
+
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 G(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]=kt(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 G(c,`${r?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(e){const[r,n,a]=kt(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]=kt(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 G(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
+
48
+ creating a LangChain Hub handle.
49
+ You can add a handle by creating a public prompt at:
50
+
51
+ https://smith.langchain.com/prompts`);const[a,s,i]=kt(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 G(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]=kt(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 h=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 G(h,"create commit"),h})).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=We(c,`Serializing body for example with id: ${o}`),l=new Blob([u],{type:"application/json"});if(n.append(o,l),i.inputs){const d=We(i.inputs,`Serializing inputs for example with id: ${o}`),h=new Blob([d],{type:"application/json"});n.append(`${o}.inputs`,h)}if(i.outputs){const d=We(i.outputs,`Serializing outputs whle updating example with id: ${o}`),h=new Blob([d],{type:"application/json"});n.append(`${o}.outputs`,h)}if(i.attachments)for(const[d,h]of Object.entries(i.attachments)){let f,p;Array.isArray(h)?[f,p]=h:(f=h.mimeType,p=h.data);const y=new Blob([p],{type:`${f}; length=${p.byteLength}`});n.append(`${o}.attachment.${d}`,y)}if(i.attachments_operations){const d=We(i.attachments_operations,`Serializing attachments while updating example with id: ${o}`),h=new Blob([d],{type:"application/json"});n.append(`${o}.attachments_operations`,h)}}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 G(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??Ue()).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=We(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=We(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=We(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 h,f;Array.isArray(d)?[h,f]=d:(h=d.mimeType,f=d.data);const p=new Blob([f],{type:`${h}; length=${f.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 G(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]=kt(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 G(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]=kt(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 G(i,"delete prompt"),i})).json()}async pullPromptCommit(e,r){const[n,a,s]=kt(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 G(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 Ur({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(h=>h.inputs),outputs:l.flatMap(h=>h.outputs?[h.outputs]:[]),datasetId:d.id})}catch(h){throw console.error(`An error occurred while creating dataset ${u}. You should delete it manually.`),h}}parseTokenOrUrl(e,r,n=2,a="dataset"){try{return re(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 Of()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function yc(t){return"dataset_id"in t||"dataset_name"in t}const $p=t=>!!["TRACING_V2","TRACING"].find(r=>He(r)==="true"),es=Symbol.for("lc:context_variables");function Pp(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:Pp(a)+e,microsecondPrecisionDatestring:a}}class En{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 En(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 Ge{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}),Mp(e)){Object.assign(this,{...e});return}const r=Ge.getDefaultConfig(),{metadata:n,...a}=e,s=a.client??Ge.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=Fp(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:Ue(),run_type:"chain",project_name:_u(),child_runs:[],api_url:vt("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:vt("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return Ge.sharedClient||(Ge.sharedClient=new Ur),Ge.sharedClient}createChild(e){const r=this.child_execution_order+1,n=new Ge({...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});es in this&&(n[es]=this[es]);const a=Symbol.for("lc:child_config"),s=e.extra?.[a]??this.extra[a];if(jp(s)){const c={...s},u=Lp(c.callbacks)?c.callbacks.copy?.():void 0;u&&(Object.assign(u,{_parentRunId:n.id}),u.handlers?.find($u)?.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=>eo(`${d}:${e}`,eo.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=Dp(a.dotted_order),h=[];for(let p=0;p<d.length-1;p++){const[y,_]=d[p],w=s(_);h.push(y.toISOString().replace(/[-:]/g,"").replace(".","")+w)}const[f]=d[d.length-1];h.push(f.toISOString().replace(/[-:]/g,"").replace(".","")+i),u=h.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=Eu();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){Ts("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=$p();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 Ge({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 Ge({...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=En.fromHeader(n.baggage);c.metadata=u.metadata,c.tags=u.tags,c.project_name=u.project_name,c.replicas=u.replicas}return new Ge(c)}toHeaders(e){const r={"langsmith-trace":this.dotted_order,baggage:new En(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(Ge,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function Mp(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}function $u(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}function _c(t){return Array.isArray(t)&&t.some(e=>$u(e))}function Lp(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}function jp(t){return t!=null&&typeof t.callbacks=="object"&&(_c(t.callbacks?.handlers)||_c(t.callbacks))}function Dp(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 Up(){const t=vt("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){Bp(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(vp(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 Fp(t){return t?t.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):Up()}function Bp(t){if(Object.keys(t).length>0&&He("ENDPOINT"))throw new _p}var zp={};pe(zp,{BaseTracer:()=>wr,isBaseTracer:()=>nr});const qp=t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t};function xs(t,e){if(t)return new Ge({...t,start_time:t._serialized_start_time??t.start_time,parent_run:xs(e),child_runs:t.child_runs.map(r=>xs(r)).filter(r=>r!==void 0),extra:{...t.extra,runtime:fu()},tracingEnabled:!1})}function ts(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}function nr(t){return typeof t._addRunToRunMap=="function"}var wr=class extends Hr{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(t){super(...arguments)}copy(){return this}getRunById(t){if(t!==void 0)return this.usesRunTreeMap?qp(this.runTreeMap.get(t)):this.runMap.get(t)}stringifyError(t){return t instanceof Error?t.message+(t?.stack?`
52
+
53
+ ${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=xs(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=ts(t,"output"),s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),a?.inputs!==void 0&&(s.inputs=ts(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=ts(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}},ln={exports:{}};ln.exports;var vc;function Gp(){return vc||(vc=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})})(ln)),ln.exports}var Hp=Gp();const Pu=yr(Hp);var Vp={};pe(Vp,{ConsoleCallbackHandler:()=>Is});function Le(t,e){return`${t.open}${e}${t.close}`}function Xe(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}function wc(t){return typeof t=="string"?t.trim():t==null?t:Xe(t,t.toString())}function Rt(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:qe}=Pu;var Is=class extends wr{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?Le(Pu.bold,i):i}).join(" > ");return Le(qe.grey,r)}onChainStart(t){const e=this.getBreadcrumbs(t);console.log(`${Le(qe.green,"[chain/start]")} [${e}] Entering Chain run with input: ${Xe(t.inputs,"[inputs]")}`)}onChainEnd(t){const e=this.getBreadcrumbs(t);console.log(`${Le(qe.cyan,"[chain/end]")} [${e}] [${Rt(t)}] Exiting Chain run with output: ${Xe(t.outputs,"[outputs]")}`)}onChainError(t){const e=this.getBreadcrumbs(t);console.log(`${Le(qe.red,"[chain/error]")} [${e}] [${Rt(t)}] Chain run errored with error: ${Xe(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(`${Le(qe.green,"[llm/start]")} [${e}] Entering LLM run with input: ${Xe(r,"[inputs]")}`)}onLLMEnd(t){const e=this.getBreadcrumbs(t);console.log(`${Le(qe.cyan,"[llm/end]")} [${e}] [${Rt(t)}] Exiting LLM run with output: ${Xe(t.outputs,"[response]")}`)}onLLMError(t){const e=this.getBreadcrumbs(t);console.log(`${Le(qe.red,"[llm/error]")} [${e}] [${Rt(t)}] LLM run errored with error: ${Xe(t.error,"[error]")}`)}onToolStart(t){const e=this.getBreadcrumbs(t);console.log(`${Le(qe.green,"[tool/start]")} [${e}] Entering Tool run with input: "${wc(t.inputs.input)}"`)}onToolEnd(t){const e=this.getBreadcrumbs(t);console.log(`${Le(qe.cyan,"[tool/end]")} [${e}] [${Rt(t)}] Exiting Tool run with output: "${wc(t.outputs?.output)}"`)}onToolError(t){const e=this.getBreadcrumbs(t);console.log(`${Le(qe.red,"[tool/error]")} [${e}] [${Rt(t)}] Tool run errored with error: ${Xe(t.error,"[error]")}`)}onRetrieverStart(t){const e=this.getBreadcrumbs(t);console.log(`${Le(qe.green,"[retriever/start]")} [${e}] Entering Retriever run with input: ${Xe(t.inputs,"[inputs]")}`)}onRetrieverEnd(t){const e=this.getBreadcrumbs(t);console.log(`${Le(qe.cyan,"[retriever/end]")} [${e}] [${Rt(t)}] Exiting Retriever run with output: ${Xe(t.outputs,"[outputs]")}`)}onRetrieverError(t){const e=this.getBreadcrumbs(t);console.log(`${Le(qe.red,"[retriever/error]")} [${e}] [${Rt(t)}] Retriever run errored with error: ${Xe(t.error,"[error]")}`)}onAgentAction(t){const e=t,r=this.getBreadcrumbs(t);console.log(`${Le(qe.blue,"[agent/action]")} [${r}] Agent selected action: ${Xe(e.actions[e.actions.length-1],"[action]")}`)}};let rs;const Mu=()=>{if(rs===void 0){const t=Pt("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};rs=new Ur(t)}return rs};let Zp=class{getStore(){}run(e,r){return r()}};const ns=Symbol.for("ls:tracing_async_local_storage"),Jp=new Zp;let Wp=class{getInstance(){return globalThis[ns]??Jp}initializeGlobalInstance(e){globalThis[ns]===void 0&&(globalThis[ns]=e)}};const Kp=new Wp;function Yp(t=!1){const e=Kp.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree.
54
+
55
+ Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function pi(t){return typeof t=="function"&&"langsmith:traceable"in t}var Xp={};pe(Xp,{LangChainTracer:()=>dn});var dn=class Lu extends wr{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??_u(),this.replicas=s,this.exampleId=r,this.client=a??Mu();const i=Lu.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 Ge({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return Yp(!0)}catch{return}}};let qt;function Qp(){const t="default"in St?St.default:St;return new t({autoStart:!0,concurrency:1})}function em(){return typeof qt>"u"&&(qt=Qp()),qt}async function Oe(t,e){if(e===!0){const r=Dr();r!==void 0?await r.run(void 0,async()=>t()):await t()}else qt=em(),qt.add(async()=>{const r=Dr();r!==void 0?await r.run(void 0,async()=>t()):await t()})}async function tm(){const t=Mu();await Promise.allSettled([typeof qt<"u"?qt.onIdle():Promise.resolve(),t.awaitPendingTraceBatches()])}var rm={};pe(rm,{awaitAllCallbacks:()=>tm,consumeCallback:()=>Oe});const nm=t=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(r=>Pt(r)==="true");function ju(t){const e=Dr();return e===void 0?void 0:e.getStore()?.[Rr]?.[t]}const am=Symbol("lc:configure_hooks"),sm=()=>ju(am)||[];var im={};pe(im,{BaseCallbackManager:()=>Du,BaseRunManager:()=>Zr,CallbackManager:()=>gt,CallbackManagerForChainRun:()=>Fu,CallbackManagerForLLMRun:()=>As,CallbackManagerForRetrieverRun:()=>Uu,CallbackManagerForToolRun:()=>Bu,ensureHandler:()=>Fr,parseCallbackConfigArg:()=>om});function om(t){return t?Array.isArray(t)||"name"in t?{callbacks:t}:t:{}}var Du=class{setHandler(t){return this.setHandlers([t])}},Zr=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=>Oe(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=>Oe(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)))}},Uu=class extends Zr{getChild(t){const e=new gt(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=>Oe(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=>Oe(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)))}},As=class extends Zr{async handleLLMNewToken(t,e,r,n,a,s){await Promise.all(this.handlers.map(i=>Oe(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=>Oe(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=>Oe(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)))}},Fu=class extends Zr{getChild(t){const e=new gt(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=>Oe(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=>Oe(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=>Oe(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=>Oe(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)))}},Bu=class extends Zr{getChild(t){const e=new gt(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=>Oe(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=>Oe(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)))}},gt=class Ir 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:Ue();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return nr(h)&&h._createRunForLLMStart(e,[u],d,this._parentRunId,s,this.tags,this.metadata,c),Oe(async()=>{try{await h.handleLLMStart?.(e,[u],d,this._parentRunId,s,this.tags,this.metadata,c)}catch(f){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${f}`),h.raiseError)throw f}},h.awaitHandlers)})),new As(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:Ue();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return nr(h)&&h._createRunForChatModelStart(e,[u],d,this._parentRunId,s,this.tags,this.metadata,c),Oe(async()=>{try{if(h.handleChatModelStart)await h.handleChatModelStart?.(e,[u],d,this._parentRunId,s,this.tags,this.metadata,c);else if(h.handleLLMStart){const f=si(u);await h.handleLLMStart?.(e,[f],d,this._parentRunId,s,this.tags,this.metadata,c)}}catch(f){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${f}`),h.raiseError)throw f}},h.awaitHandlers)})),new As(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,r,n=Ue(),a=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreChain)return nr(c)&&c._createRunForChainStart(e,r,n,this._parentRunId,this.tags,this.metadata,a,o),Oe(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 Fu(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,r,n=Ue(),a=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreAgent)return nr(c)&&c._createRunForToolStart(e,r,n,this._parentRunId,this.tags,this.metadata,o),Oe(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 Bu(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,r,n=Ue(),a=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return nr(c)&&c._createRunForRetrieverStart(e,r,n,this._parentRunId,this.tags,this.metadata,o),Oe(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 Uu(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=>Oe(async()=>{if(!i.ignoreCustomEvent)try{await i.handleCustomEvent?.(e,r,n,this.tags,this.metadata)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}addHandler(e,r=!0){this.handlers.push(e),r&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(r=>r!==e),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==e)}setHandlers(e,r=!0){this.handlers=[],this.inheritableHandlers=[];for(const n of e)this.addHandler(n,r)}addTags(e,r=!0){this.removeTags(e),this.tags.push(...e),r&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(r=>!e.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!e.includes(r))}addMetadata(e,r=!0){this.metadata={...this.metadata,...e},r&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(const r of Object.keys(e))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(e=[],r=!0){const n=new Ir(this._parentRunId);for(const a of this.handlers){const s=this.inheritableHandlers.includes(a);n.addHandler(a,s)}for(const a of this.tags){const s=this.inheritableTags.includes(a);n.addTags([a],s)}for(const a of Object.keys(this.metadata)){const s=Object.keys(this.inheritableMetadata).includes(a);n.addMetadata({[a]:this.metadata[a]},s)}for(const a of e)n.handlers.filter(s=>s.name==="console_callback_handler").some(s=>s.name===a.name)||n.addHandler(a,r);return n}static fromHandlers(e){class r extends Hr{name=Ue();constructor(){super(),Object.assign(this,e)}}const n=new this;return n.addHandler(new r),n}static configure(e,r,n,a,s,i,o){return this._configureSync(e,r,n,a,s,i,o)}static _configureSync(e,r,n,a,s,i,o){let c;(e||r)&&(Array.isArray(e)||!e?(c=new Ir,c.setHandlers(e?.map(Fr)??[],!0)):c=e,c=c.copy(Array.isArray(r)?r.map(Fr):r?.handlers,!1));const u=Pt("LANGCHAIN_VERBOSE")==="true"||o?.verbose,l=dn.getTraceableRunTree()?.tracingEnabled||nm(),d=l||(Pt("LANGCHAIN_TRACING")??!1);if(u||d){if(c||(c=new Ir),u&&!c.handlers.some(h=>h.name===Is.prototype.name)){const h=new Is;c.addHandler(h,!0)}if(d&&!c.handlers.some(h=>h.name==="langchain_tracer")&&l){const h=new dn;c.addHandler(h,!0)}if(l){const h=dn.getTraceableRunTree();h&&c._parentRunId===void 0&&(c._parentRunId=h.id,c.handlers.find(p=>p.name==="langchain_tracer")?.updateFromRunTree(h))}}for(const{contextVar:h,inheritable:f=!0,handlerClass:p,envVar:y}of sm()){const _=y&&Pt(y)==="true"&&p;let w;const T=h!==void 0?ju(h):void 0;T&&gu(T)?w=T:_&&(w=new p({})),w!==void 0&&(c||(c=new Ir),c.handlers.some(E=>E.name===w.name)||c.addHandler(w,f))}return(n||a)&&c&&(c.addTags(n??[]),c.addTags(a??[],!1)),(s||i)&&c&&(c.addMetadata(s??{}),c.addMetadata(i??{},!1)),c}};function Fr(t){return"name"in t?t:Hr.fromMethods(t)}var zu=class{getStore(){}run(t,e){return e()}enterWith(t){}};const cm=new zu,bc=Symbol.for("lc:child_config");var um=class{getInstance(){return Dr()??cm}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[bc]}runWithConfig(t,e,r){const n=gt._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 Ge({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[bc]:t}),s!==void 0&&s[Rr]!==void 0&&(c===void 0&&(c={}),c[Rr]=s[Rr]),a.run(c,e)}initializeGlobalInstance(t){Dr()===void 0&&bh(t)}};const It=new um;var lm={};pe(lm,{AsyncLocalStorageProviderSingleton:()=>It,MockAsyncLocalStorage:()=>zu,_CONTEXT_VARIABLES_KEY:()=>Rr});const as=25;async function Ke(t){return gt._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata)}function Os(...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(Fr(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(Fr(o),!0);e.callbacks=i}else e.callbacks=new gt(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 dm=new Set(["string","number","boolean"]);function de(t){const e=It.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))dm.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=de(t);return e!==void 0&&(delete o.runName,o.callbacks=e),n!==void 0&&(o.recursionLimit=n),r!==void 0&&(o.maxConcurrency=r),a!==void 0&&(o.runName=a),s!==void 0&&(o.configurable={...o.configurable,...s}),i!==void 0&&delete o.runId,o}function Jt(t){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 Ut(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(Tn(e))},e.addEventListener("abort",r),e.aborted&&a(Tn(e))})]).finally(()=>e.removeEventListener("abort",r))}function Tn(t){return t?.reason instanceof Error?t.reason:typeof t?.reason=="string"?new Error(t.reason):new Error("Aborted")}var hm={};pe(hm,{AsyncGeneratorWithSetup:()=>Qt,IterableReadableStream:()=>ct,atee:()=>mi,concat:()=>Wt,pipeGeneratorWithSetup:()=>qu});var ct=class ks 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 ks({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 ks({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 mi(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 Wt(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]=Wt(r[n],a):r[n]=a;return r}else throw new Error(`Cannot concat ${typeof t} and ${typeof e}`)}var Qt=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)=>{It.runWithConfig(Jt(t.config),async()=>{this.firstResult=t.generator.next(),t.startSetup?this.firstResult.then(t.startSetup).then(e,r):this.firstResult.then(n=>e(void 0),r)},!0)})}async next(...t){return this.signal?.throwIfAborted(),this.firstResultUsed?It.runWithConfig(Jt(this.config),this.signal?async()=>Ut(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 qu(t,e,r,n,...a){const s=new Qt({generator:e,startSetup:r,signal:n}),i=await s.setup;return{output:t(s,i,...a),setup:i}}const fm=Object.prototype.hasOwnProperty;function Rs(t,e){return fm.call(t,e)}function Cs(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)Rs(t,r)&&e.push(r);return e}function it(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Ns(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 tr(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function pm(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function $s(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if($s(t[r]))return!0}else if(typeof t=="object"){const r=Cs(t),n=r.length;for(var e=0;e<n;e++)if($s(t[r[e]]))return!0}}return!1}function Ec(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 mm=class extends Error{constructor(t,e,r,n,a){super(Ec(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=Ec(t,{name:e,index:r,operation:n,tree:a})}},Gu={};pe(Gu,{JsonPatchError:()=>Ee,_areEquals:()=>Br,applyOperation:()=>Gt,applyPatch:()=>mr,applyReducer:()=>_m,deepClone:()=>gm,getValueByPointer:()=>Sn,validate:()=>Hu,validator:()=>xn});const Ee=mm,gm=it,sr={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=it(n));const a=Gt(r,{op:"remove",path:this.from}).removed;return Gt(r,{op:"add",path:this.path,value:a}),{newDocument:r,removed:n}},copy:function(t,e,r){const n=Sn(r,this.from);return Gt(r,{op:"add",path:this.path,value:it(n)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:Br(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}};var ym={add:function(t,e,r){return Ns(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:sr.move,copy:sr.copy,test:sr.test,_get:sr._get};function Sn(t,e){if(e=="")return t;var r={op:"_get",path:e};return Gt(t,r),r.value}function Gt(t,e,r=!1,n=!0,a=!0,s=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):xn(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=Br(t,e.value),i.test===!1)throw new Ee("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 Ee("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,t);return i}}else{n||(t=it(t));const o=(e.path||"").split("/");let c=t,u=1,l=o.length,d,h,f;for(typeof r=="function"?f=r:f=xn;;){if(h=o[u],h&&h.indexOf("~")!=-1&&(h=pm(h)),a&&(h=="__proto__"||h=="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[h]===void 0?d=o.slice(0,u).join("/"):u==l-1&&(d=e.path),d!==void 0&&f(e,0,t,d)),u++,Array.isArray(c)){if(h==="-")h=c.length;else{if(r&&!Ns(h))throw new Ee("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);Ns(h)&&(h=~~h)}if(u>=l){if(r&&e.op==="add"&&h>c.length)throw new Ee("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=ym[e.op].call(e,c,h,t);if(p.test===!1)throw new Ee("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return p}}else if(u>=l){const p=sr[e.op].call(e,c,h,t);if(p.test===!1)throw new Ee("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return p}if(c=c[h],r&&u<l&&(!c||typeof c!="object"))throw new Ee("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,t)}}}function mr(t,e,r,n=!0,a=!0){if(r&&!Array.isArray(e))throw new Ee("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=it(t));const s=new Array(e.length);for(let i=0,o=e.length;i<o;i++)s[i]=Gt(t,e[i],r,!0,a,i),t=s[i].newDocument;return s.newDocument=t,s}function _m(t,e,r){const n=Gt(t,e);if(n.test===!1)throw new Ee("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function xn(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new Ee("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(sr[t.op]){if(typeof t.path!="string")throw new Ee("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new Ee('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 Ee("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 Ee("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")&&$s(t.value))throw new Ee("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 Ee("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 Ee("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=Hu([i],r);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new Ee("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new Ee("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function Hu(t,e,r){try{if(!Array.isArray(t))throw new Ee("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)mr(it(e),it(t),r||!0);else{r=r||xn;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(a){if(a instanceof Ee)return a;throw a}}function Br(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(!Br(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],!Br(t[i],e[i]))return!1;return!0}return t!==t&&e!==e}function Vu(t,e,r,n,a){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=Cs(e),i=Cs(t),o=!1,c=i.length-1;c>=0;c--){var u=i[c],l=t[u];if(Rs(e,u)&&!(e[u]===void 0&&l!==void 0&&Array.isArray(e)===!1)){var d=e[u];typeof l=="object"&&l!=null&&typeof d=="object"&&d!=null&&Array.isArray(l)===Array.isArray(d)?Vu(l,d,r,n+"/"+tr(u),a):l!==d&&(a&&r.push({op:"test",path:n+"/"+tr(u),value:it(l)}),r.push({op:"replace",path:n+"/"+tr(u),value:it(d)}))}else Array.isArray(t)===Array.isArray(e)?(a&&r.push({op:"test",path:n+"/"+tr(u),value:it(l)}),r.push({op:"remove",path:n+"/"+tr(u)}),o=!0):(a&&r.push({op:"test",path:n,value:t}),r.push({op:"replace",path:n,value:e}))}if(!(!o&&s.length==i.length))for(var c=0;c<s.length;c++){var u=s[c];!Rs(t,u)&&e[u]!==void 0&&r.push({op:"add",path:n+"/"+tr(u),value:it(e[u])})}}}function gi(t,e,r=!1){var n=[];return Vu(t,e,n,"",r),n}({...Gu});var vm={};pe(vm,{LogStreamCallbackHandler:()=>Ms,RunLog:()=>yi,RunLogPatch:()=>bt,isLogStreamHandler:()=>Zu});var bt=class{ops;constructor(t){this.ops=t.ops??[]}concat(t){const e=this.ops.concat(t.ops),r=mr({},e);return new yi({ops:e,state:r[r.length-1].newDocument})}},yi=class Ps extends bt{state;constructor(e){super(e),this.state=e.state}concat(e){const r=this.ops.concat(e.ops),n=mr(this.state,e.ops);return new Ps({ops:r,state:n[n.length-1].newDocument})}static fromRunLogPatch(e){const r=mr({},e.ops);return new Ps({ops:e.ops,state:r[r.length-1].newDocument})}};const Zu=t=>t.name==="log_stream_tracer";async function Tc(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 Sc(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 wm(t){return t!==void 0&&t.message!==void 0}var Ms=class extends wr{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=ct.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 bt({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 bt({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 Tc(t,this._schemaFormat)),await this.writer.write(new bt({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 Tc(t,this._schemaFormat)}),r.push({op:"add",path:`/logs/${e}/final_output`,value:await Sc(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 bt({ops:r});await this.writer.write(n)}finally{if(t.id===this.rootId){const e=new bt({ops:[{op:"replace",path:"/final_output",value:await Sc(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?wm(r?.chunk)?s=r?.chunk:s=new Xt({id:`run-${t.id}`,content:e}):s=e;const i=new bt({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)}},bm={};pe(bm,{ChatGenerationChunk:()=>js,GenerationChunk:()=>zr,RUN_KEY:()=>Ls});const Ls="__run";var zr=class Ju{text;generationInfo;constructor(e){this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new Ju({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}},js=class Wu extends zr{message;constructor(e){super(e),this.message=e.message}concat(e){return new Wu({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo},message:this.message.concat(e.message)})}};function on({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 Em=t=>t.name==="event_stream_tracer";var Tm=class extends wr{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=ct.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 zr({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=on(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 Xt({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 zr({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=on(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=on(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=on(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()})}},Sm={};pe(Sm,{AsyncCaller:()=>Bn});const xm=[400,401,402,403,404,405,406,407,409],Im=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&&xm.includes(+e))throw t;if(t?.error?.code==="insufficient_quota"){const r=new Error(t?.message);throw r.name="InsufficientQuotaError",r}};var Bn=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(t){this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,this.onFailedAttempt=t.onFailedAttempt??Im;const e="default"in St?St.default:St;this.queue=new e({concurrency:this.maxConcurrency})}call(t,...e){return this.queue.add(()=>wn(()=>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(Tn(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)))}},Ku=class extends wr{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 _i(t){return t?t.lc_runnable:!1}var Am=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 xe(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 Re(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 Om(t){return xe(t)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),Re(t)}function Jr(t){return!t||typeof t!="object"||Array.isArray(t)?!1:!!(xe(t)||Re(t))}function Yu(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 Xu(t){return xe(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 km(t){return!!(Yu(t)||Xu(t))}async function Rm(t,e){if(xe(t))try{return{success:!0,data:await Lc(t,e)}}catch(r){return{success:!1,error:r}}if(Re(t))return await t.safeParseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function vi(t,e){if(xe(t))return await Lc(t,e);if(Re(t))return await t.parseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Cm(t,e){if(xe(t))try{return{success:!0,data:Vs(t,e)}}catch(r){return{success:!1,error:r}}if(Re(t))return t.safeParse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Nm(t,e){if(xe(t))return Vs(t,e);if(Re(t))return t.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function wi(t){if(xe(t))return Ve.get(t)?.description;if(Re(t)||"description"in t&&typeof t.description=="string")return t.description}function $m(t){if(!Jr(t))return!1;if(Re(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(xe(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 Qu(t){return Jr(t)?Re(t)?t._def.typeName==="ZodString":xe(t)?t._zod.def.type==="string":!1:!1}function bi(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 yt(t){return xe(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 zn(t){return xe(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 Pm(t){return!!(bi(t)||yt(t))}function Ds(t){if(Re(t))return t.shape;if(xe(t))return t._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Mm(t,e){if(Re(t))return t.extend(e);if(xe(t))return Gl(t,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Lm(t){if(Re(t))return t.partial();if(xe(t))return Hl(jc,t,void 0);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function In(t,e=!1){if(Re(t))return t.strict();if(yt(t)){const r=t._zod.def.shape;if(e)for(const[s,i]of Object.entries(t._zod.def.shape)){if(yt(i)){const c=In(i,e);r[s]=c}else if(zn(i)){let c=i._zod.def.element;yt(c)&&(c=In(c,e)),r[s]=Zt(i,{...i._zod.def,element:c})}else r[s]=i;const o=Ve.get(i);o&&Ve.add(r[s],o)}const n=Zt(t,{...t._zod.def,shape:r,catchall:zl(ql)}),a=Ve.get(t);return a&&Ve.add(n,a),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Us(t,e=!1){if(bi(t))return t.passthrough();if(yt(t)){const r=t._zod.def.shape;if(e)for(const[s,i]of Object.entries(t._zod.def.shape)){if(yt(i)){const c=Us(i,e);r[s]=c}else if(zn(i)){let c=i._zod.def.element;yt(c)&&(c=Us(c,e)),r[s]=Zt(i,{...i._zod.def,element:c})}else r[s]=i;const o=Ve.get(i);o&&Ve.add(r[s],o)}const n=Zt(t,{...t._zod.def,shape:r,catchall:Vl(Zl)}),a=Ve.get(t);return a&&Ve.add(n,a),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function jm(t){if(Re(t))try{const e=t.parse(void 0);return()=>e}catch{return}if(xe(t))try{const e=Vs(t,void 0);return()=>e}catch{return}}function Dm(t){return Re(t)&&"typeName"in t._def&&t._def.typeName==="ZodEffects"}function Um(t){return xe(t)&&t._zod.def.type==="pipe"}function ir(t,e=!1){if(Re(t))return Dm(t)?ir(t._def.schema,e):t;if(xe(t)){let r=t;if(Um(t)&&(r=ir(t._zod.def.in,e)),e){if(yt(r)){const a=r._zod.def.shape;for(const[s,i]of Object.entries(r._zod.def.shape))a[s]=ir(i,e);r=Zt(r,{...r._zod.def,shape:a})}else if(zn(r)){const a=ir(r._zod.def.element,e);r=Zt(r,{...r._zod.def,element:a})}}const n=Ve.get(t);return n&&Ve.add(r,n),r}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Fm(t,e){if(Re(t)){const r=Ds(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(xe(t)){const r=Ds(t),n={...t._zod.def.shape};for(const[i,o]of Object.entries(r))e(i,o)&&(n[i]=new jc({type:"optional",innerType:o}));const a=Zt(t,{...t._zod.def,shape:n}),s=Ve.get(t);return s&&Ve.add(a,s),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function ss(t){return t.replace(/[^a-zA-Z-_0-9]/g,"_")}const Bm=["*","_","`"];function zm(t){let e="";for(const[r,n]of Object.entries(t))e+=` classDef ${r} ${n};
57
+ `;return e}function qm(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
+ graph TD;
59
+ `:`graph TD;
60
+ `;if(i){const f="default",p={[f]:"{0}({1})"};n!==void 0&&(p[n]="{0}([{1}]):::first"),a!==void 0&&(p[a]="{0}([{1}]):::last");for(const[y,_]of Object.entries(t)){const w=_.name.split(":").pop()??"";let E=Bm.some(R=>w.startsWith(R)&&w.endsWith(R))?`<p>${w}</p>`:w;Object.keys(_.metadata??{}).length&&(E+=`<hr/><small><em>${Object.entries(_.metadata??{}).map(([R,j])=>`${R} = ${j}`).join(`
61
+ `)}</em></small>`);const x=(p[y]??p[f]).replace("{0}",ss(y)).replace("{1}",E);u+=` ${x}
62
+ `}}const l={};for(const f of e){const p=f.source.split(":"),y=f.target.split(":"),_=p.filter((w,T)=>w===y[T]).join(":");l[_]||(l[_]=[]),l[_].push(f)}const d=new Set;function h(f,p){const y=f.length===1&&f[0].source===f[0].target;if(p&&!y){const _=p.split(":").pop();if(d.has(_))throw new Error(`Found duplicate subgraph '${_}' -- 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(_),u+=` subgraph ${_}
63
+ `}for(const _ of f){const{source:w,target:T,data:E,conditional:x}=_;let R="";if(E!==void 0){let j=E;const J=j.split(" ");J.length>c&&(j=Array.from({length:Math.ceil(J.length/c)},(v,ge)=>J.slice(ge*c,(ge+1)*c).join(" ")).join("&nbsp;<br>&nbsp;")),R=x?` -. &nbsp;${j}&nbsp; .-> `:` -- &nbsp;${j}&nbsp; --> `}else R=x?" -.-> ":" --> ";u+=` ${ss(w)}${R}${ss(T)};
64
+ `}for(const _ in l)_.startsWith(`${p}:`)&&_!==p&&h(l[_],_);p&&!y&&(u+=` end
65
+ `)}h(l[""]??[],"");for(const f in l)!f.includes(":")&&f!==""&&h(l[f],f);return i&&(u+=zm(s??{})),u}async function Gm(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 Hm=Symbol("Let zodToJsonSchema decide on which parser to use"),Vm={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"},Zm=t=>({...Vm,...t}),Jm=t=>{const e=Zm(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}]))}},el=(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 Je(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?el(e,t.currentPath):e.join("/")}}function tl(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function fe(t,e,r,n,a){t[e]=r,tl(t,e,n,a)}function Wm(t,e){const r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==A.ZodAny&&(r.items=he(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&fe(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&fe(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(fe(r,"minItems",t.exactLength.value,t.exactLength.message,e),fe(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Km(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?fe(r,"minimum",n.value,n.message,e):fe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),fe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?fe(r,"maximum",n.value,n.message,e):fe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),fe(r,"maximum",n.value,n.message,e));break;case"multipleOf":fe(r,"multipleOf",n.value,n.message,e);break}return r}function Ym(){return{type:"boolean"}}function rl(t,e){return he(t.type._def,e)}const Xm=(t,e)=>he(t.innerType._def,e);function nl(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(a=>nl(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 Qm(t,e)}}const Qm=(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":fe(r,"minimum",n.value,n.message,e);break;case"max":fe(r,"maximum",n.value,n.message,e);break}return r};function eg(t,e){return{...he(t.innerType._def,e),default:t.defaultValue()}}function tg(t,e){return e.effectStrategy==="input"?he(t.schema._def,e):Je(e)}function rg(t){return{type:"string",enum:Array.from(t.values)}}const ng=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function ag(t,e){const r=[he(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),he(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(ng(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 sg(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 is;const tt={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:()=>(is===void 0&&(is=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),is),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 al(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":fe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":fe(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":rt(r,"email",n.message,e);break;case"format:idn-email":rt(r,"idn-email",n.message,e);break;case"pattern:zod":je(r,tt.email,n.message,e);break}break;case"url":rt(r,"uri",n.message,e);break;case"uuid":rt(r,"uuid",n.message,e);break;case"regex":je(r,n.regex,n.message,e);break;case"cuid":je(r,tt.cuid,n.message,e);break;case"cuid2":je(r,tt.cuid2,n.message,e);break;case"startsWith":je(r,RegExp(`^${os(n.value,e)}`),n.message,e);break;case"endsWith":je(r,RegExp(`${os(n.value,e)}$`),n.message,e);break;case"datetime":rt(r,"date-time",n.message,e);break;case"date":rt(r,"date",n.message,e);break;case"time":rt(r,"time",n.message,e);break;case"duration":rt(r,"duration",n.message,e);break;case"length":fe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),fe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":je(r,RegExp(os(n.value,e)),n.message,e);break;case"ip":n.version!=="v6"&&rt(r,"ipv4",n.message,e),n.version!=="v4"&&rt(r,"ipv6",n.message,e);break;case"base64url":je(r,tt.base64url,n.message,e);break;case"jwt":je(r,tt.jwt,n.message,e);break;case"cidr":n.version!=="v6"&&je(r,tt.ipv4Cidr,n.message,e),n.version!=="v4"&&je(r,tt.ipv6Cidr,n.message,e);break;case"emoji":je(r,tt.emoji(),n.message,e);break;case"ulid":je(r,tt.ulid,n.message,e);break;case"base64":switch(e.base64Strategy){case"format:binary":rt(r,"binary",n.message,e);break;case"contentEncoding:base64":fe(r,"contentEncoding","base64",n.message,e);break;case"pattern:zod":je(r,tt.base64,n.message,e);break}break;case"nanoid":je(r,tt.nanoid,n.message,e);break}return r}function os(t,e){return e.patternStrategy==="escape"?og(t):t}const ig=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function og(t){let e="";for(let r=0;r<t.length;r++)ig.has(t[r])||(e+="\\"),e+=t[r];return e}function rt(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}}})):fe(t,"format",e,r,n)}function je(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:xc(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):fe(t,"pattern",xc(e,n),r,n)}function xc(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
+ ]))`;continue}else if(n[c]==="$"){a+=`($|(?=[\r
68
+ ]))`;continue}}if(r.s&&n[c]==="."){a+=i?`${n[c]}\r
69
+ `:`[${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 sl(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===A.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,a)=>({...n,[a]:he(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",a]})??Je(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const r={type:"object",additionalProperties:he(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===A.ZodString&&t.keyType._def.checks?.length){const{type:n,...a}=al(t.keyType._def,e);return{...r,propertyNames:a}}else{if(t.keyType?._def.typeName===A.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===A.ZodBranded&&t.keyType._def.type._def.typeName===A.ZodString&&t.keyType._def.type._def.checks?.length){const{type:n,...a}=rl(t.keyType._def,e);return{...r,propertyNames:a}}}return r}function cg(t,e){if(e.mapStrategy==="record")return sl(t,e);const r=he(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Je(e),n=he(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Je(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function ug(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 lg(t){return t.target==="openAi"?void 0:{not:Je({...t,currentPath:[...t.currentPath,"not"]})}}function dg(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const An={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function hg(t,e){if(e.target==="openApi3")return Ic(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in An&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((a,s)=>{const i=An[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 Ic(t,e)}const Ic=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,a)=>he(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 fg(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:An[t.innerType._def.typeName],nullable:!0}:{type:[An[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=he(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=he(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function pg(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",tl(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?fe(r,"minimum",n.value,n.message,e):fe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),fe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?fe(r,"maximum",n.value,n.message,e):fe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),fe(r,"maximum",n.value,n.message,e));break;case"multipleOf":fe(r,"multipleOf",n.value,n.message,e);break}return r}function mg(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=yg(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=he(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=gg(t,e);return i!==void 0&&(n.additionalProperties=i),n}function gg(t,e){if(t.catchall._def.typeName!=="ZodNever")return he(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 yg(t){try{return t.isOptional()}catch{return!0}}const _g=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return he(t.innerType._def,e);const r=he(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Je(e)},r]}:Je(e)},vg=(t,e)=>{if(e.pipeStrategy==="input")return he(t.in._def,e);if(e.pipeStrategy==="output")return he(t.out._def,e);const r=he(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=he(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(a=>a!==void 0)}};function wg(t,e){return he(t.type._def,e)}function bg(t,e){const n={type:"array",uniqueItems:!0,items:he(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&fe(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&fe(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Eg(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>he(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:he(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>he(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Tg(t){return{not:Je(t)}}function Sg(t){return Je(t)}const xg=(t,e)=>he(t.innerType._def,e),Ig=(t,e,r)=>{switch(e){case A.ZodString:return al(t,r);case A.ZodNumber:return pg(t,r);case A.ZodObject:return mg(t,r);case A.ZodBigInt:return Km(t,r);case A.ZodBoolean:return Ym();case A.ZodDate:return nl(t,r);case A.ZodUndefined:return Tg(r);case A.ZodNull:return dg(r);case A.ZodArray:return Wm(t,r);case A.ZodUnion:case A.ZodDiscriminatedUnion:return hg(t,r);case A.ZodIntersection:return ag(t,r);case A.ZodTuple:return Eg(t,r);case A.ZodRecord:return sl(t,r);case A.ZodLiteral:return sg(t,r);case A.ZodEnum:return rg(t);case A.ZodNativeEnum:return ug(t);case A.ZodNullable:return fg(t,r);case A.ZodOptional:return _g(t,r);case A.ZodMap:return cg(t,r);case A.ZodSet:return bg(t,r);case A.ZodLazy:return()=>t.getter()._def;case A.ZodPromise:return wg(t,r);case A.ZodNaN:case A.ZodNever:return lg(r);case A.ZodEffects:return tg(t,r);case A.ZodAny:return Je(r);case A.ZodUnknown:return Sg(r);case A.ZodDefault:return eg(t,r);case A.ZodBranded:return rl(t,r);case A.ZodReadonly:return xg(t,r);case A.ZodCatch:return Xm(t,r);case A.ZodPipeline:return vg(t,r);case A.ZodFunction:case A.ZodVoid:case A.ZodSymbol:return;default:return(n=>{})()}};function he(t,e,r=!1){const n=e.seen.get(t);if(e.override){const o=e.override?.(t,e,n,r);if(o!==Hm)return o}if(n&&!r){const o=Ag(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=Ig(t,t.typeName,e),i=typeof s=="function"?he(s(),e):s;if(i&&Og(t,e,i),e.postProcess){const o=e.postProcess(i,t,e);return a.jsonSchema=i,o}return a.jsonSchema=i,i}const Ag=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:el(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`),Je(e)):e.$refStrategy==="seen"?Je(e):void 0}},Og=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),kg=(t,e)=>{const r=Jm(e);let n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((o,[c,u])=>({...o,[c]:he(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??Je(r)}),{}):void 0;const a=typeof e=="string"?e:e?.name,s=he(t._def,r,!1)??Je(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 Ht(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(!Ht(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(!Ht(t[i],e[i]))return!1;return!0}return t===e}function at(t){return encodeURI(Rg(t))}function Rg(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}const Cg={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Ng={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},$g={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 Pg=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 Nt(t,e=Object.create(null),r=Pg,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:Nt(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($g[s])continue;const i=`${n}/${at(s)}`,o=t[s];if(Array.isArray(o)){if(Cg[s]){const c=o.length;for(let u=0;u<c;u++)Nt(o[u],e,r,`${i}/${u}`)}}else if(Ng[s])for(let c in o)Nt(o[c],e,r,`${i}/${at(c)}`);else Nt(o,e,r,i)}return e}const Mg=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Lg=[0,31,28,31,30,31,30,31,31,30,31,30,31],jg=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Dg=/^(?=.{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,Ug=/^(?:[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,Fg=/^(?:(?:[^\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,Bg=/^(?:(?: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,zg=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,qg=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Gg=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Hg=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Vg=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))},Zg=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Jg=/^((([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,Wg=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 ft(t){return t.test.bind(t)}const Ac={date:il,time:ol.bind(void 0,!1),"date-time":Xg,duration:Wg,uri:ty,"uri-reference":ft(Ug),"uri-template":ft(Fg),url:ft(Bg),email:Vg,hostname:ft(Dg),ipv4:ft(Zg),ipv6:ft(Jg),regex:ny,uuid:ft(zg),"json-pointer":ft(qg),"json-pointer-uri-fragment":ft(Gg),"relative-json-pointer":ft(Hg)};function Kg(t){return t%4===0&&(t%100!==0||t%400===0)}function il(t){const e=t.match(Mg);if(!e)return!1;const r=+e[1],n=+e[2],a=+e[3];return n>=1&&n<=12&&a>=1&&a<=(n==2&&Kg(r)?29:Lg[n])}function ol(t,e){const r=e.match(jg);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 Yg=/t|\s/i;function Xg(t){const e=t.split(Yg);return e.length==2&&il(e[0])&&ol(!0,e[1])}const Qg=/\/|:/,ey=/^(?:[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 ty(t){return Qg.test(t)&&ey.test(t)}const ry=/[^\\]\\Z/;function ny(t){if(ry.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}function ay(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 ve(t,e,r="2019-09",n=Nt(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:h,$recursiveAnchor:f,type:p,const:y,enum:_,required:w,not:T,anyOf:E,allOf:x,oneOf:R,if:j,then:J,else:v,format:ge,properties:_e,patternProperties:oe,additionalProperties:Ne,unevaluatedProperties:wt,minProperties:C,maxProperties:O,propertyNames:k,dependentRequired:B,dependentSchemas:q,dependencies:F,prefixItems:Z,items:ae,additionalItems:ee,unevaluatedItems:le,contains:Te,minContains:ce,maxContains:g,minItems:m,maxItems:S,uniqueItems:b,minimum:se,maximum:me,exclusiveMinimum:ye,exclusiveMaximum:Ie,multipleOf:$e,minLength:et,maxLength:be,pattern:Ye,__absolute_ref__:er,__absolute_recursive_ref__:Yr}=e,P=[];if(f===!0&&s===null&&(s=e),h==="#"){const W=s===null?n[Yr]:s,H=`${o}/$recursiveRef`,Q=ve(t,s===null?e:s,r,n,a,W,i,H,c);Q.valid||P.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:H,error:"A subschema had errors."},...Q.errors)}if(d!==void 0){const H=n[er||d];if(H===void 0){let N=`Unresolved $ref "${d}".`;throw er&&er!==d&&(N+=` Absolute URI "${er}".`),N+=`
71
+ Known schemas:
72
+ - ${Object.keys(n).join(`
73
+ - `)}`,new Error(N)}const Q=`${o}/$ref`,D=ve(t,H,r,n,a,s,i,Q,c);if(D.valid||P.push({instanceLocation:i,keyword:"$ref",keywordLocation:Q,error:"A subschema had errors."},...D.errors),r==="4"||r==="7")return{valid:P.length===0,errors:P}}if(Array.isArray(p)){let W=p.length,H=!1;for(let Q=0;Q<W;Q++)if(l===p[Q]||p[Q]==="integer"&&l==="number"&&t%1===0&&t===t){H=!0;break}H||P.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)&&P.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${p}".`}):p!==void 0&&l!==p&&P.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${p}".`});if(y!==void 0&&(l==="object"||l==="array"?Ht(t,y)||P.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(y)}.`}):t!==y&&P.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})),_!==void 0&&(l==="object"||l==="array"?_.some(W=>Ht(t,W))||P.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(_)}.`}):_.some(W=>t===W)||P.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(_)}.`})),T!==void 0){const W=`${o}/not`;ve(t,T,r,n,a,s,i,W).valid&&P.push({instanceLocation:i,keyword:"not",keywordLocation:W,error:'Instance matched "not" schema.'})}let Bt=[];if(E!==void 0){const W=`${o}/anyOf`,H=P.length;let Q=!1;for(let D=0;D<E.length;D++){const N=E[D],Y=Object.create(c),K=ve(t,N,r,n,a,f===!0?s:null,i,`${W}/${D}`,Y);P.push(...K.errors),Q=Q||K.valid,K.valid&&Bt.push(Y)}Q?P.length=H:P.splice(H,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:W,error:"Instance does not match any subschemas."})}if(x!==void 0){const W=`${o}/allOf`,H=P.length;let Q=!0;for(let D=0;D<x.length;D++){const N=x[D],Y=Object.create(c),K=ve(t,N,r,n,a,f===!0?s:null,i,`${W}/${D}`,Y);P.push(...K.errors),Q=Q&&K.valid,K.valid&&Bt.push(Y)}Q?P.length=H:P.splice(H,0,{instanceLocation:i,keyword:"allOf",keywordLocation:W,error:"Instance does not match every subschema."})}if(R!==void 0){const W=`${o}/oneOf`,H=P.length,Q=R.filter((D,N)=>{const Y=Object.create(c),K=ve(t,D,r,n,a,f===!0?s:null,i,`${W}/${N}`,Y);return P.push(...K.errors),K.valid&&Bt.push(Y),K.valid}).length;Q===1?P.length=H:P.splice(H,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:W,error:`Instance does not match exactly one subschema (${Q} matches).`})}if((l==="object"||l==="array")&&Object.assign(c,...Bt),j!==void 0){const W=`${o}/if`;if(ve(t,j,r,n,a,s,i,W,c).valid){if(J!==void 0){const Q=ve(t,J,r,n,a,s,i,`${o}/then`,c);Q.valid||P.push({instanceLocation:i,keyword:"if",keywordLocation:W,error:'Instance does not match "then" schema.'},...Q.errors)}}else if(v!==void 0){const Q=ve(t,v,r,n,a,s,i,`${o}/else`,c);Q.valid||P.push({instanceLocation:i,keyword:"if",keywordLocation:W,error:'Instance does not match "else" schema.'},...Q.errors)}}if(l==="object"){if(w!==void 0)for(const D of w)D in t||P.push({instanceLocation:i,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${D}".`});const W=Object.keys(t);if(C!==void 0&&W.length<C&&P.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${C} properties.`}),O!==void 0&&W.length>O&&P.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${O} properties.`}),k!==void 0){const D=`${o}/propertyNames`;for(const N in t){const Y=`${i}/${at(N)}`,K=ve(N,k,r,n,a,s,Y,D);K.valid||P.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:D,error:`Property name "${N}" does not match schema.`},...K.errors)}}if(B!==void 0){const D=`${o}/dependantRequired`;for(const N in B)if(N in t){const Y=B[N];for(const K of Y)K in t||P.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:D,error:`Instance has "${N}" but does not have "${K}".`})}}if(q!==void 0)for(const D in q){const N=`${o}/dependentSchemas`;if(D in t){const Y=ve(t,q[D],r,n,a,s,i,`${N}/${at(D)}`,c);Y.valid||P.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:N,error:`Instance has "${D}" but does not match dependant schema.`},...Y.errors)}}if(F!==void 0){const D=`${o}/dependencies`;for(const N in F)if(N in t){const Y=F[N];if(Array.isArray(Y))for(const K of Y)K in t||P.push({instanceLocation:i,keyword:"dependencies",keywordLocation:D,error:`Instance has "${N}" but does not have "${K}".`});else{const K=ve(t,Y,r,n,a,s,i,`${D}/${at(N)}`);K.valid||P.push({instanceLocation:i,keyword:"dependencies",keywordLocation:D,error:`Instance has "${N}" but does not match dependant schema.`},...K.errors)}}}const H=Object.create(null);let Q=!1;if(_e!==void 0){const D=`${o}/properties`;for(const N in _e){if(!(N in t))continue;const Y=`${i}/${at(N)}`,K=ve(t[N],_e[N],r,n,a,s,Y,`${D}/${at(N)}`);if(K.valid)c[N]=H[N]=!0;else if(Q=a,P.push({instanceLocation:i,keyword:"properties",keywordLocation:D,error:`Property "${N}" does not match schema.`},...K.errors),Q)break}}if(!Q&&oe!==void 0){const D=`${o}/patternProperties`;for(const N in oe){const Y=new RegExp(N,"u"),K=oe[N];for(const ze in t){if(!Y.test(ze))continue;const Oi=`${i}/${at(ze)}`,ki=ve(t[ze],K,r,n,a,s,Oi,`${D}/${at(N)}`);ki.valid?c[ze]=H[ze]=!0:(Q=a,P.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:D,error:`Property "${ze}" matches pattern "${N}" but does not match associated schema.`},...ki.errors))}}}if(!Q&&Ne!==void 0){const D=`${o}/additionalProperties`;for(const N in t){if(H[N])continue;const Y=`${i}/${at(N)}`,K=ve(t[N],Ne,r,n,a,s,Y,D);K.valid?c[N]=!0:(Q=a,P.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:D,error:`Property "${N}" does not match additional properties schema.`},...K.errors))}}else if(!Q&&wt!==void 0){const D=`${o}/unevaluatedProperties`;for(const N in t)if(!c[N]){const Y=`${i}/${at(N)}`,K=ve(t[N],wt,r,n,a,s,Y,D);K.valid?c[N]=!0:P.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:D,error:`Property "${N}" does not match unevaluated properties schema.`},...K.errors)}}}else if(l==="array"){S!==void 0&&t.length>S&&P.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${t.length} > ${S}).`}),m!==void 0&&t.length<m&&P.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${t.length} < ${m}).`});const W=t.length;let H=0,Q=!1;if(Z!==void 0){const D=`${o}/prefixItems`,N=Math.min(Z.length,W);for(;H<N;H++){const Y=ve(t[H],Z[H],r,n,a,s,`${i}/${H}`,`${D}/${H}`);if(c[H]=!0,!Y.valid&&(Q=a,P.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:D,error:"Items did not match schema."},...Y.errors),Q))break}}if(ae!==void 0){const D=`${o}/items`;if(Array.isArray(ae)){const N=Math.min(ae.length,W);for(;H<N;H++){const Y=ve(t[H],ae[H],r,n,a,s,`${i}/${H}`,`${D}/${H}`);if(c[H]=!0,!Y.valid&&(Q=a,P.push({instanceLocation:i,keyword:"items",keywordLocation:D,error:"Items did not match schema."},...Y.errors),Q))break}}else for(;H<W;H++){const N=ve(t[H],ae,r,n,a,s,`${i}/${H}`,D);if(c[H]=!0,!N.valid&&(Q=a,P.push({instanceLocation:i,keyword:"items",keywordLocation:D,error:"Items did not match schema."},...N.errors),Q))break}if(!Q&&ee!==void 0){const N=`${o}/additionalItems`;for(;H<W;H++){const Y=ve(t[H],ee,r,n,a,s,`${i}/${H}`,N);c[H]=!0,Y.valid||(Q=a,P.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:N,error:"Items did not match additional items schema."},...Y.errors))}}}if(Te!==void 0)if(W===0&&ce===void 0)P.push({instanceLocation:i,keyword:"contains",keywordLocation:`${o}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(ce!==void 0&&W<ce)P.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array has less items (${W}) than minContains (${ce}).`});else{const D=`${o}/contains`,N=P.length;let Y=0;for(let K=0;K<W;K++){const ze=ve(t[K],Te,r,n,a,s,`${i}/${K}`,D);ze.valid?(c[K]=!0,Y++):P.push(...ze.errors)}Y>=(ce||0)&&(P.length=N),ce===void 0&&g===void 0&&Y===0?P.splice(N,0,{instanceLocation:i,keyword:"contains",keywordLocation:D,error:"Array does not contain item matching schema."}):ce!==void 0&&Y<ce?P.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array must contain at least ${ce} items matching schema. Only ${Y} items were found.`}):g!==void 0&&Y>g&&P.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${g} items matching schema. ${Y} items were found.`})}if(!Q&&le!==void 0){const D=`${o}/unevaluatedItems`;for(H;H<W;H++){if(c[H])continue;const N=ve(t[H],le,r,n,a,s,`${i}/${H}`,D);c[H]=!0,N.valid||P.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:D,error:"Items did not match unevaluated items schema."},...N.errors)}}if(b)for(let D=0;D<W;D++){const N=t[D],Y=typeof N=="object"&&N!==null;for(let K=0;K<W;K++){if(D===K)continue;const ze=t[K];(N===ze||Y&&(typeof ze=="object"&&ze!==null)&&Ht(N,ze))&&(P.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${o}/uniqueItems`,error:`Duplicate items at indexes ${D} and ${K}.`}),D=Number.MAX_SAFE_INTEGER,K=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(r==="4"?(se!==void 0&&(ye===!0&&t<=se||t<se)&&P.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${t} is less than ${ye?"or equal to ":""} ${se}.`}),me!==void 0&&(Ie===!0&&t>=me||t>me)&&P.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${t} is greater than ${Ie?"or equal to ":""} ${me}.`})):(se!==void 0&&t<se&&P.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${t} is less than ${se}.`}),me!==void 0&&t>me&&P.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${t} is greater than ${me}.`}),ye!==void 0&&t<=ye&&P.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${t} is less than ${ye}.`}),Ie!==void 0&&t>=Ie&&P.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${t} is greater than or equal to ${Ie}.`})),$e!==void 0){const W=t%$e;Math.abs(0-W)>=11920929e-14&&Math.abs($e-W)>=11920929e-14&&P.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${t} is not a multiple of ${$e}.`})}}else if(l==="string"){const W=et===void 0&&be===void 0?0:ay(t);et!==void 0&&W<et&&P.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${W} < ${et}).`}),be!==void 0&&W>be&&P.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${W} > ${be}).`}),Ye!==void 0&&!new RegExp(Ye,"u").test(t)&&P.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),ge!==void 0&&Ac[ge]&&!Ac[ge](t)&&P.push({instanceLocation:i,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${ge}".`})}return{valid:P.length===0,errors:P}}class sy{schema;draft;shortCircuit;lookup;constructor(e,r="2019-09",n=!0){this.schema=e,this.draft=r,this.shortCircuit=n,this.lookup=Nt(e)}validate(e){return ve(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,r){r&&(e={...e,$id:r}),Nt(e,this.lookup)}}var iy={};pe(iy,{Validator:()=>sy,deepCompareStrict:()=>Ht,toJsonSchema:()=>br,validatesOnlyStrings:()=>hn});function br(t){if(xe(t)){const e=ir(t,!0);if(yt(e)){const r=In(e,!0);return Ci(r)}else return Ci(t)}return Re(t)?kg(t):t}function hn(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=>hn(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=>hn(r))}if("not"in t)return!1;if("$ref"in t&&typeof t.$ref=="string"){const e=t.$ref,r=Nt(t);return r[e]?hn(r[e]):!1}return!1}var oy={};pe(oy,{Graph:()=>Ei});function cy(t,e){if(t!==void 0&&!Cr(t))return t;if(_i(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 uy(t){return _i(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...br(t.data.schema),title:t.data.name}}}var Ei=class cl{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]=Cr(r.id)?n:r.id}),{nodes:Object.values(this.nodes).map(r=>({id:e[r.id],...uy(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??Ue(),s={id:a,data:e,name:cy(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 Oc(this)}lastNode(){return kc(this)}extend(e,r=""){let n=r;Object.values(e.nodes).map(u=>u.id).every(Cr)&&(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&&Oc(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&kc(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 Cr(a)&&r.get(s)===1?s:a};return new cl({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 qm(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 Gm(r,{backgroundColor:e?.backgroundColor})}};function Oc(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 kc(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 ly(t){const e=new TextEncoder,r=new ReadableStream({async start(n){for await(const a of t)n.enqueue(e.encode(`event: data
74
+ data: ${JSON.stringify(a)}
75
+
76
+ `));n.enqueue(e.encode(`event: end
77
+
78
+ `)),n.close()}});return ct.fromReadableStream(r)}function Rc(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}const dy=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function";function Fs(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*Cc(t,e){for(;;){const{value:r,done:n}=It.runWithConfig(Jt(t),e.next.bind(e),!0);if(n)break;yield r}}async function*Bs(t,e){const r=e[Symbol.asyncIterator]();for(;;){const{value:n,done:a}=await It.runWithConfig(Jt(t),r.next.bind(e),!0);if(a)break;yield n}}function ke(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}var Se=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 Ti({bound:this,kwargs:{},config:{},maxAttemptNumber:t?.stopAfterAttempt,...t})}withConfig(t){return new gr({bound:this,config:t,kwargs:{}})}withFallbacks(t){const e=Array.isArray(t)?t:t.fallbacks;return new pl({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(de);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)=>de(a===0?t:r))}return Array.from({length:e},()=>de(t))}async batch(t,e,r){const n=this._getOptionsList(e??{},t.length),a=n[0]?.maxConcurrency??r?.maxConcurrency,s=new Bn({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=de(e),n=new Qt({generator:this._streamIterator(t,r),config:r});return await n.setup,ct.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(t){let e;t===void 0?e=de(t):e=de({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=de(r),s=await(await Ke(n))?.handleChainStart(this.toJSON(),ke(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 Ut(o,r?.signal)}catch(o){throw await s?.handleChainError(o),o}return await s?.handleChainEnd(ke(i,"output")),i}async _batchWithConfig(t,e,r,n){const a=this._getOptionsList(r??{},e.length),s=await Promise.all(a.map(Ke)),i=await Promise.all(s.map(async(c,u)=>{const l=await c?.handleChainStart(this.toJSON(),ke(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 Ut(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(ke(o,"output")))),o}_concatOutputChunks(t,e){return Wt(t,e)}async*_transformStreamWithConfig(t,e,r){let n,a=!0,s,i=!0;const o=de(r),c=await Ke(o),u=this;async function*l(){for await(const h of t){if(a)if(n===void 0)n=h;else try{n=u._concatOutputChunks(n,h)}catch{n=void 0,a=!1}yield h}}let d;try{const h=await qu(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=h.setup;const f=d?.handlers.find(Em);let p=h.output;f!==void 0&&d!==void 0&&(p=f.tapOutputIterable(d.runId,p));const y=d?.handlers.find(Zu);y!==void 0&&d!==void 0&&(p=y.tapOutputIterable(d.runId,p));for await(const _ of p)if(yield _,i)if(s===void 0)s=_;else try{s=this._concatOutputChunks(s,_)}catch{s=void 0,i=!1}}catch(h){throw await d?.handleChainError(h,void 0,void 0,void 0,{inputs:ke(n,"input")}),h}await d?.handleChainEnd(s??{},void 0,void 0,void 0,{inputs:ke(n,"input")})}getGraph(t){const e=new Ei,r=e.addNode({name:`${this.getName()}Input`,schema:Gi()}),n=e.addNode(this),a=e.addNode({name:`${this.getName()}Output`,schema:Gi()});return e.addEdge(r,n),e.addEdge(n,a),e}pipe(t){return new qn({first:this,last:ot(t)})}pick(t){return this.pipe(new ml(t))}assign(t){return this.pipe(new Si(new Er({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,de(e))}async*streamLog(t,e,r){const n=new Ms({...r,autoClose:!1,_schemaFormat:"original"}),a=de(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 bt({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"?ly(n):ct.fromAsyncGenerator(n)}async*_streamEventsV2(t,e,r){const n=new Tm({...r,autoClose:!1}),a=de(e),s=a.runId??Ue();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 f=i.copy();f.addHandler(n,!0),a.callbacks=f}const o=new AbortController,c=this;async function u(){let f,p=null;try{e?.signal?"any"in AbortSignal?f=AbortSignal.any([o.signal,e.signal]):(f=e.signal,p=()=>{o.abort()},e.signal.addEventListener("abort",p,{once:!0})):f=o.signal;const y=await c.stream(t,{...a,signal:f}),_=n.tapOutputIterable(s,y);for await(const w of _)if(o.signal.aborted)break}finally{await n.finish(),f&&p&&f.removeEventListener("abort",p)}}const l=u();let d=!1,h;try{for await(const f of n){if(!d){f.data.input=t,d=!0,h=f.run_id,yield f;continue}f.run_id===h&&f.event.endsWith("_end")&&f.data?.input&&delete f.data.input,yield f}}finally{o.abort(),await l}}async*_streamEventsV1(t,e,r){let n,a=!1;const s=de(e),i=s.tags??[],o=s.metadata??{},c=s.runName??this.getName(),u=new Ms({...r,autoClose:!1,_schemaFormat:"streaming_events"}),l=new Am({...r}),d=this._streamLog(t,u,s);for await(const f of d){if(n?n=n.concat(f):n=yi.fromRunLogPatch(f),n.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!a){a=!0;const w={...n.state},T={run_id:w.id,event:`on_${w.type}_start`,name:c,tags:i,metadata:o,data:{input:t}};l.includeEvent(T,w.type)&&(yield T)}const p=f.ops.filter(w=>w.path.startsWith("/logs/")).map(w=>w.path.split("/")[2]),y=[...new Set(p)];for(const w of y){let T,E={};const x=n.state.logs[w];if(x.end_time===void 0?x.streamed_output.length>0?T="stream":T="start":T="end",T==="start")x.inputs!==void 0&&(E.input=x.inputs);else if(T==="end")x.inputs!==void 0&&(E.input=x.inputs),E.output=x.final_output;else if(T==="stream"){const R=x.streamed_output.length;if(R!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${R} instead. Encountered in: "${x.name}"`);E={chunk:x.streamed_output[0]},x.streamed_output=[]}yield{event:`on_${x.type}_${T}`,name:x.name,run_id:x.id,tags:x.tags,metadata:x.metadata,data:E}}const{state:_}=n;if(_.streamed_output.length>0){const w=_.streamed_output.length;if(w!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${w} instead. Encountered in: "${_.name}"`);const T={chunk:_.streamed_output[0]};_.streamed_output=[];const E={event:`on_${_.type}_stream`,run_id:_.id,tags:i,metadata:o,name:c,data:T};l.includeEvent(E,_.type)&&(yield E)}}const h=n?.state;if(h!==void 0){const f={event:`on_${h.type}_end`,name:c,run_id:h.id,tags:i,metadata:o,data:{output:h.final_output}};l.includeEvent(f,h.type)&&(yield f)}}static isRunnable(t){return _i(t)}withListeners({onStart:t,onEnd:e,onError:r}){return new gr({bound:this,config:{},configFactories:[n=>({callbacks:[new Ku({config:n,onStart:t,onEnd:e,onError:r})]})]})}asTool(t){return gy(this,t)}},gr=class ul extends Se{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=Os(this.config,...e);return Os(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 Ti({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(de(s),this.kwargs))):await this._mergeConfig(de(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(de(r),this.kwargs))}async stream(e,r){return this.bound.stream(e,await this._mergeConfig(de(r),this.kwargs))}async*transform(e,r){yield*this.bound.transform(e,await this._mergeConfig(de(r),this.kwargs))}streamEvents(e,r,n){const a=this,s=async function*(){yield*a.bound.streamEvents(e,{...await a._mergeConfig(de(r),a.kwargs),version:r.version},n)};return ct.fromAsyncGenerator(s())}static isRunnableBinding(e){return e.bound&&Se.isRunnable(e.bound)}withListeners({onStart:e,onEnd:r,onError:n}){return new ul({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[a=>({callbacks:[new Ku({config:a,onStart:e,onEnd:r,onError:n})]})]})}},hy=class ll extends Se{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 ll({bound:this.bound.withListeners({onStart:e,onEnd:r,onError:n})})}},Ti=class extends gr{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 wn(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 wn(async s=>{const i=t.map((d,h)=>h).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 h=u[d],f=i[d];h instanceof Error&&l===void 0&&(l=h,l.input=o[d]),a[f.toString()]=h}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)}},qn=class Ar extends Se{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=de(r),s=await(await Ke(n))?.handleChainStart(this.toJSON(),ke(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 Ut(d,r?.signal)}if(r?.signal?.aborted)throw Tn(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(ke(o,"output")),o}async batch(e,r,n){const a=this._getOptionsList(r??{},e.length),s=await Promise.all(a.map(Ke)),i=await Promise.all(s.map(async(c,u)=>{const l=await c?.handleChainStart(this.toJSON(),ke(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,h)=>{const f=d?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return we(a[h],{callbacks:f})}),n);o=await Ut(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(ke(o,"output")))),o}_concatOutputChunks(e,r){return this.last._concatOutputChunks(e,r)}async*_streamIterator(e,r){const n=await Ke(r),{runId:a,...s}=r??{},i=await n?.handleChainStart(this.toJSON(),ke(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 h=1;h<o.length;h+=1)d=await o[h].transform(d,we(s,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${h+1}`)}));for await(const h of d)if(r?.signal?.throwIfAborted(),yield h,c)if(u===void 0)u=h;else try{u=this._concatOutputChunks(u,h)}catch{u=void 0,c=!1}}catch(d){throw await i?.handleChainError(d),d}await i?.handleChainEnd(ke(u,"output"))}getGraph(e){const r=new Ei;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:ot(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&Se.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:ot(e),middle:r.slice(0,-1).map(ot),last:ot(r[r.length-1])})}},Er=class dl extends Se{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]=ot(n)}static from(e){return new dl({steps:e})}async invoke(e,r){const n=de(r),s=await(await Ke(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 Ut(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=mi(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 Ut(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=de(r),s=new Qt({generator:this.transform(n(),a),config:a});return await s.setup,ct.fromAsyncGenerator(s)}},fy=class hl extends Se{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(e){if(super(e),!pi(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 Ke(n),s=this.func(we(n,{callbacks:a}),e);return Ut(s,n?.signal)}async*_streamIterator(e,r){const[n]=this._getOptionsList(r??{},1),a=await this.invoke(e,r);if(Fs(a)){for await(const s of a)n?.signal?.throwIfAborted(),yield s;return}if(dy(a)){for(;;){n?.signal?.throwIfAborted();const s=a.next();if(s.done)break;yield s.value}return}yield a}static from(e){return new hl({func:e})}};function py(t){if(pi(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var Ft=class fl extends Se{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(e){if(pi(e.func))return fy.from(e.func);super(e),py(e.func),this.func=e.func}static from(e){return new fl({func:e})}async _invoke(e,r,n){return new Promise((a,s)=>{const i=we(r,{callbacks:n?.getChild(),recursionLimit:(r?.recursionLimit??as)-1});It.runWithConfig(Jt(i),async()=>{try{let o=await this.func(e,{...i});if(o&&Se.isRunnable(o)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(e,{...i,recursionLimit:(i.recursionLimit??as)-1})}else if(Fs(o)){let c;for await(const u of Bs(i,o))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}o=c}else if(Rc(o)){let c;for(const u of Cc(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??as)-1}),i=await new Promise((o,c)=>{It.runWithConfig(Jt(s),async()=>{try{const u=await this.func(a,{...s,config:s});o(u)}catch(u){c(u)}})});if(i&&Se.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(Fs(i))for await(const o of Bs(s,i))n?.signal?.throwIfAborted(),yield o;else if(Rc(i))for(const o of Cc(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=de(r),s=new Qt({generator:this.transform(n(),a),config:a});return await s.setup,ct.fromAsyncGenerator(s)}},my=class extends Er{},pl=class extends Se{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=de(e),n=await Ke(r),{runId:a,...s}=r,i=await n?.handleChainStart(this.toJSON(),ke(t,"input"),a,void 0,void 0,void 0,s?.runName),o=we(s,{callbacks:i?.getChild()});return await It.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(ke(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=de(e),n=await Ke(r),{runId:a,...s}=r,i=await n?.handleChainStart(this.toJSON(),ke(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 h=await l.stream(t,d);c=Bs(d,h);break}catch(h){o===void 0&&(o=h)}}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(ke(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=>Ke(o))),s=await Promise.all(a.map(async(o,c)=>{const u=await o?.handleChainStart(this.toJSON(),ke(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(ke(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 ot(t){if(typeof t=="function")return new Ft({func:t});if(Se.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){const e={};for(const[r,n]of Object.entries(t))e[r]=ot(n);return new Er({steps:e})}else throw new Error(`Expected a Runnable, function or object.
79
+ Instead got an unsupported type.`)}var Si=class extends Se{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(t){t instanceof Er&&(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]=mi(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=de(e),a=new Qt({generator:this.transform(r(),n),config:n});return await a.setup,ct.fromAsyncGenerator(a)}},ml=class extends Se{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=de(e),a=new Qt({generator:this.transform(r(),n),config:n});return await a.setup,ct.fromAsyncGenerator(a)}},zs=class extends gr{name;description;schema;constructor(t){const e=qn.from([Ft.from(async r=>{let n;if(iu(r))try{n=await vi(this.schema,r.args)}catch{throw new ph("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 gy(t,e){const r=e.name??t.getName(),n=e.description??wi(e.schema);return Qu(e.schema)?new zs({name:r,description:n,schema:Ws({input:Js()}).transform(a=>a.input),bound:t}):new zs({name:r,description:n,schema:e.schema,bound:t})}const On=(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 yy(t,e){return Array.isArray(t)?Nc(t,e):Ft.from(r=>Nc(r,t))}function Nc(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&&On(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&&On(u,a)||i&&u.id&&i.some(l=>l===u.id))&&c.push(u):c.push(u)}return c}function _y(t){return Array.isArray(t)?$c(t):Ft.from($c)}function $c(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=vn(a),i=vn(n),o=s.concat(i);typeof s.content=="string"&&typeof i.content=="string"&&(o.content=`${s.content}
80
+ ${i.content}`),e.push(by(o))}}return e}function vy(t,e){if(Array.isArray(t)){const r=t;if(!e)throw new Error("Options parameter is required when providing messages.");return Pc(r,e)}else{const r=t;return Ft.from(n=>Pc(n,r)).withConfig({runName:"trim_messages"})}}async function Pc(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 h=>(await Promise.all(h.map(p=>n.getNumTokens(p.content)))).reduce((p,y)=>p+y,0):l=async h=>n(h);let d=yl;if(u&&("splitText"in u?d=u.splitText:d=async h=>u(h)),a==="first")return gl(t,{maxTokens:r,tokenCounter:l,textSplitter:d,partialStrategy:s?"first":void 0,endOn:i});if(a==="last")return wy(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 gl(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,h=s==="last"?[...l.content].reverse():l.content;for(let f=1;f<=d;f+=1){const p=s==="first"?h.slice(0,f):h.slice(-f),y=Object.fromEntries(Object.entries(l).filter(([T])=>T!=="type"&&!T.startsWith("lc_"))),_=xi(l.getType(),{...y,content:p}),w=[...o.slice(0,c),_];if(await n(w)<=r)o=w,c+=1,u=!0;else break}u&&s==="last"&&(l.content=[...h].reverse())}if(!u){const l=o[c];let d;if(Array.isArray(l.content)&&l.content.some(h=>typeof h=="string"||h.type==="text")?d=l.content.find(f=>f.type==="text"&&f.text)?.text:typeof l.content=="string"&&(d=l.content),d){const h=await a(d),f=h.length;s==="last"&&h.reverse();for(let p=0;p<f-1;p+=1)if(h.pop(),l.content=h.join(""),await n([...o.slice(0,c),l])<=r){s==="last"&&(l.content=[...h].reverse().join("")),o=[...o.slice(0,c),l],c+=1;break}}}}if(i){const u=Array.isArray(i)?i:[i];for(;c>0&&!On(o[c-1],u);)c-=1}return o.slice(0,c)}async function wy(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(([h])=>h!=="type"&&!h.startsWith("lc_")));return xi(l.getType(),d,ti(l))});if(a){const l=Array.isArray(a)?a:[a];for(;o.length>0&&!On(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 gl(u,{...i,partialStrategy:r?"last":void 0,endOn:s}),c?[u[0],...u.slice(1).reverse()]:u.reverse()}const Mc={human:{message:Ot,messageChunk:Pn},ai:{message:jt,messageChunk:Xt},system:{message:Dt,messageChunk:pr},developer:{message:Dt,messageChunk:pr},tool:{message:_r,messageChunk:Rn},function:{message:Nn,messageChunk:$n},generic:{message:Gr,messageChunk:Cn},remove:{message:_n,messageChunk:_n}};function xi(t,e,r){let n,a;switch(t){case"human":r?n=new Pn(e):a=new Ot(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 Xt(s)}else a=new jt(e);break;case"system":r?n=new pr(e):a=new Dt(e);break;case"developer":r?n=new pr({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}}):a=new Dt({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in e)r?n=new Rn(e):a=new _r(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 $n(e);else{if(!e.name)throw new Error("FunctionMessage must have a 'name' field");a=new Nn(e)}break;case"generic":if("role"in e)r?n=new Cn(e):a=new Gr(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 by(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 Mc&&(r=xi(e,n)),!r)throw new Error(`Unrecognized message chunk class ${e}. Supported classes are ${Object.keys(Mc)}`);return r}function yl(t){const e=t.split(`
81
+ `);return Promise.resolve([...e.slice(0,-1).map(r=>`${r}
82
+ `),e[e.length-1]])}const Ey=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"],Ty=["image","video","audio","text-plain","file"],Sy=["text","reasoning",...Ey,...Ty];var xy={};pe(xy,{AIMessage:()=>jt,AIMessageChunk:()=>Xt,BaseMessage:()=>At,BaseMessageChunk:()=>Yt,ChatMessage:()=>Gr,ChatMessageChunk:()=>Cn,FunctionMessage:()=>Nn,FunctionMessageChunk:()=>$n,HumanMessage:()=>Ot,HumanMessageChunk:()=>Pn,KNOWN_BLOCK_TYPES:()=>Sy,RemoveMessage:()=>_n,SystemMessage:()=>Dt,SystemMessageChunk:()=>pr,ToolMessage:()=>_r,ToolMessageChunk:()=>Rn,_isMessageFieldWithRole:()=>Wc,_mergeDicts:()=>Me,_mergeLists:()=>qr,_mergeObj:()=>Jc,_mergeStatus:()=>Zc,coerceMessageLikeToMessage:()=>kr,convertToChunk:()=>vn,convertToOpenAIImageBlock:()=>zc,convertToProviderContentBlock:()=>Td,defaultTextSplitter:()=>yl,defaultToolCallParser:()=>ri,filterMessages:()=>yy,getBufferString:()=>si,iife:()=>mh,isAIMessage:()=>nu,isAIMessageChunk:()=>bs,isBase64ContentBlock:()=>Ys,isBaseMessage:()=>Tt,isBaseMessageChunk:()=>ti,isChatMessage:()=>ih,isChatMessageChunk:()=>oh,isDataContentBlock:()=>Lt,isDirectToolOutput:()=>Qc,isFunctionMessage:()=>ch,isFunctionMessageChunk:()=>uh,isHumanMessage:()=>lh,isHumanMessageChunk:()=>dh,isIDContentBlock:()=>Bc,isMessage:()=>qc,isOpenAIToolCallArray:()=>Kd,isPlainTextContentBlock:()=>bd,isSystemMessage:()=>hh,isSystemMessageChunk:()=>fh,isToolMessage:()=>eu,isToolMessageChunk:()=>tu,isURLContentBlock:()=>Ks,mapChatMessagesToStoredMessages:()=>wh,mapStoredMessageToChatMessage:()=>ii,mapStoredMessagesToChatMessages:()=>vh,mergeContent:()=>Kt,mergeMessageRuns:()=>_y,mergeResponseMetadata:()=>Kc,mergeUsageMetadata:()=>Xc,parseBase64DataUrl:()=>vs,parseMimeType:()=>Ed,trimMessages:()=>vy});var Iy={};pe(Iy,{extendInteropZodObject:()=>Mm,getInteropZodDefaultGetter:()=>jm,getInteropZodObjectShape:()=>Ds,getSchemaDescription:()=>wi,interopParse:()=>Nm,interopParseAsync:()=>vi,interopSafeParse:()=>Cm,interopSafeParseAsync:()=>Rm,interopZodObjectMakeFieldsOptional:()=>Fm,interopZodObjectPartial:()=>Lm,interopZodObjectPassthrough:()=>Us,interopZodObjectStrict:()=>In,interopZodTransformInputSchema:()=>ir,isInteropZodLiteral:()=>km,isInteropZodObject:()=>Pm,isInteropZodSchema:()=>Jr,isShapelessZodSchema:()=>$m,isSimpleStringZodSchema:()=>Qu,isZodArrayV4:()=>zn,isZodLiteralV3:()=>Yu,isZodLiteralV4:()=>Xu,isZodObjectV3:()=>bi,isZodObjectV4:()=>yt,isZodSchema:()=>Om,isZodSchemaV3:()=>Re,isZodSchemaV4:()=>xe});function _l(t){return t!==void 0&&Array.isArray(t.lc_namespace)}function vl(t){return t!==void 0&&Se.isRunnable(t)&&"lc_name"in t.constructor&&typeof t.constructor.lc_name=="function"&&t.constructor.lc_name()==="RunnableToolLike"}function wl(t){return!!t&&typeof t=="object"&&"name"in t&&"schema"in t&&(Jr(t.schema)||t.schema!=null&&typeof t.schema=="object"&&"type"in t.schema&&typeof t.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(t.schema.type))}function bl(t){return wl(t)||vl(t)||_l(t)}var Ay={};pe(Ay,{convertToOpenAIFunction:()=>El,convertToOpenAITool:()=>Oy,isLangChainTool:()=>bl,isRunnableToolLike:()=>vl,isStructuredTool:()=>_l,isStructuredToolParams:()=>wl});function El(t,e){const r=typeof e=="number"?void 0:e;return{name:t.name,description:t.description,parameters:br(t.schema),...r?.strict!==void 0?{strict:r.strict}:{}}}function Oy(t,e){const r=typeof e=="number"?void 0:e;let n;return bl(t)?n={type:"function",function:El(t)}:n=t,r?.strict!==void 0&&(n.function.strict=r.strict),n}var ky={};pe(ky,{BasePromptValue:()=>Gn,ChatPromptValue:()=>Sl,ImagePromptValue:()=>Ry,StringPromptValue:()=>Tl});var Gn=class extends fr{},Tl=class extends Gn{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(t){super({value:t}),this.value=t}toString(){return this.value}toChatMessages(){return[new Ot(this.value)]}},Sl=class extends Gn{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(t){Array.isArray(t)&&(t={messages:t}),super(t),this.messages=t.messages}toString(){return si(this.messages)}toChatMessages(){return this.messages}},Ry=class extends Gn{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(t){"imageUrl"in t||(t={imageUrl:t}),super(t),this.imageUrl=t.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new Ot({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},U="0123456789abcdef".split(""),Cy=[-2147483648,8388608,32768,128],nt=[24,16,8,0],cn=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],Ce=[];function ut(t,e){e?(Ce[0]=Ce[16]=Ce[1]=Ce[2]=Ce[3]=Ce[4]=Ce[5]=Ce[6]=Ce[7]=Ce[8]=Ce[9]=Ce[10]=Ce[11]=Ce[12]=Ce[13]=Ce[14]=Ce[15]=0,this.blocks=Ce):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=t}ut.prototype.update=function(t){if(!this.finalized){var e,r=typeof t;if(r!=="string"){if(r==="object"){if(t===null)throw new Error(ERROR);if(ARRAY_BUFFER&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!Array.isArray(t)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(t)))throw new Error(ERROR)}else throw new Error(ERROR);e=!0}for(var n,a=0,s,i=t.length,o=this.blocks;a<i;){if(this.hashed&&(this.hashed=!1,o[0]=this.block,this.block=o[16]=o[1]=o[2]=o[3]=o[4]=o[5]=o[6]=o[7]=o[8]=o[9]=o[10]=o[11]=o[12]=o[13]=o[14]=o[15]=0),e)for(s=this.start;a<i&&s<64;++a)o[s>>>2]|=t[a]<<nt[s++&3];else for(s=this.start;a<i&&s<64;++a)n=t.charCodeAt(a),n<128?o[s>>>2]|=n<<nt[s++&3]:n<2048?(o[s>>>2]|=(192|n>>>6)<<nt[s++&3],o[s>>>2]|=(128|n&63)<<nt[s++&3]):n<55296||n>=57344?(o[s>>>2]|=(224|n>>>12)<<nt[s++&3],o[s>>>2]|=(128|n>>>6&63)<<nt[s++&3],o[s>>>2]|=(128|n&63)<<nt[s++&3]):(n=65536+((n&1023)<<10|t.charCodeAt(++a)&1023),o[s>>>2]|=(240|n>>>18)<<nt[s++&3],o[s>>>2]|=(128|n>>>12&63)<<nt[s++&3],o[s>>>2]|=(128|n>>>6&63)<<nt[s++&3],o[s>>>2]|=(128|n&63)<<nt[s++&3]);this.lastByteIndex=s,this.bytes+=s-this.start,s>=64?(this.block=o[16],this.start=s-64,this.hash(),this.hashed=!0):this.start=s}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};ut.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=Cy[e&3],this.block=t[16],e>=56&&(this.hashed||this.hash(),t[0]=this.block,t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.hBytes<<3|this.bytes>>>29,t[15]=this.bytes<<3,this.hash()}};ut.prototype.hash=function(){var t=this.h0,e=this.h1,r=this.h2,n=this.h3,a=this.h4,s=this.h5,i=this.h6,o=this.h7,c=this.blocks,u,l,d,h,f,p,y,_,w,T,E;for(u=16;u<64;++u)f=c[u-15],l=(f>>>7|f<<25)^(f>>>18|f<<14)^f>>>3,f=c[u-2],d=(f>>>17|f<<15)^(f>>>19|f<<13)^f>>>10,c[u]=c[u-16]+l+c[u-7]+d<<0;for(E=e&r,u=0;u<64;u+=4)this.first?(this.is224?(_=300032,f=c[0]-1413257819,o=f-150054599<<0,n=f+24177077<<0):(_=704751109,f=c[0]-210244248,o=f-1521486534<<0,n=f+143694565<<0),this.first=!1):(l=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),_=t&e,h=_^t&r^E,y=a&s^~a&i,f=o+d+y+cn[u]+c[u],p=l+h,o=n+f<<0,n=f+p<<0),l=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),w=n&t,h=w^n&e^_,y=i&o^~i&a,f=s+d+y+cn[u+1]+c[u+1],p=l+h,i=r+f<<0,r=f+p<<0,l=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),T=r&n,h=T^r&t^w,y=s&i^~s&o,f=a+d+y+cn[u+2]+c[u+2],p=l+h,s=e+f<<0,e=f+p<<0,l=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),E=e&r,h=E^e&n^T,y=s&i^~s&o,f=a+d+y+cn[u+3]+c[u+3],p=l+h,a=t+f<<0,t=f+p<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+t<<0,this.h1=this.h1+e<<0,this.h2=this.h2+r<<0,this.h3=this.h3+n<<0,this.h4=this.h4+a<<0,this.h5=this.h5+s<<0,this.h6=this.h6+i<<0,this.h7=this.h7+o<<0};ut.prototype.hex=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,a=this.h4,s=this.h5,i=this.h6,o=this.h7,c=U[t>>>28&15]+U[t>>>24&15]+U[t>>>20&15]+U[t>>>16&15]+U[t>>>12&15]+U[t>>>8&15]+U[t>>>4&15]+U[t&15]+U[e>>>28&15]+U[e>>>24&15]+U[e>>>20&15]+U[e>>>16&15]+U[e>>>12&15]+U[e>>>8&15]+U[e>>>4&15]+U[e&15]+U[r>>>28&15]+U[r>>>24&15]+U[r>>>20&15]+U[r>>>16&15]+U[r>>>12&15]+U[r>>>8&15]+U[r>>>4&15]+U[r&15]+U[n>>>28&15]+U[n>>>24&15]+U[n>>>20&15]+U[n>>>16&15]+U[n>>>12&15]+U[n>>>8&15]+U[n>>>4&15]+U[n&15]+U[a>>>28&15]+U[a>>>24&15]+U[a>>>20&15]+U[a>>>16&15]+U[a>>>12&15]+U[a>>>8&15]+U[a>>>4&15]+U[a&15]+U[s>>>28&15]+U[s>>>24&15]+U[s>>>20&15]+U[s>>>16&15]+U[s>>>12&15]+U[s>>>8&15]+U[s>>>4&15]+U[s&15]+U[i>>>28&15]+U[i>>>24&15]+U[i>>>20&15]+U[i>>>16&15]+U[i>>>12&15]+U[i>>>8&15]+U[i>>>4&15]+U[i&15];return this.is224||(c+=U[o>>>28&15]+U[o>>>24&15]+U[o>>>20&15]+U[o>>>16&15]+U[o>>>12&15]+U[o>>>8&15]+U[o>>>4&15]+U[o&15]),c};ut.prototype.toString=ut.prototype.hex;ut.prototype.digest=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,a=this.h4,s=this.h5,i=this.h6,o=this.h7,c=[t>>>24&255,t>>>16&255,t>>>8&255,t&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255];return this.is224||c.push(o>>>24&255,o>>>16&255,o>>>8&255,o&255),c};ut.prototype.array=ut.prototype.digest;ut.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(this.is224?28:32),e=new DataView(t);return e.setUint32(0,this.h0),e.setUint32(4,this.h1),e.setUint32(8,this.h2),e.setUint32(12,this.h3),e.setUint32(16,this.h4),e.setUint32(20,this.h5),e.setUint32(24,this.h6),this.is224||e.setUint32(28,this.h7),t};const xl=(...t)=>new ut(!1,!0).update(t.join("")).hex();var Ny={};pe(Ny,{sha256:()=>xl});var $y={};pe($y,{BaseCache:()=>Al,InMemoryCache:()=>Ol,defaultHashKeyEncoder:()=>Il,deserializeStoredGeneration:()=>Py,serializeGeneration:()=>My});const Il=(...t)=>xl(t.join("_"));function Py(t){return t.message!==void 0?{text:t.text,message:ii(t.message)}:{text:t.text}}function My(t){const e={text:t.text};return t.message!==void 0&&(e.message=t.message.toDict()),e}var Al=class{keyEncoder=Il;makeDefaultKeyEncoder(t){this.keyEncoder=t}};const Ly=new Map;var Ol=class kl extends Al{cache;constructor(e){super(),this.cache=e??new Map}lookup(e,r){return Promise.resolve(this.cache.get(this.keyEncoder(e,r))??null)}async update(e,r,n){this.cache.set(this.keyEncoder(e,r),n)}static global(){return new kl(Ly)}},jy=Jl();const Dy=yr(jy);var Uy=Object.defineProperty,Fy=(t,e,r)=>e in t?Uy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,By=(t,e,r)=>(Fy(t,e+"",r),r);function zy(t,e){let r=Array.from({length:t.length},(n,a)=>({start:a,end:a+1}));for(;r.length>1;){let n=null;for(let a=0;a<r.length-1;a++){const s=t.slice(r[a].start,r[a+1].end),i=e.get(s.join(","));i!=null&&(n==null||i<n[0])&&(n=[i,a])}if(n!=null){const a=n[1];r[a]={start:r[a].start,end:r[a+1].end},r.splice(a+1,1)}else break}return r}function qy(t,e){return t.length===1?[e.get(t.join(","))]:zy(t,e).map(r=>e.get(t.slice(r.start,r.end).join(","))).filter(r=>r!=null)}function Gy(t){return t.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var qs=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(t,e){this.patStr=t.pat_str;const r=t.bpe_ranks.split(`
83
+ `).filter(Boolean).reduce((n,a)=>{const[s,i,...o]=a.split(" "),c=Number.parseInt(i,10);return o.forEach((u,l)=>n[u]=c+l),n},{});for(const[n,a]of Object.entries(r)){const s=Dy.toByteArray(n);this.rankMap.set(s.join(","),a),this.textMap.set(a,s)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[a,s])=>(n[s]=this.textEncoder.encode(a),n),{})}encode(t,e=[],r="all"){const n=new RegExp(this.patStr,"ug"),a=qs.specialTokenRegex(Object.keys(this.specialTokens)),s=[],i=new Set(e==="all"?Object.keys(this.specialTokens):e),o=new Set(r==="all"?Object.keys(this.specialTokens).filter(u=>!i.has(u)):r);if(o.size>0){const u=qs.specialTokenRegex([...o]),l=t.match(u);if(l!=null)throw new Error(`The text contains a special token that is not allowed: ${l[0]}`)}let c=0;for(;;){let u=null,l=c;for(;a.lastIndex=l,u=a.exec(t),!(u==null||i.has(u[0]));)l=u.index+1;const d=u?.index??t.length;for(const f of t.substring(c,d).matchAll(n)){const p=this.textEncoder.encode(f[0]),y=this.rankMap.get(p.join(","));if(y!=null){s.push(y);continue}s.push(...qy(p,this.rankMap))}if(u==null)break;let h=this.specialTokens[u[0]];s.push(h),c=u.index+u[0].length}return s}decode(t){const e=[];let r=0;for(let s=0;s<t.length;++s){const i=t[s],o=this.textMap.get(i)??this.inverseSpecialTokens[i];o!=null&&(e.push(o),r+=o.length)}const n=new Uint8Array(r);let a=0;for(const s of e)n.set(s,a),a+=s.length;return this.textDecoder.decode(n)}},Rl=qs;By(Rl,"specialTokenRegex",t=>new RegExp(t.map(e=>Gy(e)).join("|"),"g"));function Hy(t){switch(t){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"gpt-5":case"gpt-5-2025-08-07":case"gpt-5-nano":case"gpt-5-nano-2025-08-07":case"gpt-5-mini":case"gpt-5-mini-2025-08-07":case"gpt-5-chat-latest":return"o200k_base";default:throw new Error("Unknown model")}}var Vy={};pe(Vy,{encodingForModel:()=>Ii,getEncoding:()=>Cl});const un={},Zy=new Bn({});async function Cl(t){return t in un||(un[t]=Zy.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new Rl(e)).catch(e=>{throw delete un[t],e})),await un[t]}async function Ii(t){return Cl(Hy(t))}var Jy={};pe(Jy,{BaseLangChain:()=>$l,BaseLanguageModel:()=>Pl,calculateMaxTokens:()=>Yy,getEmbeddingContextSize:()=>Wy,getModelContextSize:()=>Nl,getModelNameForTiktoken:()=>Hn,isOpenAITool:()=>Ky});const Hn=t=>t.startsWith("gpt-5")?"gpt-5":t.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":t.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":t.startsWith("gpt-4-32k")?"gpt-4-32k":t.startsWith("gpt-4-")?"gpt-4":t.startsWith("gpt-4o")?"gpt-4o":t,Wy=t=>{switch(t){case"text-embedding-ada-002":return 8191;default:return 2046}},Nl=t=>{switch(Hn(t)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128e3;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};function Ky(t){return typeof t!="object"||!t?!1:!!("type"in t&&t.type==="function"&&"function"in t&&typeof t.function=="object"&&t.function&&"name"in t.function&&"parameters"in t.function)}const Yy=async({prompt:t,modelName:e})=>{let r;try{r=(await Ii(Hn(e))).encode(t).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),r=Math.ceil(t.length/4)}return Nl(e)-r},Xy=()=>!1;var $l=class extends Se{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(t){super(t),this.verbose=t.verbose??Xy(),this.callbacks=t.callbacks,this.tags=t.tags??[],this.metadata=t.metadata??{}}},Pl=class extends $l{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:t,callbackManager:e,...r}){const{cache:n,...a}=r;super({callbacks:t??e,...a}),typeof n=="object"?this.cache=n:n?this.cache=Ol.global():this.cache=void 0,this.caller=new Bn(r??{})}_encoding;async getNumTokens(t){let e;typeof t=="string"?e=t:e=t.map(n=>typeof n=="string"?n:n.type==="text"&&"text"in n?n.text:"").join("");let r=Math.ceil(e.length/4);if(!this._encoding)try{this._encoding=await Ii("modelName"in this?Hn(this.modelName):"gpt2")}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}if(this._encoding)try{r=this._encoding.encode(e).length}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}return r}static _convertInputToPromptValue(t){return typeof t=="string"?new Tl(t):Array.isArray(t)?new Sl(t.map(kr)):t}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:t,...e}){const r={...this._identifyingParams(),...e,_type:this._llmType(),_model:this._modelType()};return Object.entries(r).filter(([s,i])=>i!==void 0).map(([s,i])=>`${s}:${JSON.stringify(i)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(t){throw new Error("Use .toJSON() instead")}},kn=class extends Se{static lc_name(){return"RunnablePassthrough"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;func;constructor(t){super(t),t&&(this.func=t.func)}async invoke(t,e){const r=de(e);return this.func&&await this.func(t,r),this._callWithConfig(n=>Promise.resolve(n),t,r)}async*transform(t,e){const r=de(e);let n,a=!0;for await(const s of this._transformStreamWithConfig(t,i=>i,r))if(yield s,a)if(n===void 0)n=s;else try{n=Wt(n,s)}catch{n=void 0,a=!1}this.func&&n!==void 0&&await this.func(n,r)}static assign(t){return new Si(new Er({steps:t}))}};const Qy=t=>t();function cs(t){const e=t.constructor;return new e({...t,content:t.contentBlocks,response_metadata:{...t.response_metadata,output_version:"v1"}})}var e_={};pe(e_,{BaseChatModel:()=>Ml,SimpleChatModel:()=>t_});function us(t){const e=[];for(const r of t){let n=r;if(Array.isArray(r.content))for(let a=0;a<r.content.length;a++){const s=r.content[a];(Ks(s)||Ys(s))&&n===r&&(n=new r.constructor({...n,content:[...r.content.slice(0,a),zc(s),...r.content.slice(a+1)]}))}e.push(n)}return e}var Ml=class zt extends Pl{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(e){super(e),this.outputVersion=Qy(()=>{const r=e.outputVersion??Pt("LC_OUTPUT_VERSION");return r&&["v0","v1"].includes(r)?r:"v0"})}_separateRunnableConfigFromCallOptionsCompat(e){const[r,n]=super._separateRunnableConfigFromCallOptions(e);return n.signal=r.signal,[r,n]}async invoke(e,r){const n=zt._convertInputToPromptValue(e);return(await this.generatePrompt([n],r,r?.callbacks)).generations[0][0].message}async*_streamResponseChunks(e,r,n){throw new Error("Not implemented.")}async*_streamIterator(e,r){if(this._streamResponseChunks===zt.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(e,r);else{const a=zt._convertInputToPromptValue(e).toChatMessages(),[s,i]=this._separateRunnableConfigFromCallOptionsCompat(r),o={...s.metadata,...this.getLsParams(i)},c=await gt.configure(s.callbacks,this.callbacks,s.tags,this.tags,o,this.metadata,{verbose:this.verbose}),u={options:i,invocation_params:this?.invocationParams(i),batch_size:1},l=i.outputVersion??this.outputVersion,d=await c?.handleChatModelStart(this.toJSON(),[us(a)],s.runId,void 0,u,void 0,void 0,s.runName);let h,f;try{for await(const p of this._streamResponseChunks(a,i,d?.[0])){if(p.message.id==null){const y=d?.at(0)?.runId;y!=null&&p.message._updateId(`run-${y}`)}p.message.response_metadata={...p.generationInfo,...p.message.response_metadata},l==="v1"?yield cs(p.message):yield p.message,h?h=h.concat(p):h=p,bs(p.message)&&p.message.usage_metadata!==void 0&&(f={tokenUsage:{promptTokens:p.message.usage_metadata.input_tokens,completionTokens:p.message.usage_metadata.output_tokens,totalTokens:p.message.usage_metadata.total_tokens}})}}catch(p){throw await Promise.all((d??[]).map(y=>y?.handleLLMError(p))),p}await Promise.all((d??[]).map(p=>p?.handleLLMEnd({generations:[[h]],llmOutput:f})))}}getLsParams(e){const r=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:e.stop,ls_provider:r}}async _generateUncached(e,r,n,a){const s=e.map(h=>h.map(kr));let i;if(a!==void 0&&a.length===s.length)i=a;else{const h={...n.metadata,...this.getLsParams(r)},f=await gt.configure(n.callbacks,this.callbacks,n.tags,this.tags,h,this.metadata,{verbose:this.verbose}),p={options:r,invocation_params:this?.invocationParams(r),batch_size:1};i=await f?.handleChatModelStart(this.toJSON(),s.map(us),n.runId,void 0,p,void 0,void 0,n.runName)}const o=r.outputVersion??this.outputVersion,c=[],u=[];if(!!i?.[0].handlers.find(mu)&&!this.disableStreaming&&s.length===1&&this._streamResponseChunks!==zt.prototype._streamResponseChunks)try{const h=await this._streamResponseChunks(s[0],r,i?.[0]);let f,p;for await(const y of h){if(y.message.id==null){const _=i?.at(0)?.runId;_!=null&&y.message._updateId(`run-${_}`)}f===void 0?f=y:f=Wt(f,y),bs(y.message)&&y.message.usage_metadata!==void 0&&(p={tokenUsage:{promptTokens:y.message.usage_metadata.input_tokens,completionTokens:y.message.usage_metadata.output_tokens,totalTokens:y.message.usage_metadata.total_tokens}})}if(f===void 0)throw new Error("Received empty response from chat model call.");c.push([f]),await i?.[0].handleLLMEnd({generations:c,llmOutput:p})}catch(h){throw await i?.[0].handleLLMError(h),h}else{const h=await Promise.allSettled(s.map(async(f,p)=>{const y=await this._generate(f,{...r,promptIndex:p},i?.[p]);if(o==="v1")for(const _ of y.generations)_.message=cs(_.message);return y}));await Promise.all(h.map(async(f,p)=>{if(f.status==="fulfilled"){const y=f.value;for(const _ of y.generations){if(_.message.id==null){const w=i?.at(0)?.runId;w!=null&&_.message._updateId(`run-${w}`)}_.message.response_metadata={..._.generationInfo,..._.message.response_metadata}}return y.generations.length===1&&(y.generations[0].message.response_metadata={...y.llmOutput,...y.generations[0].message.response_metadata}),c[p]=y.generations,u[p]=y.llmOutput,i?.[p]?.handleLLMEnd({generations:[y.generations],llmOutput:y.llmOutput})}else return await i?.[p]?.handleLLMError(f.reason),Promise.reject(f.reason)}))}const d={generations:c,llmOutput:u.length?this._combineLLMOutput?.(...u):void 0};return Object.defineProperty(d,Ls,{value:i?{runIds:i?.map(h=>h.runId)}:void 0,configurable:!0}),d}async _generateCached({messages:e,cache:r,llmStringKey:n,parsedOptions:a,handledOptions:s}){const i=e.map(w=>w.map(kr)),o={...s.metadata,...this.getLsParams(a)},c=await gt.configure(s.callbacks,this.callbacks,s.tags,this.tags,o,this.metadata,{verbose:this.verbose}),u={options:a,invocation_params:this?.invocationParams(a),batch_size:1},l=await c?.handleChatModelStart(this.toJSON(),i.map(us),s.runId,void 0,u,void 0,void 0,s.runName),d=[],f=(await Promise.allSettled(i.map(async(w,T)=>{const E=zt._convertInputToPromptValue(w).toString(),x=await r.lookup(E,n);return x==null&&d.push(T),x}))).map((w,T)=>({result:w,runManager:l?.[T]})).filter(({result:w})=>w.status==="fulfilled"&&w.value!=null||w.status==="rejected"),p=a.outputVersion??this.outputVersion,y=[];await Promise.all(f.map(async({result:w,runManager:T},E)=>{if(w.status==="fulfilled"){const x=w.value;return y[E]=x.map(R=>("message"in R&&Tt(R.message)&&nu(R.message)&&(R.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},p==="v1"&&(R.message=cs(R.message))),R.generationInfo={...R.generationInfo,tokenUsage:{}},R)),x.length&&await T?.handleLLMNewToken(x[0].text),T?.handleLLMEnd({generations:[x]},void 0,void 0,void 0,{cached:!0})}else return await T?.handleLLMError(w.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(w.reason)}));const _={generations:y,missingPromptIndices:d,startedRunManagers:l};return Object.defineProperty(_,Ls,{value:l?{runIds:l?.map(w=>w.runId)}:void 0,configurable:!0}),_}async generate(e,r,n){let a;Array.isArray(r)?a={stop:r}:a=r;const s=e.map(p=>p.map(kr)),[i,o]=this._separateRunnableConfigFromCallOptionsCompat(a);if(i.callbacks=i.callbacks??n,!this.cache)return this._generateUncached(s,o,i);const{cache:c}=this,u=this._getSerializedCacheKeyParametersForCall(o),{generations:l,missingPromptIndices:d,startedRunManagers:h}=await this._generateCached({messages:s,cache:c,llmStringKey:u,parsedOptions:o,handledOptions:i});let f={};if(d.length>0){const p=await this._generateUncached(d.map(y=>s[y]),o,i,h!==void 0?d.map(y=>h?.[y]):void 0);await Promise.all(p.generations.map(async(y,_)=>{const w=d[_];l[w]=y;const T=zt._convertInputToPromptValue(s[w]).toString();return c.update(T,u,y)})),f=p.llmOutput??{}}return{generations:l,llmOutput:f}}invocationParams(e){return{}}_modelType(){return"base_chat_model"}async generatePrompt(e,r,n){const a=e.map(s=>s.toChatMessages());return this.generate(a,r,n)}withStructuredOutput(e,r){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(r?.strict)throw new Error('"strict" mode is not supported for this model by default.');const n=e,a=r?.name,s=wi(n)??"A function available to call.",i=r?.method,o=r?.includeRaw;if(i==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let c=a??"extract",u;Jr(n)?u=[{type:"function",function:{name:c,description:s,parameters:br(n)}}]:("name"in n&&(c=n.name),u=[{type:"function",function:{name:c,description:s,parameters:n}}]);const l=this.bindTools(u),d=Ft.from(y=>{if(!Xt.isInstance(y))throw new Error("Input is not an AIMessageChunk.");if(!y.tool_calls||y.tool_calls.length===0)throw new Error("No tool calls found in the response.");const _=y.tool_calls.find(w=>w.name===c);if(!_)throw new Error(`No tool call found with name ${c}.`);return _.args});if(!o)return l.pipe(d).withConfig({runName:"StructuredOutput"});const h=kn.assign({parsed:(y,_)=>d.invoke(y.raw,_)}),f=kn.assign({parsed:()=>null}),p=h.withFallbacks({fallbacks:[f]});return qn.from([{raw:l},p]).withConfig({runName:"StructuredOutputRunnable"})}},t_=class extends Ml{async _generate(t,e,r){const n=await this._call(t,e,r),a=new jt(n);if(typeof a.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:a.content,message:a}]}}},r_=class extends Se{static lc_name(){return"RouterRunnable"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnables;constructor(t){super(t),this.runnables=t.runnables}async invoke(t,e){const{key:r,input:n}=t,a=this.runnables[r];if(a===void 0)throw new Error(`No runnable associated with key "${r}".`);return a.invoke(n,de(e))}async batch(t,e,r){const n=t.map(d=>d.key),a=t.map(d=>d.input);if(n.find(d=>this.runnables[d]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");const i=n.map(d=>this.runnables[d]),o=this._getOptionsList(e??{},t.length),c=o[0]?.maxConcurrency??r?.maxConcurrency,u=c&&c>0?c:t.length,l=[];for(let d=0;d<a.length;d+=u){const h=a.slice(d,d+u).map((p,y)=>i[y].invoke(p,o[y])),f=await Promise.all(h);l.push(f)}return l.flat()}async stream(t,e){const{key:r,input:n}=t,a=this.runnables[r];if(a===void 0)throw new Error(`No runnable associated with key "${r}".`);return a.stream(n,e)}},n_=class extends Se{static lc_name(){return"RunnableBranch"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;default;branches;constructor(t){super(t),this.branches=t.branches,this.default=t.default}static from(t){if(t.length<1)throw new Error("RunnableBranch requires at least one branch");const r=t.slice(0,-1).map(([a,s])=>[ot(a),ot(s)]),n=ot(t[t.length-1]);return new this({branches:r,default:n})}async _invoke(t,e,r){let n;for(let a=0;a<this.branches.length;a+=1){const[s,i]=this.branches[a];if(await s.invoke(t,we(e,{callbacks:r?.getChild(`condition:${a+1}`)}))){n=await i.invoke(t,we(e,{callbacks:r?.getChild(`branch:${a+1}`)}));break}}return n||(n=await this.default.invoke(t,we(e,{callbacks:r?.getChild("branch:default")}))),n}async invoke(t,e={}){return this._callWithConfig(this._invoke,t,e)}async*_streamIterator(t,e){const n=await(await Ke(e))?.handleChainStart(this.toJSON(),ke(t,"input"),e?.runId,void 0,void 0,void 0,e?.runName);let a,s=!0,i;try{for(let o=0;o<this.branches.length;o+=1){const[c,u]=this.branches[o];if(await c.invoke(t,we(e,{callbacks:n?.getChild(`condition:${o+1}`)}))){i=await u.stream(t,we(e,{callbacks:n?.getChild(`branch:${o+1}`)}));for await(const d of i)if(yield d,s)if(a===void 0)a=d;else try{a=Wt(a,d)}catch{a=void 0,s=!1}break}}if(i===void 0){i=await this.default.stream(t,we(e,{callbacks:n?.getChild("branch:default")}));for await(const o of i)if(yield o,s)if(a===void 0)a=o;else try{a=Wt(a,o)}catch{a=void 0,s=!1}}}catch(o){throw await n?.handleChainError(o),o}await n?.handleChainEnd(a??{})}},a_=class extends gr{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(t){let e=Ft.from((s,i)=>this._enterHistory(s,i??{})).withConfig({runName:"loadHistory"});const r=t.historyMessagesKey??t.inputMessagesKey;r&&(e=kn.assign({[r]:e}).withConfig({runName:"insertHistory"}));const n=e.pipe(t.runnable.withListeners({onEnd:(s,i)=>this._exitHistory(s,i??{})})).withConfig({runName:"RunnableWithMessageHistory"}),a=t.config??{};super({...t,config:a,bound:n}),this.runnable=t.runnable,this.getMessageHistory=t.getMessageHistory,this.inputMessagesKey=t.inputMessagesKey,this.outputMessagesKey=t.outputMessagesKey,this.historyMessagesKey=t.historyMessagesKey}_getInputMessages(t){let e;if(typeof t=="object"&&!Array.isArray(t)&&!Tt(t)){let r;this.inputMessagesKey?r=this.inputMessagesKey:Object.keys(t).length===1?r=Object.keys(t)[0]:r="input",Array.isArray(t[r])&&Array.isArray(t[r][0])?e=t[r][0]:e=t[r]}else e=t;if(typeof e=="string")return[new Ot(e)];if(Array.isArray(e))return e;if(Tt(e))return[e];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
84
+ Got ${JSON.stringify(e,null,2)}`)}_getOutputMessages(t){let e;if(!Array.isArray(t)&&!Tt(t)&&typeof t!="string"){let r;this.outputMessagesKey!==void 0?r=this.outputMessagesKey:Object.keys(t).length===1?r=Object.keys(t)[0]:r="output",t.generations!==void 0?e=t.generations[0][0].message:e=t[r]}else e=t;if(typeof e=="string")return[new jt(e)];if(Array.isArray(e))return e;if(Tt(e))return[e];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(e,null,2)}`)}async _enterHistory(t,e){const n=await(e?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?n.concat(this._getInputMessages(t)):n}async _exitHistory(t,e){const r=e.configurable?.messageHistory;let n;Array.isArray(t.inputs)&&Array.isArray(t.inputs[0])?n=t.inputs[0]:n=t.inputs;let a=this._getInputMessages(n);if(this.historyMessagesKey===void 0){const o=await r.getMessages();a=a.slice(o.length)}const s=t.outputs;if(!s)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(t,null,2)}`);const i=this._getOutputMessages(s);await r.addMessages([...a,...i])}async _mergeConfig(...t){const e=await super._mergeConfig(...t);if(!e.configurable||!e.configurable.sessionId){const n={[this.inputMessagesKey??"input"]:"foo"},a={configurable:{sessionId:"123"}};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
85
+ eg. chain.invoke(${JSON.stringify(n)}, ${JSON.stringify(a)})`)}const{sessionId:r}=e.configurable;return e.configurable.messageHistory=await this.getMessageHistory(r),e}},s_={};pe(s_,{RouterRunnable:()=>r_,Runnable:()=>Se,RunnableAssign:()=>Si,RunnableBinding:()=>gr,RunnableBranch:()=>n_,RunnableEach:()=>hy,RunnableLambda:()=>Ft,RunnableMap:()=>Er,RunnableParallel:()=>my,RunnablePassthrough:()=>kn,RunnablePick:()=>ml,RunnableRetry:()=>Ti,RunnableSequence:()=>qn,RunnableToolLike:()=>zs,RunnableWithFallbacks:()=>pl,RunnableWithMessageHistory:()=>a_,_coerceToRunnable:()=>ot,ensureConfig:()=>de,getCallbackManagerForConfig:()=>Ke,mergeConfigs:()=>Os,patchConfig:()=>we,pickRunnableConfigKeys:()=>Jt});var Ll=class extends Se{parseResultWithPrompt(t,e,r){return this.parseResult(t,r)}_baseMessageToString(t){return typeof t.content=="string"?t.content:this._baseMessageContentToString(t.content)}_baseMessageContentToString(t){return JSON.stringify(t)}async invoke(t,e){return typeof t=="string"?this._callWithConfig(async(r,n)=>this.parseResult([{text:r}],n?.callbacks),t,{...e,runType:"parser"}):this._callWithConfig(async(r,n)=>this.parseResult([{message:r,text:this._baseMessageToString(r)}],n?.callbacks),t,{...e,runType:"parser"})}},Vn=class extends Ll{parseResult(t,e){return this.parse(t[0].text,e)}async parseWithPrompt(t,e,r){return this.parse(t,r)}_type(){throw new Error("_type not implemented")}},Vt=class extends Error{llmOutput;observation;sendToLLM;constructor(t,e,r,n=!1){if(super(t),this.llmOutput=e,this.observation=r,this.sendToLLM=n,n&&(r===void 0||e===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");su(this,"OUTPUT_PARSING_FAILURE")}},Wr=class extends Vn{async*_transform(t){for await(const e of t)typeof e=="string"?yield this.parseResult([{text:e}]):yield this.parseResult([{message:e,text:this._baseMessageToString(e)}])}async*transform(t,e){yield*this._transformStreamWithConfig(t,this._transform.bind(this),{...e,runType:"parser"})}},Ai=class extends Wr{diff=!1;constructor(t){super(t),this.diff=t?.diff??this.diff}async*_transform(t){let e,r;for await(const n of t){if(typeof n!="string"&&typeof n.content!="string")throw new Error("Cannot handle non-string output.");let a;if(ti(n)){if(typeof n.content!="string")throw new Error("Cannot handle non-string message output.");a=new js({message:n,text:n.content})}else if(Tt(n)){if(typeof n.content!="string")throw new Error("Cannot handle non-string message output.");a=new js({message:vn(n),text:n.content})}else a=new zr({text:n});r===void 0?r=a:r=r.concat(a);const s=await this.parsePartialResult([r]);s!=null&&!Ht(s,e)&&(this.diff?yield this._diff(e,s):yield s,e=s)}}getFormatInstructions(){return""}},i_=class extends Wr{static lc_name(){return"BytesOutputParser"}lc_namespace=["langchain_core","output_parsers","bytes"];lc_serializable=!0;textEncoder=new TextEncoder;parse(t){return Promise.resolve(this.textEncoder.encode(t))}getFormatInstructions(){return""}},Kr=class extends Wr{re;async*_transform(t){let e="";for await(const r of t)if(typeof r=="string"?e+=r:e+=r.content,this.re){const n=[...e.matchAll(this.re)];if(n.length>1){let a=0;for(const s of n.slice(0,-1))yield[s[1]],a+=(s.index??0)+s[0].length;e=e.slice(a)}}else{const n=await this.parse(e);if(n.length>1){for(const a of n.slice(0,-1))yield[a];e=n[n.length-1]}}for(const r of await this.parse(e))yield[r]}},o_=class extends Kr{static lc_name(){return"CommaSeparatedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;async parse(t){try{return t.trim().split(",").map(e=>e.trim())}catch{throw new Vt(`Could not parse output: ${t}`,t)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},c_=class extends Kr{lc_namespace=["langchain_core","output_parsers","list"];length;separator;constructor({length:t,separator:e}){super(...arguments),this.length=t,this.separator=e||","}async parse(t){try{const e=t.trim().split(this.separator).map(r=>r.trim());if(this.length!==void 0&&e.length!==this.length)throw new Vt(`Incorrect number of items. Expected ${this.length}, got ${e.length}.`);return e}catch(e){throw Object.getPrototypeOf(e)===Vt.prototype?e:new Vt(`Could not parse output: ${t}`)}}getFormatInstructions(){return`Your response should be a list of ${this.length===void 0?"":`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}},u_=class extends Kr{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
86
+
87
+ 1. foo
88
+
89
+ 2. bar
90
+
91
+ 3. baz`}re=/\d+\.\s([^\n]+)/g;async parse(t){return[...t.matchAll(this.re)??[]].map(e=>e[1])}},l_=class extends Kr{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
92
+
93
+ 1. foo
94
+
95
+ 2. bar
96
+
97
+ 3. baz`}re=/^\s*[-*]\s([^\n]+)$/gm;async parse(t){return[...t.matchAll(this.re)??[]].map(e=>e[1])}},d_=class extends Wr{static lc_name(){return"StrOutputParser"}lc_namespace=["langchain_core","output_parsers","string"];lc_serializable=!0;parse(t){return Promise.resolve(t)}getFormatInstructions(){return""}_textContentToString(t){return t.text}_imageUrlContentToString(t){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentToString(t){switch(t.type){case"text":case"text_delta":if("text"in t)return this._textContentToString(t);break;case"image_url":if("image_url"in t)return this._imageUrlContentToString(t);break;default:throw new Error(`Cannot coerce "${t.type}" message part into a string.`)}throw new Error(`Invalid content type: ${t.type}`)}_baseMessageContentToString(t){return t.reduce((e,r)=>e+this._messageContentToString(r),"")}},jl=class extends Vn{static lc_name(){return"StructuredOutputParser"}lc_namespace=["langchain","output_parsers","structured"];toJSON(){return this.toJSONNotImplemented()}constructor(t){super(t),this.schema=t}static fromZodSchema(t){return new this(t)}static fromNamesAndDescriptions(t){const e=Ws(Object.fromEntries(Object.entries(t).map(([r,n])=>[r,Js().describe(n)])));return new this(e)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
98
+
99
+ "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
100
+
101
+ For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
102
+ would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
103
+ Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
104
+
105
+ Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
106
+
107
+ Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
108
+ \`\`\`json
109
+ ${JSON.stringify(br(this.schema))}
110
+ \`\`\`
111
+ `}async parse(t){try{const e=t.trim(),n=(e.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||e.match(/```json\s*([\s\S]*?)```/)?.[1]||e).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(a,s)=>`"${s.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await vi(this.schema,JSON.parse(n))}catch(e){throw new Vt(`Failed to parse. Text: "${t}". Error: ${e}`,t)}}},Dl=class extends jl{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(t){const e=t?.interpolationDepth??1;if(e<1)throw new Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:
112
+ \`\`\`json
113
+ ${this._schemaToInstruction(br(this.schema)).replaceAll("{","{".repeat(e)).replaceAll("}","}".repeat(e))}
114
+ \`\`\``}_schemaToInstruction(t,e=2){const r=t;if("type"in r){let n=!1,a;if(Array.isArray(r.type)){const o=r.type.findIndex(c=>c==="null");o!==-1&&(n=!0,r.type.splice(o,1)),a=r.type.join(" | ")}else a=r.type;if(r.type==="object"&&r.properties){const o=r.description?` // ${r.description}`:"";return`{
115
+ ${Object.entries(r.properties).map(([u,l])=>{const d=r.required?.includes(u)?"":" (optional)";return`${" ".repeat(e)}"${u}": ${this._schemaToInstruction(l,e+2)}${d}`}).join(`
116
+ `)}
117
+ ${" ".repeat(e-2)}}${o}`}if(r.type==="array"&&r.items){const o=r.description?` // ${r.description}`:"";return`array[
118
+ ${" ".repeat(e)}${this._schemaToInstruction(r.items,e+2)}
119
+ ${" ".repeat(e-2)}] ${o}`}const s=n?" (nullable)":"",i=r.description?` // ${r.description}`:"";return`${a}${i}${s}`}if("anyOf"in r)return r.anyOf.map(n=>this._schemaToInstruction(n,e)).join(`
120
+ ${" ".repeat(e-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(t){return new this(t)}static fromNamesAndDescriptions(t){const e=Ws(Object.fromEntries(Object.entries(t).map(([r,n])=>[r,Js().describe(n)])));return new this(e)}},h_=class extends Vn{structuredInputParser;constructor({inputSchema:t}){super(...arguments),this.structuredInputParser=new Dl(t)}async parse(t){let e;try{e=await this.structuredInputParser.parse(t)}catch(r){throw new Vt(`Failed to parse. Text: "${t}". Error: ${r}`,t)}return this.outputProcessor(e)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}},f_={};pe(f_,{applyPatch:()=>mr,compare:()=>gi});var p_=class extends Ai{static lc_name(){return"JsonOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_concatOutputChunks(t,e){return this.diff?super._concatOutputChunks(t,e):e}_diff(t,e){if(e)return t?gi(t,e):[{op:"replace",path:"",value:e}]}async parsePartialResult(t){return ws(t[0].text)}async parse(t){return ws(t,JSON.parse)}getFormatInstructions(){return""}};const m_=function(){const t={};t.parser=function(g,m){return new r(g,m)},t.SAXParser=r,t.SAXStream=u,t.createStream=c,t.MAX_BUFFER_LENGTH=64*1024;const e=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];t.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function r(g,m){if(!(this instanceof r))return new r(g,m);var S=this;a(S),S.q=S.c="",S.bufferCheckPosition=t.MAX_BUFFER_LENGTH,S.opt=m||{},S.opt.lowercase=S.opt.lowercase||S.opt.lowercasetags,S.looseCase=S.opt.lowercase?"toLowerCase":"toUpperCase",S.tags=[],S.closed=S.closedRoot=S.sawRoot=!1,S.tag=S.error=null,S.strict=!!g,S.noscript=!!(g||S.opt.noscript),S.state=v.BEGIN,S.strictEntities=S.opt.strictEntities,S.ENTITIES=S.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),S.attribList=[],S.opt.xmlns&&(S.ns=Object.create(p)),S.trackPosition=S.opt.position!==!1,S.trackPosition&&(S.position=S.line=S.column=0),_e(S,"onready")}Object.create||(Object.create=function(g){function m(){}m.prototype=g;var S=new m;return S}),Object.keys||(Object.keys=function(g){var m=[];for(var S in g)g.hasOwnProperty(S)&&m.push(S);return m});function n(g){for(var m=Math.max(t.MAX_BUFFER_LENGTH,10),S=0,b=0,se=e.length;b<se;b++){var me=g[e[b]].length;if(me>m)switch(e[b]){case"textNode":Ne(g);break;case"cdata":oe(g,"oncdata",g.cdata),g.cdata="";break;case"script":oe(g,"onscript",g.script),g.script="";break;default:C(g,"Max buffer length exceeded: "+e[b])}S=Math.max(S,me)}var ye=t.MAX_BUFFER_LENGTH-S;g.bufferCheckPosition=ye+g.position}function a(g){for(var m=0,S=e.length;m<S;m++)g[e[m]]=""}function s(g){Ne(g),g.cdata!==""&&(oe(g,"oncdata",g.cdata),g.cdata=""),g.script!==""&&(oe(g,"onscript",g.script),g.script="")}r.prototype={end:function(){O(this)},write:ce,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){s(this)}};var i=ReadableStream;i||(i=function(){});var o=t.EVENTS.filter(function(g){return g!=="error"&&g!=="end"});function c(g,m){return new u(g,m)}function u(g,m){if(!(this instanceof u))return new u(g,m);i.apply(this),this._parser=new r(g,m),this.writable=!0,this.readable=!0;var S=this;this._parser.onend=function(){S.emit("end")},this._parser.onerror=function(b){S.emit("error",b),S._parser.error=null},this._decoder=null,o.forEach(function(b){Object.defineProperty(S,"on"+b,{get:function(){return S._parser["on"+b]},set:function(se){if(!se)return S.removeAllListeners(b),S._parser["on"+b]=se,se;S.on(b,se)},enumerable:!0,configurable:!1})})}u.prototype=Object.create(i.prototype,{constructor:{value:u}}),u.prototype.write=function(g){return this._parser.write(g.toString()),this.emit("data",g),!0},u.prototype.end=function(g){return g&&g.length&&this.write(g),this._parser.end(),!0},u.prototype.on=function(g,m){var S=this;return!S._parser["on"+g]&&o.indexOf(g)!==-1&&(S._parser["on"+g]=function(){var b=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);b.splice(0,0,g),S.emit.apply(S,b)}),i.prototype.on.call(S,g,m)};var l="[CDATA[",d="DOCTYPE",h="http://www.w3.org/XML/1998/namespace",f="http://www.w3.org/2000/xmlns/",p={xml:h,xmlns:f},y=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,_=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,w=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,T=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function E(g){return g===" "||g===`
121
+ `||g==="\r"||g===" "}function x(g){return g==='"'||g==="'"}function R(g){return g===">"||E(g)}function j(g,m){return g.test(m)}function J(g,m){return!j(g,m)}var v=0;t.STATE={BEGIN:v++,BEGIN_WHITESPACE:v++,TEXT:v++,TEXT_ENTITY:v++,OPEN_WAKA:v++,SGML_DECL:v++,SGML_DECL_QUOTED:v++,DOCTYPE:v++,DOCTYPE_QUOTED:v++,DOCTYPE_DTD:v++,DOCTYPE_DTD_QUOTED:v++,COMMENT_STARTING:v++,COMMENT:v++,COMMENT_ENDING:v++,COMMENT_ENDED:v++,CDATA:v++,CDATA_ENDING:v++,CDATA_ENDING_2:v++,PROC_INST:v++,PROC_INST_BODY:v++,PROC_INST_ENDING:v++,OPEN_TAG:v++,OPEN_TAG_SLASH:v++,ATTRIB:v++,ATTRIB_NAME:v++,ATTRIB_NAME_SAW_WHITE:v++,ATTRIB_VALUE:v++,ATTRIB_VALUE_QUOTED:v++,ATTRIB_VALUE_CLOSED:v++,ATTRIB_VALUE_UNQUOTED:v++,ATTRIB_VALUE_ENTITY_Q:v++,ATTRIB_VALUE_ENTITY_U:v++,CLOSE_TAG:v++,CLOSE_TAG_SAW_WHITE:v++,SCRIPT:v++,SCRIPT_ENDING:v++},t.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},t.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(t.ENTITIES).forEach(function(g){var m=t.ENTITIES[g],S=typeof m=="number"?String.fromCharCode(m):m;t.ENTITIES[g]=S});for(var ge in t.STATE)t.STATE[t.STATE[ge]]=ge;v=t.STATE;function _e(g,m,S){g[m]&&g[m](S)}function oe(g,m,S){g.textNode&&Ne(g),_e(g,m,S)}function Ne(g){g.textNode=wt(g.opt,g.textNode),g.textNode&&_e(g,"ontext",g.textNode),g.textNode=""}function wt(g,m){return g.trim&&(m=m.trim()),g.normalize&&(m=m.replace(/\s+/g," ")),m}function C(g,m){return Ne(g),g.trackPosition&&(m+=`
122
+ Line: `+g.line+`
123
+ Column: `+g.column+`
124
+ Char: `+g.c),m=new Error(m),g.error=m,_e(g,"onerror",m),g}function O(g){return g.sawRoot&&!g.closedRoot&&k(g,"Unclosed root tag"),g.state!==v.BEGIN&&g.state!==v.BEGIN_WHITESPACE&&g.state!==v.TEXT&&C(g,"Unexpected end"),Ne(g),g.c="",g.closed=!0,_e(g,"onend"),r.call(g,g.strict,g.opt),g}function k(g,m){if(typeof g!="object"||!(g instanceof r))throw new Error("bad call to strictFail");g.strict&&C(g,m)}function B(g){g.strict||(g.tagName=g.tagName[g.looseCase]());var m=g.tags[g.tags.length-1]||g,S=g.tag={name:g.tagName,attributes:{}};g.opt.xmlns&&(S.ns=m.ns),g.attribList.length=0,oe(g,"onopentagstart",S)}function q(g,m){var S=g.indexOf(":"),b=S<0?["",g]:g.split(":"),se=b[0],me=b[1];return m&&g==="xmlns"&&(se="xmlns",me=""),{prefix:se,local:me}}function F(g){if(g.strict||(g.attribName=g.attribName[g.looseCase]()),g.attribList.indexOf(g.attribName)!==-1||g.tag.attributes.hasOwnProperty(g.attribName)){g.attribName=g.attribValue="";return}if(g.opt.xmlns){var m=q(g.attribName,!0),S=m.prefix,b=m.local;if(S==="xmlns")if(b==="xml"&&g.attribValue!==h)k(g,"xml: prefix must be bound to "+h+`
125
+ Actual: `+g.attribValue);else if(b==="xmlns"&&g.attribValue!==f)k(g,"xmlns: prefix must be bound to "+f+`
126
+ Actual: `+g.attribValue);else{var se=g.tag,me=g.tags[g.tags.length-1]||g;se.ns===me.ns&&(se.ns=Object.create(me.ns)),se.ns[b]=g.attribValue}g.attribList.push([g.attribName,g.attribValue])}else g.tag.attributes[g.attribName]=g.attribValue,oe(g,"onattribute",{name:g.attribName,value:g.attribValue});g.attribName=g.attribValue=""}function Z(g,m){if(g.opt.xmlns){var S=g.tag,b=q(g.tagName);S.prefix=b.prefix,S.local=b.local,S.uri=S.ns[b.prefix]||"",S.prefix&&!S.uri&&(k(g,"Unbound namespace prefix: "+JSON.stringify(g.tagName)),S.uri=b.prefix);var se=g.tags[g.tags.length-1]||g;S.ns&&se.ns!==S.ns&&Object.keys(S.ns).forEach(function(Bt){oe(g,"onopennamespace",{prefix:Bt,uri:S.ns[Bt]})});for(var me=0,ye=g.attribList.length;me<ye;me++){var Ie=g.attribList[me],$e=Ie[0],et=Ie[1],be=q($e,!0),Ye=be.prefix,er=be.local,Yr=Ye===""?"":S.ns[Ye]||"",P={name:$e,value:et,prefix:Ye,local:er,uri:Yr};Ye&&Ye!=="xmlns"&&!Yr&&(k(g,"Unbound namespace prefix: "+JSON.stringify(Ye)),P.uri=Ye),g.tag.attributes[$e]=P,oe(g,"onattribute",P)}g.attribList.length=0}g.tag.isSelfClosing=!!m,g.sawRoot=!0,g.tags.push(g.tag),oe(g,"onopentag",g.tag),m||(!g.noscript&&g.tagName.toLowerCase()==="script"?g.state=v.SCRIPT:g.state=v.TEXT,g.tag=null,g.tagName=""),g.attribName=g.attribValue="",g.attribList.length=0}function ae(g){if(!g.tagName){k(g,"Weird empty close tag."),g.textNode+="</>",g.state=v.TEXT;return}if(g.script){if(g.tagName!=="script"){g.script+="</"+g.tagName+">",g.tagName="",g.state=v.SCRIPT;return}oe(g,"onscript",g.script),g.script=""}var m=g.tags.length,S=g.tagName;g.strict||(S=S[g.looseCase]());for(var b=S;m--;){var se=g.tags[m];if(se.name!==b)k(g,"Unexpected close tag");else break}if(m<0){k(g,"Unmatched closing tag: "+g.tagName),g.textNode+="</"+g.tagName+">",g.state=v.TEXT;return}g.tagName=S;for(var me=g.tags.length;me-- >m;){var ye=g.tag=g.tags.pop();g.tagName=g.tag.name,oe(g,"onclosetag",g.tagName);var Ie={};for(var $e in ye.ns)Ie[$e]=ye.ns[$e];var et=g.tags[g.tags.length-1]||g;g.opt.xmlns&&ye.ns!==et.ns&&Object.keys(ye.ns).forEach(function(be){var Ye=ye.ns[be];oe(g,"onclosenamespace",{prefix:be,uri:Ye})})}m===0&&(g.closedRoot=!0),g.tagName=g.attribValue=g.attribName="",g.attribList.length=0,g.state=v.TEXT}function ee(g){var m=g.entity,S=m.toLowerCase(),b,se="";return g.ENTITIES[m]?g.ENTITIES[m]:g.ENTITIES[S]?g.ENTITIES[S]:(m=S,m.charAt(0)==="#"&&(m.charAt(1)==="x"?(m=m.slice(2),b=parseInt(m,16),se=b.toString(16)):(m=m.slice(1),b=parseInt(m,10),se=b.toString(10))),m=m.replace(/^0+/,""),isNaN(b)||se.toLowerCase()!==m?(k(g,"Invalid character entity"),"&"+g.entity+";"):String.fromCodePoint(b))}function le(g,m){m==="<"?(g.state=v.OPEN_WAKA,g.startTagPosition=g.position):E(m)||(k(g,"Non-whitespace before first tag."),g.textNode=m,g.state=v.TEXT)}function Te(g,m){var S="";return m<g.length&&(S=g.charAt(m)),S}function ce(g){var m=this;if(this.error)throw this.error;if(m.closed)return C(m,"Cannot write after close. Assign an onready handler.");if(g===null)return O(m);typeof g=="object"&&(g=g.toString());for(var S=0,b="";b=Te(g,S++),m.c=b,!!b;)switch(m.trackPosition&&(m.position++,b===`
127
+ `?(m.line++,m.column=0):m.column++),m.state){case v.BEGIN:if(m.state=v.BEGIN_WHITESPACE,b==="\uFEFF")continue;le(m,b);continue;case v.BEGIN_WHITESPACE:le(m,b);continue;case v.TEXT:if(m.sawRoot&&!m.closedRoot){for(var se=S-1;b&&b!=="<"&&b!=="&";)b=Te(g,S++),b&&m.trackPosition&&(m.position++,b===`
128
+ `?(m.line++,m.column=0):m.column++);m.textNode+=g.substring(se,S-1)}b==="<"&&!(m.sawRoot&&m.closedRoot&&!m.strict)?(m.state=v.OPEN_WAKA,m.startTagPosition=m.position):(!E(b)&&(!m.sawRoot||m.closedRoot)&&k(m,"Text data outside of root node."),b==="&"?m.state=v.TEXT_ENTITY:m.textNode+=b);continue;case v.SCRIPT:b==="<"?m.state=v.SCRIPT_ENDING:m.script+=b;continue;case v.SCRIPT_ENDING:b==="/"?m.state=v.CLOSE_TAG:(m.script+="<"+b,m.state=v.SCRIPT);continue;case v.OPEN_WAKA:if(b==="!")m.state=v.SGML_DECL,m.sgmlDecl="";else if(!E(b))if(j(y,b))m.state=v.OPEN_TAG,m.tagName=b;else if(b==="/")m.state=v.CLOSE_TAG,m.tagName="";else if(b==="?")m.state=v.PROC_INST,m.procInstName=m.procInstBody="";else{if(k(m,"Unencoded <"),m.startTagPosition+1<m.position){var me=m.position-m.startTagPosition;b=new Array(me).join(" ")+b}m.textNode+="<"+b,m.state=v.TEXT}continue;case v.SGML_DECL:(m.sgmlDecl+b).toUpperCase()===l?(oe(m,"onopencdata"),m.state=v.CDATA,m.sgmlDecl="",m.cdata=""):m.sgmlDecl+b==="--"?(m.state=v.COMMENT,m.comment="",m.sgmlDecl=""):(m.sgmlDecl+b).toUpperCase()===d?(m.state=v.DOCTYPE,(m.doctype||m.sawRoot)&&k(m,"Inappropriately located doctype declaration"),m.doctype="",m.sgmlDecl=""):b===">"?(oe(m,"onsgmldeclaration",m.sgmlDecl),m.sgmlDecl="",m.state=v.TEXT):(x(b)&&(m.state=v.SGML_DECL_QUOTED),m.sgmlDecl+=b);continue;case v.SGML_DECL_QUOTED:b===m.q&&(m.state=v.SGML_DECL,m.q=""),m.sgmlDecl+=b;continue;case v.DOCTYPE:b===">"?(m.state=v.TEXT,oe(m,"ondoctype",m.doctype),m.doctype=!0):(m.doctype+=b,b==="["?m.state=v.DOCTYPE_DTD:x(b)&&(m.state=v.DOCTYPE_QUOTED,m.q=b));continue;case v.DOCTYPE_QUOTED:m.doctype+=b,b===m.q&&(m.q="",m.state=v.DOCTYPE);continue;case v.DOCTYPE_DTD:m.doctype+=b,b==="]"?m.state=v.DOCTYPE:x(b)&&(m.state=v.DOCTYPE_DTD_QUOTED,m.q=b);continue;case v.DOCTYPE_DTD_QUOTED:m.doctype+=b,b===m.q&&(m.state=v.DOCTYPE_DTD,m.q="");continue;case v.COMMENT:b==="-"?m.state=v.COMMENT_ENDING:m.comment+=b;continue;case v.COMMENT_ENDING:b==="-"?(m.state=v.COMMENT_ENDED,m.comment=wt(m.opt,m.comment),m.comment&&oe(m,"oncomment",m.comment),m.comment=""):(m.comment+="-"+b,m.state=v.COMMENT);continue;case v.COMMENT_ENDED:b!==">"?(k(m,"Malformed comment"),m.comment+="--"+b,m.state=v.COMMENT):m.state=v.TEXT;continue;case v.CDATA:b==="]"?m.state=v.CDATA_ENDING:m.cdata+=b;continue;case v.CDATA_ENDING:b==="]"?m.state=v.CDATA_ENDING_2:(m.cdata+="]"+b,m.state=v.CDATA);continue;case v.CDATA_ENDING_2:b===">"?(m.cdata&&oe(m,"oncdata",m.cdata),oe(m,"onclosecdata"),m.cdata="",m.state=v.TEXT):b==="]"?m.cdata+="]":(m.cdata+="]]"+b,m.state=v.CDATA);continue;case v.PROC_INST:b==="?"?m.state=v.PROC_INST_ENDING:E(b)?m.state=v.PROC_INST_BODY:m.procInstName+=b;continue;case v.PROC_INST_BODY:if(!m.procInstBody&&E(b))continue;b==="?"?m.state=v.PROC_INST_ENDING:m.procInstBody+=b;continue;case v.PROC_INST_ENDING:b===">"?(oe(m,"onprocessinginstruction",{name:m.procInstName,body:m.procInstBody}),m.procInstName=m.procInstBody="",m.state=v.TEXT):(m.procInstBody+="?"+b,m.state=v.PROC_INST_BODY);continue;case v.OPEN_TAG:j(_,b)?m.tagName+=b:(B(m),b===">"?Z(m):b==="/"?m.state=v.OPEN_TAG_SLASH:(E(b)||k(m,"Invalid character in tag name"),m.state=v.ATTRIB));continue;case v.OPEN_TAG_SLASH:b===">"?(Z(m,!0),ae(m)):(k(m,"Forward-slash in opening tag not followed by >"),m.state=v.ATTRIB);continue;case v.ATTRIB:if(E(b))continue;b===">"?Z(m):b==="/"?m.state=v.OPEN_TAG_SLASH:j(y,b)?(m.attribName=b,m.attribValue="",m.state=v.ATTRIB_NAME):k(m,"Invalid attribute name");continue;case v.ATTRIB_NAME:b==="="?m.state=v.ATTRIB_VALUE:b===">"?(k(m,"Attribute without value"),m.attribValue=m.attribName,F(m),Z(m)):E(b)?m.state=v.ATTRIB_NAME_SAW_WHITE:j(_,b)?m.attribName+=b:k(m,"Invalid attribute name");continue;case v.ATTRIB_NAME_SAW_WHITE:if(b==="=")m.state=v.ATTRIB_VALUE;else{if(E(b))continue;k(m,"Attribute without value"),m.tag.attributes[m.attribName]="",m.attribValue="",oe(m,"onattribute",{name:m.attribName,value:""}),m.attribName="",b===">"?Z(m):j(y,b)?(m.attribName=b,m.state=v.ATTRIB_NAME):(k(m,"Invalid attribute name"),m.state=v.ATTRIB)}continue;case v.ATTRIB_VALUE:if(E(b))continue;x(b)?(m.q=b,m.state=v.ATTRIB_VALUE_QUOTED):(k(m,"Unquoted attribute value"),m.state=v.ATTRIB_VALUE_UNQUOTED,m.attribValue=b);continue;case v.ATTRIB_VALUE_QUOTED:if(b!==m.q){b==="&"?m.state=v.ATTRIB_VALUE_ENTITY_Q:m.attribValue+=b;continue}F(m),m.q="",m.state=v.ATTRIB_VALUE_CLOSED;continue;case v.ATTRIB_VALUE_CLOSED:E(b)?m.state=v.ATTRIB:b===">"?Z(m):b==="/"?m.state=v.OPEN_TAG_SLASH:j(y,b)?(k(m,"No whitespace between attributes"),m.attribName=b,m.attribValue="",m.state=v.ATTRIB_NAME):k(m,"Invalid attribute name");continue;case v.ATTRIB_VALUE_UNQUOTED:if(!R(b)){b==="&"?m.state=v.ATTRIB_VALUE_ENTITY_U:m.attribValue+=b;continue}F(m),b===">"?Z(m):m.state=v.ATTRIB;continue;case v.CLOSE_TAG:if(m.tagName)b===">"?ae(m):j(_,b)?m.tagName+=b:m.script?(m.script+="</"+m.tagName,m.tagName="",m.state=v.SCRIPT):(E(b)||k(m,"Invalid tagname in closing tag"),m.state=v.CLOSE_TAG_SAW_WHITE);else{if(E(b))continue;J(y,b)?m.script?(m.script+="</"+b,m.state=v.SCRIPT):k(m,"Invalid tagname in closing tag."):m.tagName=b}continue;case v.CLOSE_TAG_SAW_WHITE:if(E(b))continue;b===">"?ae(m):k(m,"Invalid characters in closing tag");continue;case v.TEXT_ENTITY:case v.ATTRIB_VALUE_ENTITY_Q:case v.ATTRIB_VALUE_ENTITY_U:var ye,Ie;switch(m.state){case v.TEXT_ENTITY:ye=v.TEXT,Ie="textNode";break;case v.ATTRIB_VALUE_ENTITY_Q:ye=v.ATTRIB_VALUE_QUOTED,Ie="attribValue";break;case v.ATTRIB_VALUE_ENTITY_U:ye=v.ATTRIB_VALUE_UNQUOTED,Ie="attribValue";break}if(b===";")if(m.opt.unparsedEntities){var $e=ee(m);m.entity="",m.state=ye,m.write($e)}else m[Ie]+=ee(m),m.entity="",m.state=ye;else j(m.entity.length?T:w,b)?m.entity+=b:(k(m,"Invalid character in entity name"),m[Ie]+="&"+m.entity+b,m.entity="",m.state=ye);continue;default:throw new Error(m,"Unknown state: "+m.state)}return m.position>=m.bufferCheckPosition&&n(m),m}return String.fromCodePoint||(function(){var g=String.fromCharCode,m=Math.floor,S=function(){var b=16384,se=[],me,ye,Ie=-1,$e=arguments.length;if(!$e)return"";for(var et="";++Ie<$e;){var be=Number(arguments[Ie]);if(!isFinite(be)||be<0||be>1114111||m(be)!==be)throw RangeError("Invalid code point: "+be);be<=65535?se.push(be):(be-=65536,me=(be>>10)+55296,ye=be%1024+56320,se.push(me,ye)),(Ie+1===$e||se.length>b)&&(et+=g.apply(null,se),se.length=0)}return et};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:S,configurable:!0,writable:!0}):String.fromCodePoint=S})(),t},g_=m_(),Gs=`The output should be formatted as a XML file.
129
+ 1. Output should conform to the tags below.
130
+ 2. If tags are not given, make them on your own.
131
+ 3. Remember to always open and close all the tags.
132
+
133
+ As an example, for the tags ["foo", "bar", "baz"]:
134
+ 1. String "<foo>
135
+ <bar>
136
+ <baz></baz>
137
+ </bar>
138
+ </foo>" is a well-formatted instance of the schema.
139
+ 2. String "<foo>
140
+ <bar>
141
+ </foo>" is a badly-formatted instance.
142
+ 3. String "<foo>
143
+ <tag>
144
+ </tag>
145
+ </foo>" is a badly-formatted instance.
146
+
147
+ Here are the output tags:
148
+ \`\`\`
149
+ {tags}
150
+ \`\`\``;var y_=class extends Ai{tags;constructor(t){super(t),this.tags=t?.tags}static lc_name(){return"XMLOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_diff(t,e){if(e)return t?gi(t,e):[{op:"replace",path:"",value:e}]}async parsePartialResult(t){return Hs(t[0].text)}async parse(t){return Hs(t)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?Gs.replace("{tags}",this.tags?.join(", ")??""):Gs}};const __=t=>t.split(`
151
+ `).map(e=>e.replace(/^\s+/,"")).join(`
152
+ `).trim(),Ul=t=>{if(Object.keys(t).length===0)return{};const e={};return t.children.length>0?(e[t.name]=t.children.map(Ul),e):(e[t.name]=t.text??void 0,e)};function Hs(t){const e=__(t),r=g_.parser(!0);let n={};const a=[];r.onopentag=o=>{const c={name:o.name,attributes:o.attributes,children:[],text:"",isSelfClosing:o.isSelfClosing};a.length>0?a[a.length-1].children.push(c):n=c,o.isSelfClosing||a.push(c)},r.onclosetag=()=>{if(a.length>0){const o=a.pop();a.length===0&&o&&(n=o)}},r.ontext=o=>{if(a.length>0){const c=a[a.length-1];c.text+=o}},r.onattribute=o=>{if(a.length>0){const c=a[a.length-1];c.attributes[o.name]=o.value}};const s=/```(xml)?(.*)```/s.exec(e),i=s?s[2]:e;return r.write(i).close(),n&&n.name==="?xml"&&(n=n.children[0]),Ul(n)}var v_={};pe(v_,{AsymmetricStructuredOutputParser:()=>h_,BaseCumulativeTransformOutputParser:()=>Ai,BaseLLMOutputParser:()=>Ll,BaseOutputParser:()=>Vn,BaseTransformOutputParser:()=>Wr,BytesOutputParser:()=>i_,CommaSeparatedListOutputParser:()=>o_,CustomListOutputParser:()=>c_,JsonMarkdownStructuredOutputParser:()=>Dl,JsonOutputParser:()=>p_,ListOutputParser:()=>Kr,MarkdownListOutputParser:()=>l_,NumberedListOutputParser:()=>u_,OutputParserException:()=>Vt,StringOutputParser:()=>d_,StructuredOutputParser:()=>jl,XMLOutputParser:()=>y_,XML_FORMAT_INSTRUCTIONS:()=>Gs,parseJsonMarkdown:()=>ws,parsePartialJson:()=>ni,parseXMLMarkdown:()=>Hs});export{qn as $,Bn as A,Ai as B,gt as C,It as D,Jt as E,Tn as F,zr as G,br as H,Tt as I,jt as J,js as K,Xt as L,Gr as M,eu as N,Vt as O,Ky as P,Lt as Q,Ls as R,Td as S,ph as T,vs as U,Ll as V,Ml as W,Pt as X,p_ as Y,kn as Z,pe as _,nu as a,rm as a$,Ot as a0,Oy as a1,A as a2,Ci as a3,Re as a4,xe as a5,jl as a6,wi as a7,Ft as a8,Pn as a9,Sl as aA,wr as aB,Vn as aC,Iy as aD,Vy as aE,hm as aF,iy as aG,f_ as aH,Ny as aI,Ay as aJ,Th as aK,Sm as aL,Xp as aM,vm as aN,Vp as aO,zp as aP,lm as aQ,oy as aR,s_ as aS,ky as aT,bm as aU,v_ as aV,Qd as aW,xy as aX,Nd as aY,e_ as aZ,Jy as a_,pr as aa,$n as ab,Rn as ac,Cn as ad,Ed as ae,mh as af,Ah as ag,pu as ah,xh as ai,gr as aj,Qt as ak,ct as al,Pm as am,sy as an,eo as ao,fr as ap,Se as aq,Ur as ar,xl as as,gi as at,Tl as au,su as av,Ry as aw,Dt as ax,kr as ay,At as az,Pl as b,im as b0,Mh as b1,$y as b2,Xs as b3,Cd as b4,$_ as b5,ot as b6,Hr as b7,ti as b8,Ke as b9,E_ as bA,yy as bB,Yt as bC,Ei as ba,Cr as bb,jm as bc,Ds as bd,Mm as be,Lm as bf,Nm as bg,Ue as bh,vd as bi,ie as bj,A_ as bk,R_ as bl,x_ as bm,Gi as bn,Fm as bo,k_ as bp,I_ as bq,T_ as br,N_ as bs,Cm as bt,_n as bu,Nl as bv,vy as bw,C_ as bx,O_ as by,S_ as bz,mu as c,Wt as d,om as e,$l as f,de as g,iu as h,Rm as i,Jr as j,vi as k,P_ as l,Os as m,Qc as n,_r as o,ni as p,wl as q,_l as r,vl as s,bl as t,Ws as u,ve as v,Js as w,Qu as x,hn as y,we as z};