@transai/connector-runner-ai-agent 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +11 -0
  3. package/index.cjs +196 -0
  4. package/index.cjs.map +7 -0
  5. package/index.js +196 -0
  6. package/index.js.map +7 -0
  7. package/libs/connector-runner-ai-agent/src/index.d.ts +1 -0
  8. package/libs/connector-runner-ai-agent/src/lib/connector-runner-ai-agent.d.ts +13 -0
  9. package/libs/connector-runner-ai-agent/src/lib/output-parsers/index.d.ts +1 -0
  10. package/libs/connector-runner-ai-agent/src/lib/output-parsers/output-parser-factory.d.ts +2 -0
  11. package/libs/connector-runner-ai-agent/src/lib/types.d.ts +9 -0
  12. package/libs/connector-runtime-sdk/src/index.d.ts +3 -0
  13. package/libs/connector-runtime-sdk/src/lib/connector-runtime.d.ts +16 -0
  14. package/libs/connector-runtime-sdk/src/lib/connector-runtime.interface.d.ts +5 -0
  15. package/libs/connector-runtime-sdk/src/lib/sdk/index.d.ts +7 -0
  16. package/libs/connector-runtime-sdk/src/lib/sdk/logger.sdk.interface.d.ts +7 -0
  17. package/libs/connector-runtime-sdk/src/lib/sdk/offset-store.sdk.interface.d.ts +11 -0
  18. package/libs/connector-runtime-sdk/src/lib/sdk/processing.sdk.interface.d.ts +12 -0
  19. package/libs/connector-runtime-sdk/src/lib/sdk/receiver.sdk.interface.d.ts +14 -0
  20. package/libs/connector-runtime-sdk/src/lib/sdk/sdk.interface.d.ts +16 -0
  21. package/libs/connector-runtime-sdk/src/lib/sdk/sender.sdk.interface.d.ts +22 -0
  22. package/libs/connector-runtime-sdk/src/lib/sdk/templating.sdk.interface.d.ts +12 -0
  23. package/libs/types/src/index.d.ts +7 -0
  24. package/libs/types/src/lib/cube-query-config.types.d.ts +20 -0
  25. package/libs/types/src/lib/file-action.types.d.ts +5 -0
  26. package/libs/types/src/lib/http-status-codes.enum.d.ts +63 -0
  27. package/libs/types/src/lib/management-api/action-definition.interface.d.ts +12 -0
  28. package/libs/types/src/lib/management-api/chart.interface.d.ts +9 -0
  29. package/libs/types/src/lib/management-api/connector/connector.interface.d.ts +140 -0
  30. package/libs/types/src/lib/management-api/connector/connectors.interface.d.ts +126 -0
  31. package/libs/types/src/lib/management-api/connector-orchestrator-config.interface.d.ts +14 -0
  32. package/libs/types/src/lib/management-api/cube-dataset.interface.d.ts +93 -0
  33. package/libs/types/src/lib/management-api/dashboard.interface.d.ts +35 -0
  34. package/libs/types/src/lib/management-api/dataset/collection.interface.d.ts +16 -0
  35. package/libs/types/src/lib/management-api/dataset/dataset-record.interface.d.ts +5 -0
  36. package/libs/types/src/lib/management-api/dataset/dataset.interface.d.ts +730 -0
  37. package/libs/types/src/lib/management-api/dataset/datasets.interface.d.ts +710 -0
  38. package/libs/types/src/lib/management-api/dataset/dimension.interface.d.ts +205 -0
  39. package/libs/types/src/lib/management-api/dataset/dimensions.interface.d.ts +186 -0
  40. package/libs/types/src/lib/management-api/dataset/filter-group.interface.d.ts +8 -0
  41. package/libs/types/src/lib/management-api/dataset/filter.interface.d.ts +34 -0
  42. package/libs/types/src/lib/management-api/dataset/filters.interface.d.ts +7 -0
  43. package/libs/types/src/lib/management-api/dataset/measure.interface.d.ts +65 -0
  44. package/libs/types/src/lib/management-api/dataset/measures.interface.d.ts +56 -0
  45. package/libs/types/src/lib/management-api/dataset/meta.interface.d.ts +9 -0
  46. package/libs/types/src/lib/management-api/dataset/pre-aggregate.interface.d.ts +69 -0
  47. package/libs/types/src/lib/management-api/dataset/pre-aggregations.interface.d.ts +54 -0
  48. package/libs/types/src/lib/management-api/dataset/relation.interface.d.ts +40 -0
  49. package/libs/types/src/lib/management-api/dataset/relations.interface.d.ts +36 -0
  50. package/libs/types/src/lib/management-api/dataset/segment.interface.d.ts +45 -0
  51. package/libs/types/src/lib/management-api/dataset/segments.interface.d.ts +43 -0
  52. package/libs/types/src/lib/management-api/dataset/switch.interface.d.ts +70 -0
  53. package/libs/types/src/lib/management-api/dataset/when-item.interface.d.ts +41 -0
  54. package/libs/types/src/lib/management-api/dataset/when-items.interface.d.ts +40 -0
  55. package/libs/types/src/lib/management-api/event-origin.interface.d.ts +22 -0
  56. package/libs/types/src/lib/management-api/index.d.ts +39 -0
  57. package/libs/types/src/lib/management-api/pagination/index.d.ts +1 -0
  58. package/libs/types/src/lib/management-api/pagination/paginated-response.interface.d.ts +17 -0
  59. package/libs/types/src/lib/management-api/semantic-trigger/index.d.ts +5 -0
  60. package/libs/types/src/lib/management-api/semantic-trigger/semantic-trigger-filter.interface.d.ts +20 -0
  61. package/libs/types/src/lib/management-api/semantic-trigger/semantic-trigger-filters.interface.d.ts +18 -0
  62. package/libs/types/src/lib/management-api/semantic-trigger/semantic-trigger-record.interface.d.ts +6 -0
  63. package/libs/types/src/lib/management-api/semantic-trigger/semantic-trigger.interface.d.ts +74 -0
  64. package/libs/types/src/lib/management-api/semantic-trigger/semantic-triggers.interface.d.ts +62 -0
  65. package/libs/types/src/lib/management-api/template-implementation-overrides.interface.d.ts +1152 -0
  66. package/libs/types/src/lib/management-api/template-implementation.interface.d.ts +2860 -0
  67. package/libs/types/src/lib/management-api/template.interface.d.ts +1191 -0
  68. package/libs/types/src/lib/management-api/tenant.interface.d.ts +8 -0
  69. package/libs/types/src/lib/management-api/type-enums.d.ts +85 -0
  70. package/libs/types/src/lib/management-api/workflow/action.interface.d.ts +85 -0
  71. package/libs/types/src/lib/management-api/workflow/index.d.ts +6 -0
  72. package/libs/types/src/lib/management-api/workflow/offset.interface.d.ts +16 -0
  73. package/libs/types/src/lib/management-api/workflow/trigger-types.interface.d.ts +5 -0
  74. package/libs/types/src/lib/management-api/workflow/workflow-definition.interface.d.ts +49 -0
  75. package/libs/types/src/lib/management-api/workflow/workflow-run.d.ts +65 -0
  76. package/libs/types/src/lib/management-api/workflow/workflow.drawing.d.ts +101 -0
  77. package/libs/types/src/lib/message.types.d.ts +59 -0
  78. package/libs/types/src/lib/response.types.d.ts +27 -0
  79. package/libs/types/src/lib/types.d.ts +113 -0
  80. package/package.json +12 -0
package/index.js ADDED
@@ -0,0 +1,196 @@
1
+ var F0=Object.create;var Ql=Object.defineProperty;var U0=Object.getOwnPropertyDescriptor;var B0=Object.getOwnPropertyNames;var Z0=Object.getPrototypeOf,V0=Object.prototype.hasOwnProperty;var _=(r,e)=>()=>(r&&(e=r(r=0)),e);var D=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),du=(r,e)=>{for(var t in e)Ql(r,t,{get:e[t],enumerable:!0})},q0=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of B0(e))!V0.call(r,s)&&s!==t&&Ql(r,s,{get:()=>e[s],enumerable:!(n=U0(e,s))||n.enumerable});return r};var Dt=(r,e,t)=>(t=r!=null?F0(Z0(r)):{},q0(e||!r||!r.__esModule?Ql(t,"default",{value:r,enumerable:!0}):t,r));var ie,ed,R,sr,Ti=_(()=>{"use strict";(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let a={};for(let i of s)a[i]=i;return a},r.getValidEnumValues=s=>{let a=r.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(let o of a)i[o]=s[o];return r.objectValues(i)},r.objectValues=s=>r.objectKeys(s).map(function(a){return s[a]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let a=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},r.find=(s,a)=>{for(let i of s)if(a(i))return i},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}r.joinValues=n,r.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(ie||(ie={}));(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(ed||(ed={}));R=ie.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),sr=r=>{switch(typeof r){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(r)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(r)?R.array:r===null?R.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?R.promise:typeof Map<"u"&&r instanceof Map?R.map:typeof Set<"u"&&r instanceof Set?R.set:typeof Date<"u"&&r instanceof Date?R.date:R.object;default:return R.unknown}}});var A,G0,rt,pu=_(()=>{"use strict";Ti();A=ie.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"]),G0=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),rt=class r 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]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(a){return a.message},n={_errors:[]},s=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let o=n,u=0;for(;u<i.path.length;){let c=i.path[u];u===i.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(t(i))):o[c]=o[c]||{_errors:[]},o=o[c],u++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ie.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let a=s.path[0];t[a]=t[a]||[],t[a].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};rt.create=r=>new rt(r)});var H0,Pr,td=_(()=>{"use strict";pu();Ti();H0=(r,e)=>{let t;switch(r.code){case A.invalid_type:r.received===R.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case A.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,ie.jsonStringifyReplacer)}`;break;case A.unrecognized_keys:t=`Unrecognized key(s) in object: ${ie.joinValues(r.keys,", ")}`;break;case A.invalid_union:t="Invalid input";break;case A.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${ie.joinValues(r.options)}`;break;case A.invalid_enum_value:t=`Invalid enum value. Expected ${ie.joinValues(r.options)}, received '${r.received}'`;break;case A.invalid_arguments:t="Invalid function arguments";break;case A.invalid_return_type:t="Invalid function return type";break;case A.invalid_date:t="Invalid date";break;case A.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:ie.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case A.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case A.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case A.custom:t="Invalid input";break;case A.invalid_intersection_types:t="Intersection results could not be merged";break;case A.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case A.not_finite:t="Number must be finite";break;default:t=e.defaultError,ie.assertNever(r)}return{message:t}},Pr=H0});function K0(r){vh=r}function Xs(){return vh}var vh,fu=_(()=>{"use strict";td();vh=Pr});function T(r,e){let t=Xs(),n=Pi({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Pr?void 0:Pr].filter(s=>!!s)});r.common.issues.push(n)}var Pi,W0,Me,q,Ln,Fe,mu,hu,en,Ys,rd=_(()=>{"use strict";fu();td();Pi=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,a=[...t,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="",u=n.filter(c=>!!c).slice().reverse();for(let c of u)o=c(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}},W0=[];Me=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return q;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let a=await s.key,i=await s.value;n.push({key:a,value:i})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return q;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[a.value]=i.value)}return{status:e.value,value:n}}},q=Object.freeze({status:"aborted"}),Ln=r=>({status:"dirty",value:r}),Fe=r=>({status:"valid",value:r}),mu=r=>r.status==="aborted",hu=r=>r.status==="dirty",en=r=>r.status==="valid",Ys=r=>typeof Promise<"u"&&r instanceof Promise});var xh=_(()=>{"use strict"});var L,Eh=_(()=>{"use strict";(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(L||(L={}))});function re(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,o)=>{let{message:u}=r;return i.code==="invalid_enum_value"?{message:u??o.defaultError}:typeof o.data>"u"?{message:u??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:u??t??o.defaultError}},description:s}}function Th(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function pE(r){return new RegExp(`^${Th(r)}$`)}function Ph(r){let e=`${Ih}T${Th(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function fE(r,e){return!!((e==="v4"||!e)&&aE.test(r)||(e==="v6"||!e)&&oE.test(r))}function mE(r,e){if(!tE.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function hE(r,e){return!!((e==="v4"||!e)&&iE.test(r)||(e==="v6"||!e)&&uE.test(r))}function gE(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,a=Number.parseInt(r.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return a%i/10**s}function Qs(r){if(r instanceof nt){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=Et.create(Qs(n))}return new nt({...r._def,shape:()=>e})}else return r instanceof Rr?new Rr({...r._def,type:Qs(r.element)}):r instanceof Et?Et.create(Qs(r.unwrap())):r instanceof ir?ir.create(Qs(r.unwrap())):r instanceof ar?ar.create(r.items.map(e=>Qs(e))):r}function sd(r,e){let t=sr(r),n=sr(e);if(r===e)return{valid:!0,data:r};if(t===R.object&&n===R.object){let s=ie.objectKeys(e),a=ie.objectKeys(r).filter(o=>s.indexOf(o)!==-1),i={...r,...e};for(let o of a){let u=sd(r[o],e[o]);if(!u.valid)return{valid:!1};i[o]=u.data}return{valid:!0,data:i}}else if(t===R.array&&n===R.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let a=0;a<r.length;a++){let i=r[a],o=e[a],u=sd(i,o);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===R.date&&n===R.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}function Sh(r,e){return new Wn({values:r,typeName:v.ZodEnum,...re(e)})}function Oh(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function kh(r,e={},t){return r?rn.create().superRefine((n,s)=>{let a=r(n);if(a instanceof Promise)return a.then(i=>{if(!i){let o=Oh(e,n),u=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:u})}});if(!a){let i=Oh(e,n),o=i.fatal??t??!0;s.addIssue({code:"custom",...i,fatal:o})}}):rn.create()}var At,Ah,se,J0,X0,Y0,Q0,eE,tE,rE,nE,sE,nd,aE,iE,oE,uE,cE,lE,Ih,dE,tn,Dn,Fn,Un,Bn,ea,Zn,Vn,rn,kr,Ft,ta,Rr,nt,qn,Sr,gu,Gn,ar,_u,ra,na,yu,Hn,Kn,Wn,Jn,nn,Ot,Et,ir,Xn,Yn,sa,_E,Si,ki,Qn,yE,v,bE,Rh,Ch,wE,vE,$h,xE,EE,AE,OE,IE,TE,PE,SE,kE,RE,CE,$E,NE,jE,ME,zE,LE,DE,FE,UE,BE,ZE,VE,qE,GE,HE,KE,WE,JE,XE,YE,QE,eA,tA,Nh=_(()=>{"use strict";pu();fu();Eh();rd();Ti();At=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}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}},Ah=(r,e)=>{if(en(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new rt(r.common.issues);return this._error=t,this._error}}};se=class{get description(){return this._def.description}_getType(e){return sr(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:sr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Me,ctx:{common:e.parent.common,data:e.data,parsedType:sr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Ys(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:sr(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Ah(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:sr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return en(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>en(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:sr(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(Ys(s)?s:Promise.resolve(s));return Ah(n,a)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,a)=>{let i=e(s),o=()=>a.addIssue({code:A.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(u=>u?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new Ot({schema:this,typeName:v.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:t=>this["~validate"](t)}}optional(){return Et.create(this,this._def)}nullable(){return ir.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Rr.create(this)}promise(){return nn.create(this,this._def)}or(e){return qn.create([this,e],this._def)}and(e){return Gn.create(this,e,this._def)}transform(e){return new Ot({...re(this._def),schema:this,typeName:v.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Xn({...re(this._def),innerType:this,defaultValue:t,typeName:v.ZodDefault})}brand(){return new Si({typeName:v.ZodBranded,type:this,...re(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Yn({...re(this._def),innerType:this,catchValue:t,typeName:v.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ki.create(this,e)}readonly(){return Qn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},J0=/^c[^\s-]{8,}$/i,X0=/^[0-9a-z]+$/,Y0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Q0=/^[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,eE=/^[a-z0-9_-]{21}$/i,tE=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,rE=/^[-+]?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)?)??$/,nE=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sE="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",aE=/^(?:(?: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])$/,iE=/^(?:(?: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])$/,oE=/^(([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]))$/,uE=/^(([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])$/,cE=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,lE=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ih="((\\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])))",dE=new RegExp(`^${Ih}$`);tn=class r extends se{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){let a=this._getOrReturnCtx(e);return T(a,{code:A.invalid_type,expected:R.string,received:a.parsedType}),q}let n=new Me,s;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),T(s,{code:A.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),T(s,{code:A.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(s=this._getOrReturnCtx(e,s),i?T(s,{code:A.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&T(s,{code:A.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")nE.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"email",code:A.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")nd||(nd=new RegExp(sE,"u")),nd.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"emoji",code:A.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")Q0.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"uuid",code:A.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")eE.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"nanoid",code:A.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")J0.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"cuid",code:A.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")X0.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"cuid2",code:A.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")Y0.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"ulid",code:A.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),T(s,{validation:"url",code:A.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"regex",code:A.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),T(s,{code:A.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),T(s,{code:A.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),T(s,{code:A.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?Ph(a).test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{code:A.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?dE.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{code:A.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?pE(a).test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{code:A.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?rE.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"duration",code:A.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?fE(e.data,a.version)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"ip",code:A.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?mE(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"jwt",code:A.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?hE(e.data,a.version)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"cidr",code:A.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?cE.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"base64",code:A.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?lE.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"base64url",code:A.invalid_string,message:a.message}),n.dirty()):ie.assertNever(a);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:A.invalid_string,...L.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...L.errToObj(e)})}url(e){return this._addCheck({kind:"url",...L.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...L.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...L.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...L.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...L.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...L.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...L.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...L.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...L.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...L.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...L.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...L.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,...L.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,...L.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...L.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...L.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...L.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...L.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...L.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...L.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...L.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...L.errToObj(t)})}nonempty(e){return this.min(1,L.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...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(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};tn.create=r=>new tn({checks:[],typeName:v.ZodString,coerce:r?.coerce??!1,...re(r)});Dn=class r extends se{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==R.number){let a=this._getOrReturnCtx(e);return T(a,{code:A.invalid_type,expected:R.number,received:a.parsedType}),q}let n,s=new Me;for(let a of this._def.checks)a.kind==="int"?ie.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:A.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:A.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:A.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?gE(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),T(n,{code:A.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:A.not_finite,message:a.message}),s.dirty()):ie.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,L.toString(t))}gt(e,t){return this.setLimit("min",e,!1,L.toString(t))}lte(e,t){return this.setLimit("max",e,!0,L.toString(t))}lt(e,t){return this.setLimit("max",e,!1,L.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:L.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:L.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:L.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:L.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:L.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:L.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ie.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Dn.create=r=>new Dn({checks:[],typeName:v.ZodNumber,coerce:r?.coerce||!1,...re(r)});Fn=class r extends se{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==R.bigint)return this._getInvalidInput(e);let n,s=new Me;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:A.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:A.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),T(n,{code:A.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):ie.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return T(t,{code:A.invalid_type,expected:R.bigint,received:t.parsedType}),q}gte(e,t){return this.setLimit("min",e,!0,L.toString(t))}gt(e,t){return this.setLimit("min",e,!1,L.toString(t))}lte(e,t){return this.setLimit("max",e,!0,L.toString(t))}lt(e,t){return this.setLimit("max",e,!1,L.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:L.toString(s)}]})}_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:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:L.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Fn.create=r=>new Fn({checks:[],typeName:v.ZodBigInt,coerce:r?.coerce??!1,...re(r)});Un=class extends se{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){let n=this._getOrReturnCtx(e);return T(n,{code:A.invalid_type,expected:R.boolean,received:n.parsedType}),q}return Fe(e.data)}};Un.create=r=>new Un({typeName:v.ZodBoolean,coerce:r?.coerce||!1,...re(r)});Bn=class r extends se{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){let a=this._getOrReturnCtx(e);return T(a,{code:A.invalid_type,expected:R.date,received:a.parsedType}),q}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return T(a,{code:A.invalid_date}),q}let n=new Me,s;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),T(s,{code:A.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),T(s,{code:A.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):ie.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:L.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:L.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};Bn.create=r=>new Bn({checks:[],coerce:r?.coerce||!1,typeName:v.ZodDate,...re(r)});ea=class extends se{_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return T(n,{code:A.invalid_type,expected:R.symbol,received:n.parsedType}),q}return Fe(e.data)}};ea.create=r=>new ea({typeName:v.ZodSymbol,...re(r)});Zn=class extends se{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:A.invalid_type,expected:R.undefined,received:n.parsedType}),q}return Fe(e.data)}};Zn.create=r=>new Zn({typeName:v.ZodUndefined,...re(r)});Vn=class extends se{_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return T(n,{code:A.invalid_type,expected:R.null,received:n.parsedType}),q}return Fe(e.data)}};Vn.create=r=>new Vn({typeName:v.ZodNull,...re(r)});rn=class extends se{constructor(){super(...arguments),this._any=!0}_parse(e){return Fe(e.data)}};rn.create=r=>new rn({typeName:v.ZodAny,...re(r)});kr=class extends se{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Fe(e.data)}};kr.create=r=>new kr({typeName:v.ZodUnknown,...re(r)});Ft=class extends se{_parse(e){let t=this._getOrReturnCtx(e);return T(t,{code:A.invalid_type,expected:R.never,received:t.parsedType}),q}};Ft.create=r=>new Ft({typeName:v.ZodNever,...re(r)});ta=class extends se{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:A.invalid_type,expected:R.void,received:n.parsedType}),q}return Fe(e.data)}};ta.create=r=>new ta({typeName:v.ZodVoid,...re(r)});Rr=class r extends se{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==R.array)return T(t,{code:A.invalid_type,expected:R.array,received:t.parsedType}),q;if(s.exactLength!==null){let i=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(i||o)&&(T(t,{code:i?A.too_big:A.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(T(t,{code:A.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(T(t,{code:A.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>s.type._parseAsync(new At(t,i,t.path,o)))).then(i=>Me.mergeArray(n,i));let a=[...t.data].map((i,o)=>s.type._parseSync(new At(t,i,t.path,o)));return Me.mergeArray(n,a)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:L.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:L.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:L.toString(t)}})}nonempty(e){return this.min(1,e)}};Rr.create=(r,e)=>new Rr({type:r,minLength:null,maxLength:null,exactLength:null,typeName:v.ZodArray,...re(e)});nt=class r extends se{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=ie.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==R.object){let c=this._getOrReturnCtx(e);return T(c,{code:A.invalid_type,expected:R.object,received:c.parsedType}),q}let{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof Ft&&this._def.unknownKeys==="strip"))for(let c in s.data)i.includes(c)||o.push(c);let u=[];for(let c of i){let l=a[c],d=s.data[c];u.push({key:{status:"valid",value:c},value:l._parse(new At(s,d,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Ft){let c=this._def.unknownKeys;if(c==="passthrough")for(let l of o)u.push({key:{status:"valid",value:l},value:{status:"valid",value:s.data[l]}});else if(c==="strict")o.length>0&&(T(s,{code:A.unrecognized_keys,keys:o}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let l of o){let d=s.data[l];u.push({key:{status:"valid",value:l},value:c._parse(new At(s,d,s.path,l)),alwaysSet:l in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let l of u){let d=await l.key,f=await l.value;c.push({key:d,value:f,alwaysSet:l.alwaysSet})}return c}).then(c=>Me.mergeObjectSync(n,c)):Me.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return L.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:L.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:v.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of ie.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of ie.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return Qs(this)}partial(e){let t={};for(let n of ie.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of ie.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof Et;)a=a._def.innerType;t[n]=a}return new r({...this._def,shape:()=>t})}keyof(){return Sh(ie.objectKeys(this.shape))}};nt.create=(r,e)=>new nt({shape:()=>r,unknownKeys:"strip",catchall:Ft.create(),typeName:v.ZodObject,...re(e)});nt.strictCreate=(r,e)=>new nt({shape:()=>r,unknownKeys:"strict",catchall:Ft.create(),typeName:v.ZodObject,...re(e)});nt.lazycreate=(r,e)=>new nt({shape:r,unknownKeys:"strip",catchall:Ft.create(),typeName:v.ZodObject,...re(e)});qn=class extends se{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(a){for(let o of a)if(o.result.status==="valid")return o.result;for(let o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let i=a.map(o=>new rt(o.ctx.common.issues));return T(t,{code:A.invalid_union,unionErrors:i}),q}if(t.common.async)return Promise.all(n.map(async a=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(s);{let a,i=[];for(let u of n){let c={...t,common:{...t.common,issues:[]},parent:null},l=u._parseSync({data:t.data,path:t.path,parent:c});if(l.status==="valid")return l;l.status==="dirty"&&!a&&(a={result:l,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(u=>new rt(u));return T(t,{code:A.invalid_union,unionErrors:o}),q}}get options(){return this._def.options}};qn.create=(r,e)=>new qn({options:r,typeName:v.ZodUnion,...re(e)});Sr=r=>r instanceof Hn?Sr(r.schema):r instanceof Ot?Sr(r.innerType()):r instanceof Kn?[r.value]:r instanceof Wn?r.options:r instanceof Jn?ie.objectValues(r.enum):r instanceof Xn?Sr(r._def.innerType):r instanceof Zn?[void 0]:r instanceof Vn?[null]:r instanceof Et?[void 0,...Sr(r.unwrap())]:r instanceof ir?[null,...Sr(r.unwrap())]:r instanceof Si||r instanceof Qn?Sr(r.unwrap()):r instanceof Yn?Sr(r._def.innerType):[],gu=class r extends se{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.object)return T(t,{code:A.invalid_type,expected:R.object,received:t.parsedType}),q;let n=this.discriminator,s=t.data[n],a=this.optionsMap.get(s);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(T(t,{code:A.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let a of t){let i=Sr(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of i){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,a)}}return new r({typeName:v.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...re(n)})}};Gn=class extends se{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(a,i)=>{if(mu(a)||mu(i))return q;let o=sd(a.value,i.value);return o.valid?((hu(a)||hu(i))&&t.dirty(),{status:t.value,value:o.data}):(T(n,{code:A.invalid_intersection_types}),q)};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(([a,i])=>s(a,i)):s(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=(r,e,t)=>new Gn({left:r,right:e,typeName:v.ZodIntersection,...re(t)});ar=class r extends se{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return T(n,{code:A.invalid_type,expected:R.array,received:n.parsedType}),q;if(n.data.length<this._def.items.length)return T(n,{code:A.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),q;!this._def.rest&&n.data.length>this._def.items.length&&(T(n,{code:A.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...n.data].map((i,o)=>{let u=this._def.items[o]||this._def.rest;return u?u._parse(new At(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>Me.mergeArray(t,i)):Me.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};ar.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ar({items:r,typeName:v.ZodTuple,rest:null,...re(e)})};_u=class r extends se{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.object)return T(n,{code:A.invalid_type,expected:R.object,received:n.parsedType}),q;let s=[],a=this._def.keyType,i=this._def.valueType;for(let o in n.data)s.push({key:a._parse(new At(n,o,n.path,o)),value:i._parse(new At(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?Me.mergeObjectAsync(t,s):Me.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof se?new r({keyType:e,valueType:t,typeName:v.ZodRecord,...re(n)}):new r({keyType:tn.create(),valueType:e,typeName:v.ZodRecord,...re(t)})}},ra=class extends se{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.map)return T(n,{code:A.invalid_type,expected:R.map,received:n.parsedType}),q;let s=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([o,u],c)=>({key:s._parse(new At(n,o,n.path,[c,"key"])),value:a._parse(new At(n,u,n.path,[c,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let u of i){let c=await u.key,l=await u.value;if(c.status==="aborted"||l.status==="aborted")return q;(c.status==="dirty"||l.status==="dirty")&&t.dirty(),o.set(c.value,l.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let u of i){let c=u.key,l=u.value;if(c.status==="aborted"||l.status==="aborted")return q;(c.status==="dirty"||l.status==="dirty")&&t.dirty(),o.set(c.value,l.value)}return{status:t.value,value:o}}}};ra.create=(r,e,t)=>new ra({valueType:e,keyType:r,typeName:v.ZodMap,...re(t)});na=class r extends se{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return T(n,{code:A.invalid_type,expected:R.set,received:n.parsedType}),q;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(T(n,{code:A.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(T(n,{code:A.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let a=this._def.valueType;function i(u){let c=new Set;for(let l of u){if(l.status==="aborted")return q;l.status==="dirty"&&t.dirty(),c.add(l.value)}return{status:t.value,value:c}}let o=[...n.data.values()].map((u,c)=>a._parse(new At(n,u,n.path,c)));return n.common.async?Promise.all(o).then(u=>i(u)):i(o)}min(e,t){return new r({...this._def,minSize:{value:e,message:L.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:L.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};na.create=(r,e)=>new na({valueType:r,minSize:null,maxSize:null,typeName:v.ZodSet,...re(e)});yu=class r extends se{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.function)return T(t,{code:A.invalid_type,expected:R.function,received:t.parsedType}),q;function n(o,u){return Pi({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Xs(),Pr].filter(c=>!!c),issueData:{code:A.invalid_arguments,argumentsError:u}})}function s(o,u){return Pi({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Xs(),Pr].filter(c=>!!c),issueData:{code:A.invalid_return_type,returnTypeError:u}})}let a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof nn){let o=this;return Fe(async function(...u){let c=new rt([]),l=await o._def.args.parseAsync(u,a).catch(p=>{throw c.addIssue(n(u,p)),c}),d=await Reflect.apply(i,this,l);return await o._def.returns._def.type.parseAsync(d,a).catch(p=>{throw c.addIssue(s(d,p)),c})})}else{let o=this;return Fe(function(...u){let c=o._def.args.safeParse(u,a);if(!c.success)throw new rt([n(u,c.error)]);let l=Reflect.apply(i,this,c.data),d=o._def.returns.safeParse(l,a);if(!d.success)throw new rt([s(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:ar.create(e).rest(kr.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||ar.create([]).rest(kr.create()),returns:t||kr.create(),typeName:v.ZodFunction,...re(n)})}},Hn=class extends se{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Hn.create=(r,e)=>new Hn({getter:r,typeName:v.ZodLazy,...re(e)});Kn=class extends se{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return T(t,{received:t.data,code:A.invalid_literal,expected:this._def.value}),q}return{status:"valid",value:e.data}}get value(){return this._def.value}};Kn.create=(r,e)=>new Kn({value:r,typeName:v.ZodLiteral,...re(e)});Wn=class r extends se{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return T(t,{expected:ie.joinValues(n),received:t.parsedType,code:A.invalid_type}),q}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return T(t,{received:t.data,code:A.invalid_enum_value,options:n}),q}return Fe(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};Wn.create=Sh;Jn=class extends se{_parse(e){let t=ie.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let s=ie.objectValues(t);return T(n,{expected:ie.joinValues(s),received:n.parsedType,code:A.invalid_type}),q}if(this._cache||(this._cache=new Set(ie.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=ie.objectValues(t);return T(n,{received:n.data,code:A.invalid_enum_value,options:s}),q}return Fe(e.data)}get enum(){return this._def.values}};Jn.create=(r,e)=>new Jn({values:r,typeName:v.ZodNativeEnum,...re(e)});nn=class extends se{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.promise&&t.common.async===!1)return T(t,{code:A.invalid_type,expected:R.promise,received:t.parsedType}),q;let n=t.parsedType===R.promise?t.data:Promise.resolve(t.data);return Fe(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};nn.create=(r,e)=>new nn({type:r,typeName:v.ZodPromise,...re(e)});Ot=class extends se{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===v.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:i=>{T(n,i),i.fatal?t.abort():t.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){let i=s.transform(n.data,a);if(n.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return q;let u=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return u.status==="aborted"?q:u.status==="dirty"?Ln(u.value):t.value==="dirty"?Ln(u.value):u});{if(t.value==="aborted")return q;let o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?q:o.status==="dirty"?Ln(o.value):t.value==="dirty"?Ln(o.value):o}}if(s.type==="refinement"){let i=o=>{let u=s.refinement(o,a);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?q:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?q:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!en(i))return q;let o=s.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>en(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:t.value,value:o})):q);ie.assertNever(s)}};Ot.create=(r,e,t)=>new Ot({schema:r,typeName:v.ZodEffects,effect:e,...re(t)});Ot.createWithPreprocess=(r,e,t)=>new Ot({schema:e,effect:{type:"preprocess",transform:r},typeName:v.ZodEffects,...re(t)});Et=class extends se{_parse(e){return this._getType(e)===R.undefined?Fe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Et.create=(r,e)=>new Et({innerType:r,typeName:v.ZodOptional,...re(e)});ir=class extends se{_parse(e){return this._getType(e)===R.null?Fe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ir.create=(r,e)=>new ir({innerType:r,typeName:v.ZodNullable,...re(e)});Xn=class extends se{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Xn.create=(r,e)=>new Xn({innerType:r,typeName:v.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...re(e)});Yn=class extends se{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ys(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new rt(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new rt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Yn.create=(r,e)=>new Yn({innerType:r,typeName:v.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...re(e)});sa=class extends se{_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return T(n,{code:A.invalid_type,expected:R.nan,received:n.parsedType}),q}return{status:"valid",value:e.data}}};sa.create=r=>new sa({typeName:v.ZodNaN,...re(r)});_E=Symbol("zod_brand"),Si=class extends se{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},ki=class r extends se{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?q:a.status==="dirty"?(t.dirty(),Ln(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?q:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:v.ZodPipeline})}},Qn=class extends se{_parse(e){let t=this._def.innerType._parse(e),n=s=>(en(s)&&(s.value=Object.freeze(s.value)),s);return Ys(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};Qn.create=(r,e)=>new Qn({innerType:r,typeName:v.ZodReadonly,...re(e)});yE={object:nt.lazycreate};(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(v||(v={}));bE=(r,e={message:`Input not instance of ${r.name}`})=>kh(t=>t instanceof r,e),Rh=tn.create,Ch=Dn.create,wE=sa.create,vE=Fn.create,$h=Un.create,xE=Bn.create,EE=ea.create,AE=Zn.create,OE=Vn.create,IE=rn.create,TE=kr.create,PE=Ft.create,SE=ta.create,kE=Rr.create,RE=nt.create,CE=nt.strictCreate,$E=qn.create,NE=gu.create,jE=Gn.create,ME=ar.create,zE=_u.create,LE=ra.create,DE=na.create,FE=yu.create,UE=Hn.create,BE=Kn.create,ZE=Wn.create,VE=Jn.create,qE=nn.create,GE=Ot.create,HE=Et.create,KE=ir.create,WE=Ot.createWithPreprocess,JE=ki.create,XE=()=>Rh().optional(),YE=()=>Ch().optional(),QE=()=>$h().optional(),eA={string:r=>tn.create({...r,coerce:!0}),number:r=>Dn.create({...r,coerce:!0}),boolean:r=>Un.create({...r,coerce:!0}),bigint:r=>Fn.create({...r,coerce:!0}),date:r=>Bn.create({...r,coerce:!0})},tA=q});var ft={};du(ft,{BRAND:()=>_E,DIRTY:()=>Ln,EMPTY_PATH:()=>W0,INVALID:()=>q,NEVER:()=>tA,OK:()=>Fe,ParseStatus:()=>Me,Schema:()=>se,ZodAny:()=>rn,ZodArray:()=>Rr,ZodBigInt:()=>Fn,ZodBoolean:()=>Un,ZodBranded:()=>Si,ZodCatch:()=>Yn,ZodDate:()=>Bn,ZodDefault:()=>Xn,ZodDiscriminatedUnion:()=>gu,ZodEffects:()=>Ot,ZodEnum:()=>Wn,ZodError:()=>rt,ZodFirstPartyTypeKind:()=>v,ZodFunction:()=>yu,ZodIntersection:()=>Gn,ZodIssueCode:()=>A,ZodLazy:()=>Hn,ZodLiteral:()=>Kn,ZodMap:()=>ra,ZodNaN:()=>sa,ZodNativeEnum:()=>Jn,ZodNever:()=>Ft,ZodNull:()=>Vn,ZodNullable:()=>ir,ZodNumber:()=>Dn,ZodObject:()=>nt,ZodOptional:()=>Et,ZodParsedType:()=>R,ZodPipeline:()=>ki,ZodPromise:()=>nn,ZodReadonly:()=>Qn,ZodRecord:()=>_u,ZodSchema:()=>se,ZodSet:()=>na,ZodString:()=>tn,ZodSymbol:()=>ea,ZodTransformer:()=>Ot,ZodTuple:()=>ar,ZodType:()=>se,ZodUndefined:()=>Zn,ZodUnion:()=>qn,ZodUnknown:()=>kr,ZodVoid:()=>ta,addIssueToContext:()=>T,any:()=>IE,array:()=>kE,bigint:()=>vE,boolean:()=>$h,coerce:()=>eA,custom:()=>kh,date:()=>xE,datetimeRegex:()=>Ph,defaultErrorMap:()=>Pr,discriminatedUnion:()=>NE,effect:()=>GE,enum:()=>ZE,function:()=>FE,getErrorMap:()=>Xs,getParsedType:()=>sr,instanceof:()=>bE,intersection:()=>jE,isAborted:()=>mu,isAsync:()=>Ys,isDirty:()=>hu,isValid:()=>en,late:()=>yE,lazy:()=>UE,literal:()=>BE,makeIssue:()=>Pi,map:()=>LE,nan:()=>wE,nativeEnum:()=>VE,never:()=>PE,null:()=>OE,nullable:()=>KE,number:()=>Ch,object:()=>RE,objectUtil:()=>ed,oboolean:()=>QE,onumber:()=>YE,optional:()=>HE,ostring:()=>XE,pipeline:()=>JE,preprocess:()=>WE,promise:()=>qE,quotelessJson:()=>G0,record:()=>zE,set:()=>DE,setErrorMap:()=>K0,strictObject:()=>CE,string:()=>Rh,symbol:()=>EE,transformer:()=>GE,tuple:()=>ME,undefined:()=>AE,union:()=>$E,unknown:()=>TE,util:()=>ie,void:()=>SE});var bu=_(()=>{"use strict";fu();rd();xh();Ti();Nh();pu()});var wu=_(()=>{"use strict";bu();bu()});var Mh=D((SC,jh)=>{"use strict";function It(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.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))}jh.exports=It;It.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};It.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};It.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},t),this._options.unref&&this._timer.unref(),!0};It.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};It.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};It.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};It.prototype.start=It.prototype.try;It.prototype.errors=function(){return this._errors};It.prototype.attempts=function(){return this._attempts};It.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,n=0;n<this._errors.length;n++){var s=this._errors[n],a=s.message,i=(r[a]||0)+1;r[a]=i,i>=t&&(e=s,t=i)}return e}});var zh=D(es=>{"use strict";var rA=Mh();es.operation=function(r){var e=es.timeouts(r);return new rA(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};es.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],s=0;s<e.retries;s++)n.push(this.createTimeout(s,e));return r&&r.forever&&!n.length&&n.push(this.createTimeout(s,e)),n.sort(function(a,i){return a-i}),n};es.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return n=Math.min(n,e.maxTimeout),n};es.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var n in r)typeof r[n]=="function"&&t.push(n)}for(var s=0;s<t.length;s++){var a=t[s],i=r[a];r[a]=function(u){var c=es.operation(e),l=Array.prototype.slice.call(arguments,1),d=l.pop();l.push(function(f){c.retry(f)||(f&&(arguments[0]=c.mainError()),d.apply(this,arguments))}),c.attempt(function(){u.apply(r,l)})}.bind(r,i),r[a].options=e}}});var Dh=D((RC,Lh)=>{"use strict";Lh.exports=zh()});var Eu=D((CC,xu)=>{"use strict";var nA=Dh(),sA=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],vu=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},aA=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r},iA=r=>sA.includes(r),Fh=(r,e)=>new Promise((t,n)=>{e={onFailedAttempt:()=>{},retries:10,...e};let s=nA.operation(e);s.attempt(async a=>{try{t(await r(a))}catch(i){if(!(i instanceof Error)){n(new TypeError(`Non-error was thrown: "${i}". You should only throw errors.`));return}if(i instanceof vu)s.stop(),n(i.originalError);else if(i instanceof TypeError&&!iA(i.message))s.stop(),n(i);else{aA(i,a,e);try{await e.onFailedAttempt(i)}catch(o){n(o);return}s.retry(i)||n(s.mainError())}}})});xu.exports=Fh;xu.exports.default=Fh;xu.exports.AbortError=vu});var Uh,Bh=_(()=>{"use strict";Uh=/^(?:[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 oA(r){return typeof r=="string"&&Uh.test(r)}var sn,ad=_(()=>{"use strict";Bh();sn=oA});function uA(r){if(!sn(r))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(r.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(r.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(r.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(r.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(r.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var Zh,Vh=_(()=>{"use strict";ad();Zh=uA});function Au(r,e=0){return(ze[r[e+0]]+ze[r[e+1]]+ze[r[e+2]]+ze[r[e+3]]+"-"+ze[r[e+4]]+ze[r[e+5]]+"-"+ze[r[e+6]]+ze[r[e+7]]+"-"+ze[r[e+8]]+ze[r[e+9]]+"-"+ze[r[e+10]]+ze[r[e+11]]+ze[r[e+12]]+ze[r[e+13]]+ze[r[e+14]]+ze[r[e+15]]).toLowerCase()}var ze,id=_(()=>{"use strict";ze=[];for(let r=0;r<256;++r)ze.push((r+256).toString(16).slice(1))});import cA from"node:crypto";function od(){return Ou>Iu.length-16&&(cA.randomFillSync(Iu),Ou=0),Iu.slice(Ou,Ou+=16)}var Iu,Ou,qh=_(()=>{"use strict";Iu=new Uint8Array(256),Ou=Iu.length});function lA(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}function ud(r,e,t){function n(s,a,i,o){var u;if(typeof s=="string"&&(s=lA(s)),typeof a=="string"&&(a=Zh(a)),((u=a)===null||u===void 0?void 0:u.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+s.length);if(c.set(a),c.set(s,a.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){o=o||0;for(let l=0;l<16;++l)i[o+l]=c[l];return i}return Au(c)}try{n.name=r}catch{}return n.DNS=dA,n.URL=pA,n}var dA,pA,Gh=_(()=>{"use strict";id();Vh();dA="6ba7b810-9dad-11d1-80b4-00c04fd430c8",pA="6ba7b811-9dad-11d1-80b4-00c04fd430c8"});import fA from"node:crypto";var cd,Hh=_(()=>{"use strict";cd={randomUUID:fA.randomUUID}});function mA(r,e,t){if(cd.randomUUID&&!e&&!r)return cd.randomUUID();r=r||{};let n=r.random||(r.rng||od)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){t=t||0;for(let s=0;s<16;++s)e[t+s]=n[s];return e}return Au(n)}var _e,Kh=_(()=>{"use strict";Hh();qh();id();_e=mA});import hA from"node:crypto";function gA(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),hA.createHash("sha1").update(r).digest()}var Wh,Jh=_(()=>{"use strict";Wh=gA});var _A,Tu,Xh=_(()=>{"use strict";Gh();Jh();_A=ud("v5",80,Wh),Tu=_A});var ts=_(()=>{"use strict";Kh();Xh();ad()});function Yh(r=!1){let e=bA.getInstance().getStore();if(!r&&e===void 0)throw new Error(`Could not get the current run tree.
2
+
3
+ Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function Pu(r){return typeof r=="function"&&"langsmith:traceable"in r}var pd,dd,yA,fd,bA,s$,Qh=_(()=>{"use strict";pd=class{getStore(){}run(e,t){return t()}},dd=Symbol.for("ls:tracing_async_local_storage"),yA=new pd,fd=class{getInstance(){return globalThis[dd]??yA}initializeGlobalInstance(e){globalThis[dd]===void 0&&(globalThis[dd]=e)}},bA=new fd;s$=Symbol.for("langsmith:traceable:root")});var md=_(()=>{"use strict";Qh()});function ku(r,e){return wA.call(r,e)}function Ru(r){if(Array.isArray(r)){let t=new Array(r.length);for(let n=0;n<t.length;n++)t[n]=""+n;return t}if(Object.keys)return Object.keys(r);let e=[];for(let t in r)ku(r,t)&&e.push(t);return e}function Ue(r){switch(typeof r){case"object":return JSON.parse(JSON.stringify(r));case"undefined":return null;default:return r}}function Cu(r){let e=0,t=r.length,n;for(;e<t;){if(n=r.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function or(r){return r.indexOf("/")===-1&&r.indexOf("~")===-1?r:r.replace(/~/g,"~0").replace(/\//g,"~1")}function Ri(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}function Su(r){if(r===void 0)return!0;if(r){if(Array.isArray(r)){for(let t=0,n=r.length;t<n;t++)if(Su(r[t]))return!0}else if(typeof r=="object"){let t=Ru(r),n=t.length;for(var e=0;e<n;e++)if(Su(r[t[e]]))return!0}}return!1}function eg(r,e){let t=[r];for(let n in e){let s=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof s<"u"&&t.push(`${n}: ${s}`)}return t.join(`
4
+ `)}var wA,rs,Ci=_(()=>{"use strict";wA=Object.prototype.hasOwnProperty;rs=class extends Error{constructor(e,t,n,s,a){super(eg(e,{name:t,index:n,operation:s,tree:a})),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.setPrototypeOf(this,new.target.prototype),this.message=eg(e,{name:t,index:n,operation:s,tree:a})}}});var hd={};du(hd,{JsonPatchError:()=>ye,_areEquals:()=>$i,applyOperation:()=>ns,applyPatch:()=>an,applyReducer:()=>EA,deepClone:()=>vA,getValueByPointer:()=>$u,validate:()=>tg,validator:()=>Nu});function $u(r,e){if(e=="")return r;var t={op:"_get",path:e};return ns(r,t),t.value}function ns(r,e,t=!1,n=!0,s=!0,a=0){if(t&&(typeof t=="function"?t(e,0,r,e.path):Nu(e,0)),e.path===""){let i={newDocument:r};if(e.op==="add")return i.newDocument=e.value,i;if(e.op==="replace")return i.newDocument=e.value,i.removed=r,i;if(e.op==="move"||e.op==="copy")return i.newDocument=$u(r,e.from),e.op==="move"&&(i.removed=r),i;if(e.op==="test"){if(i.test=$i(r,e.value),i.test===!1)throw new ye("Test operation failed","TEST_OPERATION_FAILED",a,e,r);return i.newDocument=r,i}else{if(e.op==="remove")return i.removed=r,i.newDocument=null,i;if(e.op==="_get")return e.value=r,i;if(t)throw new ye("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",a,e,r);return i}}else{n||(r=Ue(r));let o=(e.path||"").split("/"),u=r,c=1,l=o.length,d,f,p;for(typeof t=="function"?p=t:p=Nu;;){if(f=o[c],f&&f.indexOf("~")!=-1&&(f=Ri(f)),s&&(f=="__proto__"||f=="prototype"&&c>0&&o[c-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(t&&d===void 0&&(u[f]===void 0?d=o.slice(0,c).join("/"):c==l-1&&(d=e.path),d!==void 0&&p(e,0,r,d)),c++,Array.isArray(u)){if(f==="-")f=u.length;else{if(t&&!Cu(f))throw new ye("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",a,e,r);Cu(f)&&(f=~~f)}if(c>=l){if(t&&e.op==="add"&&f>u.length)throw new ye("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",a,e,r);let m=xA[e.op].call(e,u,f,r);if(m.test===!1)throw new ye("Test operation failed","TEST_OPERATION_FAILED",a,e,r);return m}}else if(c>=l){let m=aa[e.op].call(e,u,f,r);if(m.test===!1)throw new ye("Test operation failed","TEST_OPERATION_FAILED",a,e,r);return m}if(u=u[f],t&&c<l&&(!u||typeof u!="object"))throw new ye("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",a,e,r)}}}function an(r,e,t,n=!0,s=!0){if(t&&!Array.isArray(e))throw new ye("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(r=Ue(r));let a=new Array(e.length);for(let i=0,o=e.length;i<o;i++)a[i]=ns(r,e[i],t,!0,s,i),r=a[i].newDocument;return a.newDocument=r,a}function EA(r,e,t){let n=ns(r,e);if(n.test===!1)throw new ye("Test operation failed","TEST_OPERATION_FAILED",t,e,r);return n.newDocument}function Nu(r,e,t,n){if(typeof r!="object"||r===null||Array.isArray(r))throw new ye("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,r,t);if(aa[r.op]){if(typeof r.path!="string")throw new ye("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,r,t);if(r.path.indexOf("/")!==0&&r.path.length>0)throw new ye('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,r,t);if((r.op==="move"||r.op==="copy")&&typeof r.from!="string")throw new ye("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,r,t);if((r.op==="add"||r.op==="replace"||r.op==="test")&&r.value===void 0)throw new ye("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,r,t);if((r.op==="add"||r.op==="replace"||r.op==="test")&&Su(r.value))throw new ye("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,r,t);if(t){if(r.op=="add"){var s=r.path.split("/").length,a=n.split("/").length;if(s!==a+1&&s!==a)throw new ye("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,r,t)}else if(r.op==="replace"||r.op==="remove"||r.op==="_get"){if(r.path!==n)throw new ye("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,r,t)}else if(r.op==="move"||r.op==="copy"){var i={op:"_get",path:r.from,value:void 0},o=tg([i],t);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new ye("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,r,t)}}}else throw new ye("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,r,t)}function tg(r,e,t){try{if(!Array.isArray(r))throw new ye("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)an(Ue(e),Ue(r),t||!0);else{t=t||Nu;for(var n=0;n<r.length;n++)t(r[n],n,e,void 0)}}catch(s){if(s instanceof ye)return s;throw s}}function $i(r,e){if(r===e)return!0;if(r&&e&&typeof r=="object"&&typeof e=="object"){var t=Array.isArray(r),n=Array.isArray(e),s,a,i;if(t&&n){if(a=r.length,a!=e.length)return!1;for(s=a;s--!==0;)if(!$i(r[s],e[s]))return!1;return!0}if(t!=n)return!1;var o=Object.keys(r);if(a=o.length,a!==Object.keys(e).length)return!1;for(s=a;s--!==0;)if(!e.hasOwnProperty(o[s]))return!1;for(s=a;s--!==0;)if(i=o[s],!$i(r[i],e[i]))return!1;return!0}return r!==r&&e!==e}var ye,vA,aa,xA,ju=_(()=>{"use strict";Ci();ye=rs,vA=Ue,aa={add:function(r,e,t){return r[e]=this.value,{newDocument:t}},remove:function(r,e,t){var n=r[e];return delete r[e],{newDocument:t,removed:n}},replace:function(r,e,t){var n=r[e];return r[e]=this.value,{newDocument:t,removed:n}},move:function(r,e,t){let n=$u(t,this.path);n&&(n=Ue(n));let s=ns(t,{op:"remove",path:this.from}).removed;return ns(t,{op:"add",path:this.path,value:s}),{newDocument:t,removed:n}},copy:function(r,e,t){let n=$u(t,this.from);return ns(t,{op:"add",path:this.path,value:Ue(n)}),{newDocument:t}},test:function(r,e,t){return{newDocument:t,test:$i(r[e],this.value)}},_get:function(r,e,t){return this.value=r[e],{newDocument:t}}},xA={add:function(r,e,t){return Cu(e)?r.splice(e,0,this.value):r[e]=this.value,{newDocument:t,index:e}},remove:function(r,e,t){var n=r.splice(e,1);return{newDocument:t,removed:n[0]}},replace:function(r,e,t){var n=r[e];return r[e]=this.value,{newDocument:t,removed:n}},move:aa.move,copy:aa.copy,test:aa.test,_get:aa._get}});function rg(r,e,t,n,s){if(e!==r){typeof e.toJSON=="function"&&(e=e.toJSON());for(var a=Ru(e),i=Ru(r),o=!1,u=!1,c=i.length-1;c>=0;c--){var l=i[c],d=r[l];if(ku(e,l)&&!(e[l]===void 0&&d!==void 0&&Array.isArray(e)===!1)){var f=e[l];typeof d=="object"&&d!=null&&typeof f=="object"&&f!=null&&Array.isArray(d)===Array.isArray(f)?rg(d,f,t,n+"/"+or(l),s):d!==f&&(o=!0,s&&t.push({op:"test",path:n+"/"+or(l),value:Ue(d)}),t.push({op:"replace",path:n+"/"+or(l),value:Ue(f)}))}else Array.isArray(r)===Array.isArray(e)?(s&&t.push({op:"test",path:n+"/"+or(l),value:Ue(d)}),t.push({op:"remove",path:n+"/"+or(l)}),u=!0):(s&&t.push({op:"test",path:n,value:r}),t.push({op:"replace",path:n,value:e}),o=!0)}if(!(!u&&a.length==i.length))for(var c=0;c<a.length;c++){var l=a[c];!ku(r,l)&&e[l]!==void 0&&t.push({op:"add",path:n+"/"+or(l),value:Ue(e[l])})}}}function Mu(r,e,t=!1){var n=[];return rg(r,e,n,"",t),n}var ng=_(()=>{"use strict";Ci();ju();});var m$,gd=_(()=>{"use strict";ju();ng();Ci();ju();Ci();m$={...hd,JsonPatchError:rs,deepClone:Ue,escapePathComponent:or,unescapePathComponent:Ri}});var sg,ag,_d,ig,yd,bd,wd,og,ug,cg,lg,dg,pg,fg,mg,hg,gg,_g,yg,bg,wg,vg,xg,Eg,Ag,Og,Ig,Tg,Pg,Sg,vd,kg,Rg,Cg=_(()=>{"use strict";sg="gen_ai.operation.name",ag="gen_ai.system",_d="gen_ai.request.model",ig="gen_ai.response.model",yd="gen_ai.usage.input_tokens",bd="gen_ai.usage.output_tokens",wd="gen_ai.usage.total_tokens",og="gen_ai.request.max_tokens",ug="gen_ai.request.temperature",cg="gen_ai.request.top_p",lg="gen_ai.request.frequency_penalty",dg="gen_ai.request.presence_penalty",pg="gen_ai.response.finish_reasons",fg="gen_ai.prompt",mg="gen_ai.completion",hg="gen_ai.request.extra_query",gg="gen_ai.request.extra_body",_g="gen_ai.serialized.name",yg="gen_ai.serialized.signature",bg="gen_ai.serialized.doc",wg="gen_ai.response.id",vg="gen_ai.response.service_tier",xg="gen_ai.response.system_fingerprint",Eg="gen_ai.usage.input_token_details",Ag="gen_ai.usage.output_token_details",Og="langsmith.trace.session_id",Ig="langsmith.trace.session_name",Tg="langsmith.span.kind",Pg="langsmith.trace.name",Sg="langsmith.metadata",vd="langsmith.span.tags",kg="langsmith.request.streaming",Rg="langsmith.request.headers"});var OA,$g,Ng,jg,xd=_(()=>{"use strict";Cr();OA=(...r)=>fetch(...r),$g=Symbol.for("ls:fetch_implementation"),Ng=()=>{let r=globalThis[$g];return r?typeof r=="function"&&"Headers"in r&&"Request"in r&&"Response"in r:!1},jg=r=>async(...e)=>{if(r||Oe("DEBUG")==="true"){let[n,s]=e;console.log(`\u2192 ${s?.method||"GET"} ${n}`)}let t=await(globalThis[$g]??OA)(...e);return(r||Oe("DEBUG")==="true")&&console.log(`\u2190 ${t.status} ${t.statusText} ${t.url}`),t}});var Ni,Ed=_(()=>{"use strict";Cr();Ni=()=>Oe("PROJECT")??mt("LANGCHAIN_SESSION")??"default"});var zu,Lu=_(()=>{"use strict";Ad();Od();xd();Ed();zu="0.3.74"});function Du(){if(Id===void 0){let r=Pd(),e=RA();Id={library:"langsmith",runtime:r,sdk:"langsmith-js",sdk_version:zu,...e}}return Id}function Sd(){let r=kA(),e={},t=["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(let[n,s]of Object.entries(r))typeof s=="string"&&!t.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?e.revision_id=s:e[n]=s);return e}function kA(){let r={};try{if(typeof process<"u"&&process.env)for(let[e,t]of Object.entries(process.env))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&t!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof t=="string"?r[e]=t.slice(0,2)+"*".repeat(t.length-4)+t.slice(-2):r[e]=t)}catch{}return r}function mt(r){try{return typeof process<"u"?process.env?.[r]:void 0}catch{return}}function Oe(r){return mt(`LANGSMITH_${r}`)||mt(`LANGCHAIN_${r}`)}function RA(){if(Td!==void 0)return Td;let r=["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(let t of r){let n=mt(t);n!==void 0&&(e[t]=n)}return Td=e,e}function Fu(){return mt("OTEL_ENABLED")==="true"||Oe("OTEL_ENABLED")==="true"}var ur,IA,TA,PA,Mg,SA,Pd,Id,Td,Cr=_(()=>{"use strict";Lu();IA=()=>typeof window<"u"&&typeof window.document<"u",TA=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",PA=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Mg=()=>typeof Deno<"u",SA=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Mg(),Pd=()=>ur||(typeof Bun<"u"?ur="bun":IA()?ur="browser":SA()?ur="node":TA()?ur="webworker":PA()?ur="jsdom":Mg()?ur="deno":ur="other",ur)});function Uu(){return Md.getTraceInstance()}function Lg(){return Md.getContextInstance()}function Dg(){return Md.getDefaultOTLPTracerComponents()}var Cd,$d,Nd,kd,Rd,zg,CA,$A,jd,Md,zd=_(()=>{"use strict";Cr();Cd=class{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){!this.hasWarned&&Fu()&&(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(t.length===1&&typeof t[0]=="function"?n=t[0]:t.length===2&&typeof t[1]=="function"?n=t[1]:t.length===3&&typeof t[2]=="function"&&(n=t[2]),typeof n=="function")return n()}},$d=class{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new Cd})}getTracer(e,t){return this.mockTracer}getActiveSpan(){}setSpan(e,t){return e}getSpan(e){}setSpanContext(e,t){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},Nd=class{active(){return{}}with(e,t){return t()}},kd=Symbol.for("ls:otel_trace"),Rd=Symbol.for("ls:otel_context"),zg=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),CA=new $d,$A=new Nd,jd=class{getTraceInstance(){return globalThis[kd]??CA}getContextInstance(){return globalThis[Rd]??$A}initializeGlobalInstances(e){globalThis[kd]===void 0&&(globalThis[kd]=e.trace),globalThis[Rd]===void 0&&(globalThis[Rd]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[zg]=e}getDefaultOTLPTracerComponents(){return globalThis[zg]??void 0}},Md=new jd});function jA(r){return NA[r]||r}var NA,Bu,Fg=_(()=>{"use strict";Cg();zd();NA={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};Bu=class{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,t){for(let n of e)try{if(!n.run)continue;if(n.operation==="post"){let s=this.createSpanForRun(n,n.run,t.get(n.id));s&&!n.run.end_time&&this.spans.set(n.id,s)}else this.updateSpanForRun(n,n.run)}catch(s){console.error(`Error processing operation ${n.id}:`,s)}}createSpanForRun(e,t,n){let s=n&&Uu().getSpan(n);if(s)try{return this.finishSpanSetup(s,t,e)}catch(a){console.error(`Failed to create span for run ${e.id}:`,a);return}}finishSpanSetup(e,t,n){return this.setSpanAttributes(e,t,n),t.error?(e.setStatus({code:2}),e.recordException(new Error(t.error))):e.setStatus({code:1}),t.end_time&&e.end(new Date(t.end_time)),e}updateSpanForRun(e,t){try{let n=this.spans.get(e.id);if(!n){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(n,t,e),t.error?(n.setStatus({code:2}),n.recordException(new Error(t.error))):n.setStatus({code:1});let s=t.end_time;s&&(n.end(new Date(s)),this.spans.delete(e.id))}catch(n){console.error(`Failed to update span for run ${e.id}:`,n)}}extractModelName(e){if(e.extra?.metadata){let t=e.extra.metadata;if(t.ls_model_name)return t.ls_model_name;if(t.invocation_params){let n=t.invocation_params;if(n.model)return n.model;if(n.model_name)return n.model_name}}}setSpanAttributes(e,t,n){if("run_type"in t&&t.run_type){e.setAttribute(Tg,t.run_type);let o=jA(t.run_type||"chain");e.setAttribute(sg,o)}"name"in t&&t.name&&e.setAttribute(Pg,t.name),"session_id"in t&&t.session_id&&e.setAttribute(Og,t.session_id),"session_name"in t&&t.session_name&&e.setAttribute(Ig,t.session_name),this.setGenAiSystem(e,t);let s=this.extractModelName(t);s&&e.setAttribute(_d,s),"prompt_tokens"in t&&typeof t.prompt_tokens=="number"&&e.setAttribute(yd,t.prompt_tokens),"completion_tokens"in t&&typeof t.completion_tokens=="number"&&e.setAttribute(bd,t.completion_tokens),"total_tokens"in t&&typeof t.total_tokens=="number"&&e.setAttribute(wd,t.total_tokens),this.setInvocationParameters(e,t);let a=t.extra?.metadata||{};for(let[o,u]of Object.entries(a))u!=null&&e.setAttribute(`${Sg}.${o}`,String(u));let i=t.tags;if(i&&Array.isArray(i)?e.setAttribute(vd,i.join(", ")):i&&e.setAttribute(vd,String(i)),"serialized"in t&&typeof t.serialized=="object"){let o=t.serialized;o.name&&e.setAttribute(_g,String(o.name)),o.signature&&e.setAttribute(yg,String(o.signature)),o.doc&&e.setAttribute(bg,String(o.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,t){let n="langchain",s=this.extractModelName(t);if(s){let a=s.toLowerCase();a.includes("anthropic")||a.startsWith("claude")?n="anthropic":a.includes("bedrock")?n="aws.bedrock":a.includes("azure")&&a.includes("openai")?n="az.ai.openai":a.includes("azure")&&a.includes("inference")?n="az.ai.inference":a.includes("cohere")?n="cohere":a.includes("deepseek")?n="deepseek":a.includes("gemini")?n="gemini":a.includes("groq")?n="groq":a.includes("watson")||a.includes("ibm")?n="ibm.watsonx.ai":a.includes("mistral")?n="mistral_ai":a.includes("gpt")||a.includes("openai")?n="openai":a.includes("perplexity")||a.includes("sonar")?n="perplexity":a.includes("vertex")?n="vertex_ai":(a.includes("xai")||a.includes("grok"))&&(n="xai")}e.setAttribute(ag,n)}setInvocationParameters(e,t){if(!t.extra?.metadata?.invocation_params)return;let n=t.extra.metadata.invocation_params;n.max_tokens!==void 0&&e.setAttribute(og,n.max_tokens),n.temperature!==void 0&&e.setAttribute(ug,n.temperature),n.top_p!==void 0&&e.setAttribute(cg,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(lg,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(dg,n.presence_penalty)}setIOAttributes(e,t){if(t.run.inputs)try{let n=t.run.inputs;typeof n=="object"&&n!==null&&(n.model&&Array.isArray(n.messages)&&e.setAttribute(_d,n.model),n.stream!==void 0&&e.setAttribute(kg,n.stream),n.extra_headers&&e.setAttribute(Rg,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(hg,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(gg,JSON.stringify(n.extra_body))),e.setAttribute(fg,JSON.stringify(n))}catch(n){console.debug(`Failed to process inputs for run ${t.id}`,n)}if(t.run.outputs)try{let n=t.run.outputs,s=this.getUnifiedRunTokens(n);if(s&&(e.setAttribute(yd,s[0]),e.setAttribute(bd,s[1]),e.setAttribute(wd,s[0]+s[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(ig,String(n.model)),n.id&&e.setAttribute(wg,n.id),n.choices&&Array.isArray(n.choices)){let a=n.choices.map(i=>i.finish_reason).filter(i=>i).map(String);a.length>0&&e.setAttribute(pg,a.join(", "))}if(n.service_tier&&e.setAttribute(vg,n.service_tier),n.system_fingerprint&&e.setAttribute(xg,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){let a=n.usage_metadata;a.input_token_details&&e.setAttribute(Eg,JSON.stringify(a.input_token_details)),a.output_token_details&&e.setAttribute(Ag,JSON.stringify(a.output_token_details))}}e.setAttribute(mg,JSON.stringify(n))}catch(n){console.debug(`Failed to process outputs for run ${t.id}`,n)}}getUnifiedRunTokens(e){if(!e)return null;let t=this.extractUnifiedRunTokens(e.usage_metadata);if(t)return t;let n=Object.keys(e);for(let i of n){let o=e[i];if(!(!o||typeof o!="object")&&(t=this.extractUnifiedRunTokens(o.usage_metadata),t||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(t=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),t)))return t}let s=e.generations||[];if(!Array.isArray(s))return null;let a=Array.isArray(s[0])?s.flat():s;for(let i of a)if(typeof i=="object"&&i.message&&typeof i.message=="object"&&i.message.kwargs&&typeof i.message.kwargs=="object"&&(t=this.extractUnifiedRunTokens(i.message.kwargs.usage_metadata),t))return t;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 Bg=D((j$,Ld)=>{"use strict";var MA=Object.prototype.hasOwnProperty,Ge="~";function ji(){}Object.create&&(ji.prototype=Object.create(null),new ji().__proto__||(Ge=!1));function zA(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Ug(r,e,t,n,s){if(typeof t!="function")throw new TypeError("The listener must be a function");var a=new zA(t,n||r,s),i=Ge?Ge+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],a]:r._events[i].push(a):(r._events[i]=a,r._eventsCount++),r}function Zu(r,e){--r._eventsCount===0?r._events=new ji:delete r._events[e]}function Be(){this._events=new ji,this._eventsCount=0}Be.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)MA.call(t,n)&&e.push(Ge?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Be.prototype.listeners=function(e){var t=Ge?Ge+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,a=n.length,i=new Array(a);s<a;s++)i[s]=n[s].fn;return i};Be.prototype.listenerCount=function(e){var t=Ge?Ge+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Be.prototype.emit=function(e,t,n,s,a,i){var o=Ge?Ge+e:e;if(!this._events[o])return!1;var u=this._events[o],c=arguments.length,l,d;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),c){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,s),!0;case 5:return u.fn.call(u.context,t,n,s,a),!0;case 6:return u.fn.call(u.context,t,n,s,a,i),!0}for(d=1,l=new Array(c-1);d<c;d++)l[d-1]=arguments[d];u.fn.apply(u.context,l)}else{var f=u.length,p;for(d=0;d<f;d++)switch(u[d].once&&this.removeListener(e,u[d].fn,void 0,!0),c){case 1:u[d].fn.call(u[d].context);break;case 2:u[d].fn.call(u[d].context,t);break;case 3:u[d].fn.call(u[d].context,t,n);break;case 4:u[d].fn.call(u[d].context,t,n,s);break;default:if(!l)for(p=1,l=new Array(c-1);p<c;p++)l[p-1]=arguments[p];u[d].fn.apply(u[d].context,l)}}return!0};Be.prototype.on=function(e,t,n){return Ug(this,e,t,n,!1)};Be.prototype.once=function(e,t,n){return Ug(this,e,t,n,!0)};Be.prototype.removeListener=function(e,t,n,s){var a=Ge?Ge+e:e;if(!this._events[a])return this;if(!t)return Zu(this,a),this;var i=this._events[a];if(i.fn)i.fn===t&&(!s||i.once)&&(!n||i.context===n)&&Zu(this,a);else{for(var o=0,u=[],c=i.length;o<c;o++)(i[o].fn!==t||s&&!i[o].once||n&&i[o].context!==n)&&u.push(i[o]);u.length?this._events[a]=u.length===1?u[0]:u:Zu(this,a)}return this};Be.prototype.removeAllListeners=function(e){var t;return e?(t=Ge?Ge+e:e,this._events[t]&&Zu(this,t)):(this._events=new ji,this._eventsCount=0),this};Be.prototype.off=Be.prototype.removeListener;Be.prototype.addListener=Be.prototype.on;Be.prefixed=Ge;Be.EventEmitter=Be;typeof Ld<"u"&&(Ld.exports=Be)});var Vg=D((M$,Zg)=>{"use strict";Zg.exports=(r,e)=>(e=e||(()=>{}),r.then(t=>new Promise(n=>{n(e())}).then(()=>t),t=>new Promise(n=>{n(e())}).then(()=>{throw t})))});var Gg=D((z$,qu)=>{"use strict";var LA=Vg(),Vu=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},qg=(r,e,t)=>new Promise((n,s)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){n(r);return}let a=setTimeout(()=>{if(typeof t=="function"){try{n(t())}catch(u){s(u)}return}let i=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,o=t instanceof Error?t:new Vu(i);typeof r.cancel=="function"&&r.cancel(),s(o)},e);LA(r.then(n,s),()=>{clearTimeout(a)})});qu.exports=qg;qu.exports.default=qg;qu.exports.TimeoutError=Vu});var Hg=D(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});function DA(r,e,t){let n=0,s=r.length;for(;s>0;){let a=s/2|0,i=n+a;t(r[i],e)<=0?(n=++i,s-=a+1):s=a}return n}Dd.default=DA});var Kg=D(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var FA=Hg(),Fd=class{constructor(){this._queue=[]}enqueue(e,t){t=Object.assign({priority:0},t);let n={priority:t.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority){this._queue.push(n);return}let s=FA.default(this._queue,n,(a,i)=>i.priority-a.priority);this._queue.splice(s,0,n)}dequeue(){let e=this._queue.shift();return e?.run}filter(e){return this._queue.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this._queue.length}};Ud.default=Fd});var Hu=D(Zd=>{"use strict";Object.defineProperty(Zd,"__esModule",{value:!0});var UA=Bg(),Wg=Gg(),BA=Kg(),Gu=()=>{},ZA=new Wg.TimeoutError,Bd=class extends UA{constructor(e){var t,n,s,a;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=Gu,this._resolveIdle=Gu,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:BA.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(a=(s=e.interval)===null||s===void 0?void 0:s.toString())!==null&&a!==void 0?a:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.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=Gu,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=Gu,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let t=this._intervalEnd-e;if(t<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},t)),!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){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let t=this._queue.dequeue();return t?(this.emit("active"),t(),e&&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(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={}){return new Promise((n,s)=>{let a=async()=>{this._pendingCount++,this._intervalCount++;try{let i=this._timeout===void 0&&t.timeout===void 0?e():Wg.default(Promise.resolve(e()),t.timeout===void 0?this._timeout:t.timeout,()=>{(t.throwOnTimeout===void 0?this._throwOnTimeout:t.throwOnTimeout)&&s(ZA)});n(await i)}catch(i){s(i)}this._next()};this._queue.enqueue(a,t),this._tryToStartAnother(),this.emit("add")})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};Zd.default=Bd});var Jg,Ku,VA,Mi,Xg=_(()=>{"use strict";Jg=Dt(Eu(),1),Ku=Dt(Hu(),1),VA=[429,500,502,503,504],Mi=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 Ku.default?this.queue=new Ku.default.default({concurrency:this.maxConcurrency}):this.queue=new Ku.default({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){let n=this.onFailedResponseHook;return this.queue.add(()=>(0,Jg.default)(()=>e(...t).catch(s=>{throw s instanceof Error?s:new Error(s)}),{async onFailedAttempt(s){if(s.message.startsWith("Cancel")||s.message.startsWith("TimeoutError")||s.name==="TimeoutError"||s.message.startsWith("AbortError")||s?.code==="ECONNABORTED")throw s;let a=s?.response;if(n&&await n(a))return;let i=a?.status??s?.status;if(i&&!VA.includes(+i))throw s},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){return e.signal?Promise.race([this.call(t,...n),new Promise((s,a)=>{e.signal?.addEventListener("abort",()=>{a(new Error("AbortError"))})})]):this.call(t,...n)}}});function Vd(r){return typeof r?._getType=="function"}function qd(r){let e={type:r._getType(),data:{content:r.content}};return r?.additional_kwargs&&Object.keys(r.additional_kwargs).length>0&&(e.data.additional_kwargs={...r.additional_kwargs}),e}var Yg=_(()=>{"use strict"});function ee(r,e){if(!qA.test(r)){let t=e!==void 0?`Invalid UUID for ${e}: ${r}`:`Invalid UUID: ${r}`;throw new Error(t)}return r}var qA,Qg=_(()=>{"use strict";qA=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i});function zi(r){e_[r]||(console.warn(r),e_[r]=!0)}var e_,Gd=_(()=>{"use strict";e_={}});var Li=D((q$,t_)=>{"use strict";var GA="2.0.0",HA=Number.MAX_SAFE_INTEGER||9007199254740991,KA=16,WA=250,JA=["major","premajor","minor","preminor","patch","prepatch","prerelease"];t_.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:KA,MAX_SAFE_BUILD_LENGTH:WA,MAX_SAFE_INTEGER:HA,RELEASE_TYPES:JA,SEMVER_SPEC_VERSION:GA,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Di=D((G$,r_)=>{"use strict";var XA=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};r_.exports=XA});var ia=D(($r,n_)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Hd,MAX_SAFE_BUILD_LENGTH:YA,MAX_LENGTH:QA}=Li(),eO=Di();$r=n_.exports={};var tO=$r.re=[],rO=$r.safeRe=[],C=$r.src=[],$=$r.t={},nO=0,Kd="[a-zA-Z0-9-]",sO=[["\\s",1],["\\d",QA],[Kd,YA]],aO=r=>{for(let[e,t]of sO)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},te=(r,e,t)=>{let n=aO(e),s=nO++;eO(r,s,e),$[r]=s,C[s]=e,tO[s]=new RegExp(e,t?"g":void 0),rO[s]=new RegExp(n,t?"g":void 0)};te("NUMERICIDENTIFIER","0|[1-9]\\d*");te("NUMERICIDENTIFIERLOOSE","\\d+");te("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Kd}*`);te("MAINVERSION",`(${C[$.NUMERICIDENTIFIER]})\\.(${C[$.NUMERICIDENTIFIER]})\\.(${C[$.NUMERICIDENTIFIER]})`);te("MAINVERSIONLOOSE",`(${C[$.NUMERICIDENTIFIERLOOSE]})\\.(${C[$.NUMERICIDENTIFIERLOOSE]})\\.(${C[$.NUMERICIDENTIFIERLOOSE]})`);te("PRERELEASEIDENTIFIER",`(?:${C[$.NUMERICIDENTIFIER]}|${C[$.NONNUMERICIDENTIFIER]})`);te("PRERELEASEIDENTIFIERLOOSE",`(?:${C[$.NUMERICIDENTIFIERLOOSE]}|${C[$.NONNUMERICIDENTIFIER]})`);te("PRERELEASE",`(?:-(${C[$.PRERELEASEIDENTIFIER]}(?:\\.${C[$.PRERELEASEIDENTIFIER]})*))`);te("PRERELEASELOOSE",`(?:-?(${C[$.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${C[$.PRERELEASEIDENTIFIERLOOSE]})*))`);te("BUILDIDENTIFIER",`${Kd}+`);te("BUILD",`(?:\\+(${C[$.BUILDIDENTIFIER]}(?:\\.${C[$.BUILDIDENTIFIER]})*))`);te("FULLPLAIN",`v?${C[$.MAINVERSION]}${C[$.PRERELEASE]}?${C[$.BUILD]}?`);te("FULL",`^${C[$.FULLPLAIN]}$`);te("LOOSEPLAIN",`[v=\\s]*${C[$.MAINVERSIONLOOSE]}${C[$.PRERELEASELOOSE]}?${C[$.BUILD]}?`);te("LOOSE",`^${C[$.LOOSEPLAIN]}$`);te("GTLT","((?:<|>)?=?)");te("XRANGEIDENTIFIERLOOSE",`${C[$.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);te("XRANGEIDENTIFIER",`${C[$.NUMERICIDENTIFIER]}|x|X|\\*`);te("XRANGEPLAIN",`[v=\\s]*(${C[$.XRANGEIDENTIFIER]})(?:\\.(${C[$.XRANGEIDENTIFIER]})(?:\\.(${C[$.XRANGEIDENTIFIER]})(?:${C[$.PRERELEASE]})?${C[$.BUILD]}?)?)?`);te("XRANGEPLAINLOOSE",`[v=\\s]*(${C[$.XRANGEIDENTIFIERLOOSE]})(?:\\.(${C[$.XRANGEIDENTIFIERLOOSE]})(?:\\.(${C[$.XRANGEIDENTIFIERLOOSE]})(?:${C[$.PRERELEASELOOSE]})?${C[$.BUILD]}?)?)?`);te("XRANGE",`^${C[$.GTLT]}\\s*${C[$.XRANGEPLAIN]}$`);te("XRANGELOOSE",`^${C[$.GTLT]}\\s*${C[$.XRANGEPLAINLOOSE]}$`);te("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Hd}})(?:\\.(\\d{1,${Hd}}))?(?:\\.(\\d{1,${Hd}}))?`);te("COERCE",`${C[$.COERCEPLAIN]}(?:$|[^\\d])`);te("COERCEFULL",C[$.COERCEPLAIN]+`(?:${C[$.PRERELEASE]})?(?:${C[$.BUILD]})?(?:$|[^\\d])`);te("COERCERTL",C[$.COERCE],!0);te("COERCERTLFULL",C[$.COERCEFULL],!0);te("LONETILDE","(?:~>?)");te("TILDETRIM",`(\\s*)${C[$.LONETILDE]}\\s+`,!0);$r.tildeTrimReplace="$1~";te("TILDE",`^${C[$.LONETILDE]}${C[$.XRANGEPLAIN]}$`);te("TILDELOOSE",`^${C[$.LONETILDE]}${C[$.XRANGEPLAINLOOSE]}$`);te("LONECARET","(?:\\^)");te("CARETTRIM",`(\\s*)${C[$.LONECARET]}\\s+`,!0);$r.caretTrimReplace="$1^";te("CARET",`^${C[$.LONECARET]}${C[$.XRANGEPLAIN]}$`);te("CARETLOOSE",`^${C[$.LONECARET]}${C[$.XRANGEPLAINLOOSE]}$`);te("COMPARATORLOOSE",`^${C[$.GTLT]}\\s*(${C[$.LOOSEPLAIN]})$|^$`);te("COMPARATOR",`^${C[$.GTLT]}\\s*(${C[$.FULLPLAIN]})$|^$`);te("COMPARATORTRIM",`(\\s*)${C[$.GTLT]}\\s*(${C[$.LOOSEPLAIN]}|${C[$.XRANGEPLAIN]})`,!0);$r.comparatorTrimReplace="$1$2$3";te("HYPHENRANGE",`^\\s*(${C[$.XRANGEPLAIN]})\\s+-\\s+(${C[$.XRANGEPLAIN]})\\s*$`);te("HYPHENRANGELOOSE",`^\\s*(${C[$.XRANGEPLAINLOOSE]})\\s+-\\s+(${C[$.XRANGEPLAINLOOSE]})\\s*$`);te("STAR","(<|>)?=?\\s*\\*");te("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");te("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Wu=D((H$,s_)=>{"use strict";var iO=Object.freeze({loose:!0}),oO=Object.freeze({}),uO=r=>r?typeof r!="object"?iO:r:oO;s_.exports=uO});var Wd=D((K$,o_)=>{"use strict";var a_=/^[0-9]+$/,i_=(r,e)=>{let t=a_.test(r),n=a_.test(e);return t&&n&&(r=+r,e=+e),r===e?0:t&&!n?-1:n&&!t?1:r<e?-1:1},cO=(r,e)=>i_(e,r);o_.exports={compareIdentifiers:i_,rcompareIdentifiers:cO}});var Ze=D((W$,d_)=>{"use strict";var Ju=Di(),{MAX_LENGTH:u_,MAX_SAFE_INTEGER:Xu}=Li(),{safeRe:c_,t:l_}=ia(),lO=Wu(),{compareIdentifiers:oa}=Wd(),Jd=class r{constructor(e,t){if(t=lO(t),e instanceof r){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>u_)throw new TypeError(`version is longer than ${u_} characters`);Ju("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?c_[l_.LOOSE]:c_[l_.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>Xu||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Xu||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Xu||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let a=+s;if(a>=0&&a<Xu)return a}return s}):this.prerelease=[],this.build=n[5]?n[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(e){if(Ju("SemVer.compare",this.version,this.options,e),!(e instanceof r)){if(typeof e=="string"&&e===this.version)return 0;e=new r(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof r||(e=new r(e,this.options)),oa(this.major,e.major)||oa(this.minor,e.minor)||oa(this.patch,e.patch)}comparePre(e){if(e instanceof r||(e=new r(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let n=this.prerelease[t],s=e.prerelease[t];if(Ju("prerelease compare",t,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return oa(n,s)}while(++t)}compareBuild(e){e instanceof r||(e=new r(e,this.options));let t=0;do{let n=this.build[t],s=e.build[t];if(Ju("build compare",t,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return oa(n,s)}while(++t)}inc(e,t,n){switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,n),this.inc("pre",t,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,n),this.inc("pre",t,n);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":{let s=Number(n)?1:0;if(!t&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(this.prerelease.length===0)this.prerelease=[s];else{let a=this.prerelease.length;for(;--a>=0;)typeof this.prerelease[a]=="number"&&(this.prerelease[a]++,a=-2);if(a===-1){if(t===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(t){let a=[t,s];n===!1&&(a=[t]),oa(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=a):this.prerelease=a}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};d_.exports=Jd});var as=D((J$,f_)=>{"use strict";var p_=Ze(),dO=(r,e,t=!1)=>{if(r instanceof p_)return r;try{return new p_(r,e)}catch(n){if(!t)return null;throw n}};f_.exports=dO});var h_=D((X$,m_)=>{"use strict";var pO=as(),fO=(r,e)=>{let t=pO(r,e);return t?t.version:null};m_.exports=fO});var __=D((Y$,g_)=>{"use strict";var mO=as(),hO=(r,e)=>{let t=mO(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};g_.exports=hO});var w_=D((Q$,b_)=>{"use strict";var y_=Ze(),gO=(r,e,t,n,s)=>{typeof t=="string"&&(s=n,n=t,t=void 0);try{return new y_(r instanceof y_?r.version:r,t).inc(e,n,s).version}catch{return null}};b_.exports=gO});var E_=D((eN,x_)=>{"use strict";var v_=as(),_O=(r,e)=>{let t=v_(r,null,!0),n=v_(e,null,!0),s=t.compare(n);if(s===0)return null;let a=s>0,i=a?t:n,o=a?n:t,u=!!i.prerelease.length;if(!!o.prerelease.length&&!u)return!o.patch&&!o.minor?"major":i.patch?"patch":i.minor?"minor":"major";let l=u?"pre":"";return t.major!==n.major?l+"major":t.minor!==n.minor?l+"minor":t.patch!==n.patch?l+"patch":"prerelease"};x_.exports=_O});var O_=D((tN,A_)=>{"use strict";var yO=Ze(),bO=(r,e)=>new yO(r,e).major;A_.exports=bO});var T_=D((rN,I_)=>{"use strict";var wO=Ze(),vO=(r,e)=>new wO(r,e).minor;I_.exports=vO});var S_=D((nN,P_)=>{"use strict";var xO=Ze(),EO=(r,e)=>new xO(r,e).patch;P_.exports=EO});var R_=D((sN,k_)=>{"use strict";var AO=as(),OO=(r,e)=>{let t=AO(r,e);return t&&t.prerelease.length?t.prerelease:null};k_.exports=OO});var Tt=D((aN,$_)=>{"use strict";var C_=Ze(),IO=(r,e,t)=>new C_(r,t).compare(new C_(e,t));$_.exports=IO});var j_=D((iN,N_)=>{"use strict";var TO=Tt(),PO=(r,e,t)=>TO(e,r,t);N_.exports=PO});var z_=D((oN,M_)=>{"use strict";var SO=Tt(),kO=(r,e)=>SO(r,e,!0);M_.exports=kO});var Yu=D((uN,D_)=>{"use strict";var L_=Ze(),RO=(r,e,t)=>{let n=new L_(r,t),s=new L_(e,t);return n.compare(s)||n.compareBuild(s)};D_.exports=RO});var U_=D((cN,F_)=>{"use strict";var CO=Yu(),$O=(r,e)=>r.sort((t,n)=>CO(t,n,e));F_.exports=$O});var Z_=D((lN,B_)=>{"use strict";var NO=Yu(),jO=(r,e)=>r.sort((t,n)=>NO(n,t,e));B_.exports=jO});var Fi=D((dN,V_)=>{"use strict";var MO=Tt(),zO=(r,e,t)=>MO(r,e,t)>0;V_.exports=zO});var Qu=D((pN,q_)=>{"use strict";var LO=Tt(),DO=(r,e,t)=>LO(r,e,t)<0;q_.exports=DO});var Xd=D((fN,G_)=>{"use strict";var FO=Tt(),UO=(r,e,t)=>FO(r,e,t)===0;G_.exports=UO});var Yd=D((mN,H_)=>{"use strict";var BO=Tt(),ZO=(r,e,t)=>BO(r,e,t)!==0;H_.exports=ZO});var ec=D((hN,K_)=>{"use strict";var VO=Tt(),qO=(r,e,t)=>VO(r,e,t)>=0;K_.exports=qO});var tc=D((gN,W_)=>{"use strict";var GO=Tt(),HO=(r,e,t)=>GO(r,e,t)<=0;W_.exports=HO});var Qd=D((_N,J_)=>{"use strict";var KO=Xd(),WO=Yd(),JO=Fi(),XO=ec(),YO=Qu(),QO=tc(),eI=(r,e,t,n)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return KO(r,t,n);case"!=":return WO(r,t,n);case">":return JO(r,t,n);case">=":return XO(r,t,n);case"<":return YO(r,t,n);case"<=":return QO(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};J_.exports=eI});var Y_=D((yN,X_)=>{"use strict";var tI=Ze(),rI=as(),{safeRe:rc,t:nc}=ia(),nI=(r,e)=>{if(r instanceof tI)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?rc[nc.COERCEFULL]:rc[nc.COERCE]);else{let u=e.includePrerelease?rc[nc.COERCERTLFULL]:rc[nc.COERCERTL],c;for(;(c=u.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||c.index+c[0].length!==t.index+t[0].length)&&(t=c),u.lastIndex=c.index+c[1].length+c[2].length;u.lastIndex=-1}if(t===null)return null;let n=t[2],s=t[3]||"0",a=t[4]||"0",i=e.includePrerelease&&t[5]?`-${t[5]}`:"",o=e.includePrerelease&&t[6]?`+${t[6]}`:"";return rI(`${n}.${s}.${a}${i}${o}`,e)};X_.exports=nI});var ey=D((bN,Q_)=>{"use strict";var ep=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let s=this.map.keys().next().value;this.delete(s)}this.map.set(e,t)}return this}};Q_.exports=ep});var Pt=D((wN,sy)=>{"use strict";var sI=/\s+/g,tp=class r{constructor(e,t){if(t=iI(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof rp)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(sI," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(s=>!ry(s[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let s of this.set)if(s.length===1&&fI(s[0])){this.set=[s];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");let t=this.set[e];for(let n=0;n<t.length;n++)n>0&&(this.formatted+=" "),this.formatted+=t[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let n=((this.options.includePrerelease&&dI)|(this.options.loose&&pI))+":"+e,s=ty.get(n);if(s)return s;let a=this.options.loose,i=a?st[He.HYPHENRANGELOOSE]:st[He.HYPHENRANGE];e=e.replace(i,EI(this.options.includePrerelease)),me("hyphen replace",e),e=e.replace(st[He.COMPARATORTRIM],uI),me("comparator trim",e),e=e.replace(st[He.TILDETRIM],cI),me("tilde trim",e),e=e.replace(st[He.CARETTRIM],lI),me("caret trim",e);let o=e.split(" ").map(d=>mI(d,this.options)).join(" ").split(/\s+/).map(d=>xI(d,this.options));a&&(o=o.filter(d=>(me("loose invalid filter",d,this.options),!!d.match(st[He.COMPARATORLOOSE])))),me("range list",o);let u=new Map,c=o.map(d=>new rp(d,this.options));for(let d of c){if(ry(d))return[d];u.set(d.value,d)}u.size>1&&u.has("")&&u.delete("");let l=[...u.values()];return ty.set(n,l),l}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>ny(n,t)&&e.set.some(s=>ny(s,t)&&n.every(a=>s.every(i=>a.intersects(i,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new oI(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(AI(this.set[t],e,this.options))return!0;return!1}};sy.exports=tp;var aI=ey(),ty=new aI,iI=Wu(),rp=Ui(),me=Di(),oI=Ze(),{safeRe:st,t:He,comparatorTrimReplace:uI,tildeTrimReplace:cI,caretTrimReplace:lI}=ia(),{FLAG_INCLUDE_PRERELEASE:dI,FLAG_LOOSE:pI}=Li(),ry=r=>r.value==="<0.0.0-0",fI=r=>r.value==="",ny=(r,e)=>{let t=!0,n=r.slice(),s=n.pop();for(;t&&n.length;)t=n.every(a=>s.intersects(a,e)),s=n.pop();return t},mI=(r,e)=>(me("comp",r,e),r=_I(r,e),me("caret",r),r=hI(r,e),me("tildes",r),r=bI(r,e),me("xrange",r),r=vI(r,e),me("stars",r),r),Ke=r=>!r||r.toLowerCase()==="x"||r==="*",hI=(r,e)=>r.trim().split(/\s+/).map(t=>gI(t,e)).join(" "),gI=(r,e)=>{let t=e.loose?st[He.TILDELOOSE]:st[He.TILDE];return r.replace(t,(n,s,a,i,o)=>{me("tilde",r,n,s,a,i,o);let u;return Ke(s)?u="":Ke(a)?u=`>=${s}.0.0 <${+s+1}.0.0-0`:Ke(i)?u=`>=${s}.${a}.0 <${s}.${+a+1}.0-0`:o?(me("replaceTilde pr",o),u=`>=${s}.${a}.${i}-${o} <${s}.${+a+1}.0-0`):u=`>=${s}.${a}.${i} <${s}.${+a+1}.0-0`,me("tilde return",u),u})},_I=(r,e)=>r.trim().split(/\s+/).map(t=>yI(t,e)).join(" "),yI=(r,e)=>{me("caret",r,e);let t=e.loose?st[He.CARETLOOSE]:st[He.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(s,a,i,o,u)=>{me("caret",r,s,a,i,o,u);let c;return Ke(a)?c="":Ke(i)?c=`>=${a}.0.0${n} <${+a+1}.0.0-0`:Ke(o)?a==="0"?c=`>=${a}.${i}.0${n} <${a}.${+i+1}.0-0`:c=`>=${a}.${i}.0${n} <${+a+1}.0.0-0`:u?(me("replaceCaret pr",u),a==="0"?i==="0"?c=`>=${a}.${i}.${o}-${u} <${a}.${i}.${+o+1}-0`:c=`>=${a}.${i}.${o}-${u} <${a}.${+i+1}.0-0`:c=`>=${a}.${i}.${o}-${u} <${+a+1}.0.0-0`):(me("no pr"),a==="0"?i==="0"?c=`>=${a}.${i}.${o}${n} <${a}.${i}.${+o+1}-0`:c=`>=${a}.${i}.${o}${n} <${a}.${+i+1}.0-0`:c=`>=${a}.${i}.${o} <${+a+1}.0.0-0`),me("caret return",c),c})},bI=(r,e)=>(me("replaceXRanges",r,e),r.split(/\s+/).map(t=>wI(t,e)).join(" ")),wI=(r,e)=>{r=r.trim();let t=e.loose?st[He.XRANGELOOSE]:st[He.XRANGE];return r.replace(t,(n,s,a,i,o,u)=>{me("xRange",r,n,s,a,i,o,u);let c=Ke(a),l=c||Ke(i),d=l||Ke(o),f=d;return s==="="&&f&&(s=""),u=e.includePrerelease?"-0":"",c?s===">"||s==="<"?n="<0.0.0-0":n="*":s&&f?(l&&(i=0),o=0,s===">"?(s=">=",l?(a=+a+1,i=0,o=0):(i=+i+1,o=0)):s==="<="&&(s="<",l?a=+a+1:i=+i+1),s==="<"&&(u="-0"),n=`${s+a}.${i}.${o}${u}`):l?n=`>=${a}.0.0${u} <${+a+1}.0.0-0`:d&&(n=`>=${a}.${i}.0${u} <${a}.${+i+1}.0-0`),me("xRange return",n),n})},vI=(r,e)=>(me("replaceStars",r,e),r.trim().replace(st[He.STAR],"")),xI=(r,e)=>(me("replaceGTE0",r,e),r.trim().replace(st[e.includePrerelease?He.GTE0PRE:He.GTE0],"")),EI=r=>(e,t,n,s,a,i,o,u,c,l,d,f)=>(Ke(n)?t="":Ke(s)?t=`>=${n}.0.0${r?"-0":""}`:Ke(a)?t=`>=${n}.${s}.0${r?"-0":""}`:i?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Ke(c)?u="":Ke(l)?u=`<${+c+1}.0.0-0`:Ke(d)?u=`<${c}.${+l+1}.0-0`:f?u=`<=${c}.${l}.${d}-${f}`:r?u=`<${c}.${l}.${+d+1}-0`:u=`<=${u}`,`${t} ${u}`.trim()),AI=(r,e,t)=>{for(let n=0;n<r.length;n++)if(!r[n].test(e))return!1;if(e.prerelease.length&&!t.includePrerelease){for(let n=0;n<r.length;n++)if(me(r[n].semver),r[n].semver!==rp.ANY&&r[n].semver.prerelease.length>0){let s=r[n].semver;if(s.major===e.major&&s.minor===e.minor&&s.patch===e.patch)return!0}return!1}return!0}});var Ui=D((vN,ly)=>{"use strict";var Bi=Symbol("SemVer ANY"),ap=class r{static get ANY(){return Bi}constructor(e,t){if(t=ay(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),sp("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Bi?this.value="":this.value=this.operator+this.semver.version,sp("comp",this)}parse(e){let t=this.options.loose?iy[oy.COMPARATORLOOSE]:iy[oy.COMPARATOR],n=e.match(t);if(!n)throw new TypeError(`Invalid comparator: ${e}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new uy(n[2],this.options.loose):this.semver=Bi}toString(){return this.value}test(e){if(sp("Comparator.test",e,this.options.loose),this.semver===Bi||e===Bi)return!0;if(typeof e=="string")try{e=new uy(e,this.options)}catch{return!1}return np(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new cy(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new cy(this.value,t).test(e.semver):(t=ay(t),t.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||np(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||np(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};ly.exports=ap;var ay=Wu(),{safeRe:iy,t:oy}=ia(),np=Qd(),sp=Di(),uy=Ze(),cy=Pt()});var Zi=D((xN,dy)=>{"use strict";var OI=Pt(),II=(r,e,t)=>{try{e=new OI(e,t)}catch{return!1}return e.test(r)};dy.exports=II});var fy=D((EN,py)=>{"use strict";var TI=Pt(),PI=(r,e)=>new TI(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));py.exports=PI});var hy=D((AN,my)=>{"use strict";var SI=Ze(),kI=Pt(),RI=(r,e,t)=>{let n=null,s=null,a=null;try{a=new kI(e,t)}catch{return null}return r.forEach(i=>{a.test(i)&&(!n||s.compare(i)===-1)&&(n=i,s=new SI(n,t))}),n};my.exports=RI});var _y=D((ON,gy)=>{"use strict";var CI=Ze(),$I=Pt(),NI=(r,e,t)=>{let n=null,s=null,a=null;try{a=new $I(e,t)}catch{return null}return r.forEach(i=>{a.test(i)&&(!n||s.compare(i)===1)&&(n=i,s=new CI(n,t))}),n};gy.exports=NI});var wy=D((IN,by)=>{"use strict";var ip=Ze(),jI=Pt(),yy=Fi(),MI=(r,e)=>{r=new jI(r,e);let t=new ip("0.0.0");if(r.test(t)||(t=new ip("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n<r.set.length;++n){let s=r.set[n],a=null;s.forEach(i=>{let o=new ip(i.semver.version);switch(i.operator){case">":o.prerelease.length===0?o.patch++:o.prerelease.push(0),o.raw=o.format();case"":case">=":(!a||yy(o,a))&&(a=o);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),a&&(!t||yy(t,a))&&(t=a)}return t&&r.test(t)?t:null};by.exports=MI});var xy=D((TN,vy)=>{"use strict";var zI=Pt(),LI=(r,e)=>{try{return new zI(r,e).range||"*"}catch{return null}};vy.exports=LI});var sc=D((PN,Iy)=>{"use strict";var DI=Ze(),Oy=Ui(),{ANY:FI}=Oy,UI=Pt(),BI=Zi(),Ey=Fi(),Ay=Qu(),ZI=tc(),VI=ec(),qI=(r,e,t,n)=>{r=new DI(r,n),e=new UI(e,n);let s,a,i,o,u;switch(t){case">":s=Ey,a=ZI,i=Ay,o=">",u=">=";break;case"<":s=Ay,a=VI,i=Ey,o="<",u="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(BI(r,e,n))return!1;for(let c=0;c<e.set.length;++c){let l=e.set[c],d=null,f=null;if(l.forEach(p=>{p.semver===FI&&(p=new Oy(">=0.0.0")),d=d||p,f=f||p,s(p.semver,d.semver,n)?d=p:i(p.semver,f.semver,n)&&(f=p)}),d.operator===o||d.operator===u||(!f.operator||f.operator===o)&&a(r,f.semver))return!1;if(f.operator===u&&i(r,f.semver))return!1}return!0};Iy.exports=qI});var Py=D((SN,Ty)=>{"use strict";var GI=sc(),HI=(r,e,t)=>GI(r,e,">",t);Ty.exports=HI});var ky=D((kN,Sy)=>{"use strict";var KI=sc(),WI=(r,e,t)=>KI(r,e,"<",t);Sy.exports=WI});var $y=D((RN,Cy)=>{"use strict";var Ry=Pt(),JI=(r,e,t)=>(r=new Ry(r,t),e=new Ry(e,t),r.intersects(e,t));Cy.exports=JI});var jy=D((CN,Ny)=>{"use strict";var XI=Zi(),YI=Tt();Ny.exports=(r,e,t)=>{let n=[],s=null,a=null,i=r.sort((l,d)=>YI(l,d,t));for(let l of i)XI(l,e,t)?(a=l,s||(s=l)):(a&&n.push([s,a]),a=null,s=null);s&&n.push([s,null]);let o=[];for(let[l,d]of n)l===d?o.push(l):!d&&l===i[0]?o.push("*"):d?l===i[0]?o.push(`<=${d}`):o.push(`${l} - ${d}`):o.push(`>=${l}`);let u=o.join(" || "),c=typeof e.raw=="string"?e.raw:String(e);return u.length<c.length?u:e}});var Uy=D(($N,Fy)=>{"use strict";var My=Pt(),up=Ui(),{ANY:op}=up,Vi=Zi(),cp=Tt(),QI=(r,e,t={})=>{if(r===e)return!0;r=new My(r,t),e=new My(e,t);let n=!1;e:for(let s of r.set){for(let a of e.set){let i=tT(s,a,t);if(n=n||i!==null,i)continue e}if(n)return!1}return!0},eT=[new up(">=0.0.0-0")],zy=[new up(">=0.0.0")],tT=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===op){if(e.length===1&&e[0].semver===op)return!0;t.includePrerelease?r=eT:r=zy}if(e.length===1&&e[0].semver===op){if(t.includePrerelease)return!0;e=zy}let n=new Set,s,a;for(let p of r)p.operator===">"||p.operator===">="?s=Ly(s,p,t):p.operator==="<"||p.operator==="<="?a=Dy(a,p,t):n.add(p.semver);if(n.size>1)return null;let i;if(s&&a){if(i=cp(s.semver,a.semver,t),i>0)return null;if(i===0&&(s.operator!==">="||a.operator!=="<="))return null}for(let p of n){if(s&&!Vi(p,String(s),t)||a&&!Vi(p,String(a),t))return null;for(let m of e)if(!Vi(p,String(m),t))return!1;return!0}let o,u,c,l,d=a&&!t.includePrerelease&&a.semver.prerelease.length?a.semver:!1,f=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1;d&&d.prerelease.length===1&&a.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let p of e){if(l=l||p.operator===">"||p.operator===">=",c=c||p.operator==="<"||p.operator==="<=",s){if(f&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===f.major&&p.semver.minor===f.minor&&p.semver.patch===f.patch&&(f=!1),p.operator===">"||p.operator===">="){if(o=Ly(s,p,t),o===p&&o!==s)return!1}else if(s.operator===">="&&!Vi(s.semver,String(p),t))return!1}if(a){if(d&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===d.major&&p.semver.minor===d.minor&&p.semver.patch===d.patch&&(d=!1),p.operator==="<"||p.operator==="<="){if(u=Dy(a,p,t),u===p&&u!==a)return!1}else if(a.operator==="<="&&!Vi(a.semver,String(p),t))return!1}if(!p.operator&&(a||s)&&i!==0)return!1}return!(s&&c&&!a&&i!==0||a&&l&&!s&&i!==0||f||d)},Ly=(r,e,t)=>{if(!r)return e;let n=cp(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},Dy=(r,e,t)=>{if(!r)return e;let n=cp(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};Fy.exports=QI});var qy=D((NN,Vy)=>{"use strict";var lp=ia(),By=Li(),rT=Ze(),Zy=Wd(),nT=as(),sT=h_(),aT=__(),iT=w_(),oT=E_(),uT=O_(),cT=T_(),lT=S_(),dT=R_(),pT=Tt(),fT=j_(),mT=z_(),hT=Yu(),gT=U_(),_T=Z_(),yT=Fi(),bT=Qu(),wT=Xd(),vT=Yd(),xT=ec(),ET=tc(),AT=Qd(),OT=Y_(),IT=Ui(),TT=Pt(),PT=Zi(),ST=fy(),kT=hy(),RT=_y(),CT=wy(),$T=xy(),NT=sc(),jT=Py(),MT=ky(),zT=$y(),LT=jy(),DT=Uy();Vy.exports={parse:nT,valid:sT,clean:aT,inc:iT,diff:oT,major:uT,minor:cT,patch:lT,prerelease:dT,compare:pT,rcompare:fT,compareLoose:mT,compareBuild:hT,sort:gT,rsort:_T,gt:yT,lt:bT,eq:wT,neq:vT,gte:xT,lte:ET,cmp:AT,coerce:OT,Comparator:IT,Range:TT,satisfies:PT,toComparators:ST,maxSatisfying:kT,minSatisfying:RT,minVersion:CT,validRange:$T,outside:NT,gtr:jT,ltr:MT,intersects:zT,simplifyRange:LT,subset:DT,SemVer:rT,re:lp.re,src:lp.src,tokens:lp.t,SEMVER_SPEC_VERSION:By.SEMVER_SPEC_VERSION,RELEASE_TYPES:By.RELEASE_TYPES,compareIdentifiers:Zy.compareIdentifiers,rcompareIdentifiers:Zy.rcompareIdentifiers}});function Nr(r){if(!r||r.split("/").length>2||r.startsWith("/")||r.endsWith("/")||r.split(":").length>2)throw new Error(`Invalid identifier format: ${r}`);let[e,t]=r.split(":"),n=t||"latest";if(e.includes("/")){let[s,a]=e.split("/",2);if(!s||!a)throw new Error(`Invalid identifier format: ${r}`);return[s,a,n]}else{if(!e)throw new Error(`Invalid identifier format: ${r}`);return["-",e,n]}}var FT,Gy=_(()=>{"use strict";FT=Dt(qy(),1)});async function F(r,e,t){let n;if(r.ok){t&&(n=await r.text());return}if(r.status===403)try{(await r.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{let o=new Error(`${r.status} ${r.statusText}`);throw o.status=r?.status,o}if(n===void 0)try{n=await r.text()}catch{n=""}let s=`Failed to ${e}. Received status [${r.status}]: ${r.statusText}. Message: ${n}`;if(r.status===409)throw new dp(s);let a=new Error(s);throw a.status=r.status,a}function Ky(r){return typeof r=="object"&&r!==null&&r.code===Hy}var dp,Hy,ac,pp=_(()=>{"use strict";dp=class 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}};Hy="ERR_CONFLICTING_ENDPOINTS",ac=class 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:Hy}),this.name="ConflictingEndpointsError"}}});function ZT(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function ic(r){return BT.encode(r)}function Jy(r){if(r&&typeof r=="object"&&r!==null){if(r instanceof Map)return Object.fromEntries(r);if(r instanceof Set)return Array.from(r);if(r instanceof Date)return r.toISOString();if(r instanceof RegExp)return r.toString();if(r instanceof Error)return{name:r.name,message:r.message}}else if(typeof r=="bigint")return r.toString();return r}function VT(r){return function(e,t){if(r){let n=r.call(this,e,t);if(n!==void 0)return n}return Jy(t)}}function at(r,e,t,n,s){try{let a=JSON.stringify(r,VT(t),n);return ic(a)}catch(a){if(!a.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
5
+ Context: ${e}`:""}`),ic("[Unserializable]");Oe("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
6
+ Context: ${e}`:""}`),typeof s>"u"&&(s=ZT()),mp(r,"",0,[],void 0,0,s);let i;try{ua.length===0?i=JSON.stringify(r,t,n):i=JSON.stringify(r,qT(t),n)}catch{return ic("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;oc.length!==0;){let o=oc.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return ic(i)}}function fp(r,e,t,n){var s=Object.getOwnPropertyDescriptor(n,t);s.get!==void 0?s.configurable?(Object.defineProperty(n,t,{value:r}),oc.push([n,t,e,s])):ua.push([e,t,r]):(n[t]=r,oc.push([n,t,e]))}function mp(r,e,t,n,s,a,i){a+=1;var o;if(typeof r=="object"&&r!==null){for(o=0;o<n.length;o++)if(n[o]===r){fp(UT,r,e,s);return}if(typeof i.depthLimit<"u"&&a>i.depthLimit){fp(Wy,r,e,s);return}if(typeof i.edgesLimit<"u"&&t+1>i.edgesLimit){fp(Wy,r,e,s);return}if(n.push(r),Array.isArray(r))for(o=0;o<r.length;o++)mp(r[o],o,o,n,r,a,i);else{r=Jy(r);var u=Object.keys(r);for(o=0;o<u.length;o++){var c=u[o];mp(r[c],c,o,n,r,a,i)}}n.pop()}}function qT(r){return r=typeof r<"u"?r:function(e,t){return t},function(e,t){if(ua.length>0)for(var n=0;n<ua.length;n++){var s=ua[n];if(s[1]===e&&s[0]===t){t=s[2],ua.splice(n,1);break}}return r.call(this,e,t)}}var Wy,UT,oc,ua,BT,Xy=_(()=>{"use strict";Cr();Wy="[...]",UT={result:"[Circular]"},oc=[],ua=[],BT=new TextEncoder});function Yy(r,e){let t=Du(),n=e??Sd(),s=r.extra??{},a=s.metadata;return r.extra={...s,runtime:{...t,...s?.runtime},metadata:{...n,...n.revision_id||"revision_id"in r&&r.revision_id?{revision_id:("revision_id"in r?r.revision_id:void 0)??n.revision_id}:{},...a}},r}async function KT(r){let e=[];for await(let t of r)e.push(t);return e}function uc(r){if(r!==void 0)return r.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}function Qy(r){return typeof r=="number"?Number(r.toFixed(4)):r}function tb(r){return"dataset_id"in r||"dataset_name"in r}var GT,HT,WT,hp,JT,XT,YT,eb,ss,Ad=_(()=>{"use strict";ts();Fg();zd();Xg();Yg();Cr();Lu();Qg();Gd();Gy();pp();xd();Xy();GT=r=>{let e=r?.toString()??Oe("TRACING_SAMPLING_RATE");if(e===void 0)return;let t=parseFloat(e);if(t<0||t>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${t}`);return t},HT=r=>{let t=r.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return t==="localhost"||t==="127.0.0.1"||t==="::1"};WT=async r=>{if(r?.status===429){let e=parseInt(r.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(t=>setTimeout(t,e)),!0}return!1};hp=class{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(e){let t,n=new Promise(a=>{t=a}),s=at(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:t,itemPromise:n,size:s}),this.sizeBytes+=s,n}pop({upToSizeBytes:e,upToSize:t}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");let n=[],s=0;for(;s+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<t;){let a=this.items.shift();a&&(n.push(a),s+=a.size,this.sizeBytes-=a.size)}if(n.length===0&&this.items.length>0){let a=this.items.shift();n.push(a),s+=a.size,this.sizeBytes-=a.size}return[n.map(a=>({action:a.action,item:a.payload,otelContext:a.otelContext,apiKey:a.apiKey,apiUrl:a.apiUrl})),()=>n.forEach(a=>a.itemPromiseResolve())]}},JT=24*1024*1024,XT=1e4,YT=100,eb="https://api.smith.langchain.com",ss=class r{get _fetch(){return this.fetchImplementation||jg(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 hp}),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:mt("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:mt("LANGSMITH_DEBUG")==="true"});let t=r.getDefaultClientConfig();if(this.tracingSampleRate=GT(e.tracingSamplingRate),this.apiUrl=uc(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=uc(e.apiKey??t.apiKey),this.webUrl=uc(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=uc(e.workspaceId??Oe("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new Mi({...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 Mi({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:WT,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??t.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??t.hideOutputs,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,Fu()&&(this.langSmithToOTELTranslator=new Bu),this.cachedLSEnvVarsForMetadata=Sd()}static getDefaultClientConfig(){let e=Oe("API_KEY"),t=Oe("ENDPOINT")??eb,n=Oe("HIDE_INPUTS")==="true",s=Oe("HIDE_OUTPUTS")==="true";return{apiUrl:t,apiKey:e,webUrl:void 0,hideInputs:n,hideOutputs:s}}getHostUrl(){return this.webUrl?this.webUrl:HT(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(){let e={"User-Agent":`langsmith-js/${zu}`};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){let t={...e};return t.inputs!==void 0&&(t.inputs=await this.processInputs(t.inputs)),t.outputs!==void 0&&(t.outputs=await this.processOutputs(t.outputs)),t}async _getResponse(e,t){let n=t?.toString()??"",s=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{let i=await this._fetch(s,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(i,`fetch ${e}`),i})}async _get(e,t){return(await this._getResponse(e,t)).json()}async*_getPaginated(e,t=new URLSearchParams,n){let s=Number(t.get("offset"))||0,a=Number(t.get("limit"))||100;for(;;){t.set("offset",String(s)),t.set("limit",String(a));let i=`${this.apiUrl}${e}?${t}`,o=await this.caller.call(async()=>{let c=await this._fetch(i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(c,`fetch ${e}`),c}),u=n?n(await o.json()):await o.json();if(u.length===0||(yield u,u.length<a))break;s+=u.length}}async*_getCursorPaginatedList(e,t=null,n="POST",s="runs"){let a=t?{...t}:{};for(;;){let i=JSON.stringify(a),u=await(await this.caller.call(async()=>{let 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 F(l,`fetch ${e}`),l})).json();if(!u||!u[s])break;yield u[s];let c=u.cursors;if(!c||!c.next)break;a.cursor=c.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,t=!1){if(this.tracingSampleRate===void 0)return e;if(t){let n=[];for(let s of e)this.filteredPostUuids.has(s.trace_id)?s.id===s.trace_id&&this.filteredPostUuids.delete(s.trace_id):n.push(s);return n}else{let n=[];for(let s of e){let a=s.trace_id??s.id;this.filteredPostUuids.has(a)||(s.id===a?this._shouldSample()?n.push(s):this.filteredPostUuids.add(a):n.push(s))}return n}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e.batch_ingest_config?.size_limit_bytes??JT}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e.batch_ingest_config?.size_limit??YT}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t}){let n=[];for(;this.autoBatchQueue.items.length>0;){let[s,a]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:t});if(!s.length){a();break}let i=s.reduce((c,l)=>{let d=l.apiUrl??this.apiUrl,f=l.apiKey??this.apiKey,m=l.apiKey===this.apiKey&&l.apiUrl===this.apiUrl?"default":`${d}|${f}`;return c[m]||(c[m]=[]),c[m].push(l),c},{}),o=[];for(let[c,l]of Object.entries(i)){let d=this._processBatch(l,{apiUrl:c==="default"?void 0:c.split("|")[0],apiKey:c==="default"?void 0:c.split("|")[1]});o.push(d)}let u=Promise.all(o).finally(a);n.push(u)}return Promise.all(n)}async _processBatch(e,t){if(e.length)try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{let n={runCreates:e.filter(a=>a.action==="create").map(a=>a.item),runUpdates:e.filter(a=>a.action==="update").map(a=>a.item)},s=await this._ensureServerInfo();if(s?.batch_ingest_config?.use_multipart_endpoint){let a=s?.instance_flags?.gzip_body_enabled;await this.multipartIngestRuns(n,{...t,useGzip:a})}else await this.batchIngestRuns(n,t)}}catch(n){console.error("Error exporting batch:",n)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){let t=new Map,n=[];for(let s of e)s.item.id&&s.otelContext&&(t.set(s.item.id,s.otelContext),s.action==="create"?n.push({operation:"post",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}):n.push({operation:"patch",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}));this.langSmithToOTELTranslator.exportBatch(n,t)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=Yy(e.item,this.cachedLSEnvVarsForMetadata);let t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;let n=await this._getBatchSizeLimitBytes(),s=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>s)&&this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:s}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:s})},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){let t=await(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(XT),...this.fetchOptions});return await F(n,"get server info"),n})).json();return this.debug&&console.log(`
7
+ === LangSmith Server Configuration ===
8
+ `+JSON.stringify(t,null,2)+`
9
+ `),t}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(){let e=await this._getBatchSizeLimitBytes(),t=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t})}_cloneCurrentOTELContext(){let e=Uu(),t=Lg();if(this.langSmithToOTELTranslator!==void 0){let n=e.getActiveSpan();if(n)return e.setSpan(t.active(),n)}}async createRun(e,t){if(!this._filterForSampling([e]).length)return;let n={...this.headers,"Content-Type":"application/json"},s=e.project_name;delete e.project_name;let a=await this.prepareRunCreateOrUpdateInputs({session_name:s,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&a.trace_id!==void 0&&a.dotted_order!==void 0){let u=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:a,otelContext:u,apiKey:t?.apiKey,apiUrl:t?.apiUrl}).catch(console.error);return}let i=Yy(a,this.cachedLSEnvVarsForMetadata);t?.apiKey!==void 0&&(n["x-api-key"]=t.apiKey),t?.workspaceId!==void 0&&(n["x-tenant-id"]=t.workspaceId);let o=at(i,`Creating run with id: ${i.id}`);await this.caller.call(async()=>{let u=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await F(u,"create run",!0),u})}async batchIngestRuns({runCreates:e,runUpdates:t},n){if(e===void 0&&t===void 0)return;let s=await Promise.all(e?.map(u=>this.prepareRunCreateOrUpdateInputs(u))??[]),a=await Promise.all(t?.map(u=>this.prepareRunCreateOrUpdateInputs(u))??[]);if(s.length>0&&a.length>0){let u=s.reduce((l,d)=>(d.id&&(l[d.id]=d),l),{}),c=[];for(let l of a)l.id!==void 0&&u[l.id]?u[l.id]={...u[l.id],...l}:c.push(l);s=Object.values(u),a=c}let i={post:s,patch:a};if(!i.post.length&&!i.patch.length)return;let o={post:[],patch:[]};for(let u of["post","patch"]){let c=u,l=i[c].reverse(),d=l.pop();for(;d!==void 0;)o[c].push(d),d=l.pop()}if(o.post.length>0||o.patch.length>0){let u=o.post.map(c=>c.id).concat(o.patch.map(c=>c.id)).join(",");await this._postBatchIngestRuns(at(o,`Ingesting runs with ids: ${u}`),n)}}async _postBatchIngestRuns(e,t){let n={...this.headers,"Content-Type":"application/json",Accept:"application/json"};t?.apiKey!==void 0&&(n["x-api-key"]=t.apiKey),await this.batchIngestCaller.call(async()=>{let s=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await F(s,"batch create run",!0),s})}async multipartIngestRuns({runCreates:e,runUpdates:t},n){if(e===void 0&&t===void 0)return;let s={},a=[];for(let d of e??[]){let f=await this.prepareRunCreateOrUpdateInputs(d);f.id!==void 0&&f.attachments!==void 0&&(s[f.id]=f.attachments),delete f.attachments,a.push(f)}let i=[];for(let d of t??[])i.push(await this.prepareRunCreateOrUpdateInputs(d));if(a.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(a.length>0&&i.length>0){let d=a.reduce((p,m)=>(m.id&&(p[m.id]=m),p),{}),f=[];for(let p of i)p.id!==void 0&&d[p.id]?d[p.id]={...d[p.id],...p}:f.push(p);a=Object.values(d),i=f}if(a.length===0&&i.length===0)return;let c=[],l=[];for(let[d,f]of[["post",a],["patch",i]])for(let p of f){let{inputs:m,outputs:h,events:g,extra:w,error:b,serialized:x,attachments:I,...P}=p,K={inputs:m,outputs:h,events:g,extra:w,error:b,serialized:x},V=at(P,`Serializing for multipart ingestion of run with id: ${P.id}`);l.push({name:`${d}.${P.id}`,payload:new Blob([V],{type:`application/json; length=${V.length}`})});for(let[Z,oe]of Object.entries(K)){if(oe===void 0)continue;let de=at(oe,`Serializing ${Z} for multipart ingestion of run with id: ${P.id}`);l.push({name:`${d}.${P.id}.${Z}`,payload:new Blob([de],{type:`application/json; length=${de.length}`})})}if(P.id!==void 0){let Z=s[P.id];if(Z){delete s[P.id];for(let[oe,de]of Object.entries(Z)){let fe,nr;if(Array.isArray(de)?[fe,nr]=de:(fe=de.mimeType,nr=de.data),oe.includes(".")){console.warn(`Skipping attachment '${oe}' for run ${P.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${P.id}.${oe}`,payload:new Blob([nr],{type:`${fe}; length=${nr.byteLength}`})})}}}c.push(`trace=${P.trace_id},id=${P.id}`)}await this._sendMultipartRequest(l,c.join("; "),n)}async _createNodeFetchBody(e,t){let n=[];for(let i of e)n.push(new Blob([`--${t}\r
10
+ `])),n.push(new Blob([`Content-Disposition: form-data; name="${i.name}"\r
11
+ `,`Content-Type: ${i.payload.type}\r
12
+ \r
13
+ `])),n.push(i.payload),n.push(new Blob([`\r
14
+ `]));return n.push(new Blob([`--${t}--\r
15
+ `])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,t){let n=new TextEncoder;return new ReadableStream({async start(a){let i=async o=>{typeof o=="string"?a.enqueue(n.encode(o)):a.enqueue(o)};for(let o of e){await i(`--${t}\r
16
+ `),await i(`Content-Disposition: form-data; name="${o.name}"\r
17
+ `),await i(`Content-Type: ${o.payload.type}\r
18
+ \r
19
+ `);let c=o.payload.stream().getReader();try{let l;for(;!(l=await c.read()).done;)a.enqueue(l.value)}finally{c.releaseLock()}await i(`\r
20
+ `)}await i(`--${t}--\r
21
+ `),a.close()}})}async _sendMultipartRequest(e,t,n){let s="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),a=Ng(),i=()=>this._createNodeFetchBody(e,s),o=()=>this._createMultipartStream(e,s),u=async c=>this.batchIngestCaller.call(async()=>{let l=await c(),d={...this.headers,"Content-Type":`multipart/form-data; boundary=${s}`};n?.apiKey!==void 0&&(d["x-api-key"]=n.apiKey);let f=l;n?.useGzip&&typeof l=="object"&&"pipeThrough"in l&&(f=l.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");let p=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:f,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(p,"Failed to send multipart request",!0),p});try{let c,l=!1;!a&&!this.multipartStreamingDisabled&&Pd()!=="bun"?(l=!0,c=await u(o)):c=await u(i),(!this.multipartStreamingDisabled||l)&&c.status===422&&(n?.apiUrl??this.apiUrl)!==eb&&(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 "${t}".`),this.multipartStreamingDisabled=!0,c=await u(i))}catch(c){console.warn(`${c.message.trim()}
22
+
23
+ Context: ${t}`)}}async updateRun(e,t,n){ee(e),t.inputs&&(t.inputs=await this.processInputs(t.inputs)),t.outputs&&(t.outputs=await this.processOutputs(t.outputs));let s={...t,id:e};if(!this._filterForSampling([s],!0).length)return;if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){let o=this._cloneCurrentOTELContext();if(t.end_time!==void 0&&s.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:s,otelContext:o,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:s,otelContext:o,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}let a={...this.headers,"Content-Type":"application/json"};n?.apiKey!==void 0&&(a["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(a["x-tenant-id"]=n.workspaceId);let i=at(t,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let o=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await F(o,"update run",!0),o})}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){ee(e);let n=await this._get(`/runs/${e}`);return t&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:t,projectOpts:n}){if(t!==void 0){let s;t.session_id?s=t.session_id:n?.projectName?s=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?s=n?.projectId:s=(await this.readProject({projectName:Oe("PROJECT")||"default"})).id;let a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${s}/r/${t.id}?poll=true`}else if(e!==void 0){let s=await this.readRun(e);if(!s.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${s.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){let t=await KT(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},s={};t.sort((a,i)=>(a?.dotted_order??"").localeCompare(i?.dotted_order??""));for(let a of t){if(a.parent_run_id===null||a.parent_run_id===void 0)throw new Error(`Child run ${a.id} has no parent`);a.dotted_order?.startsWith(e.dotted_order??"")&&a.id!==e.id&&(a.parent_run_id in n||(n[a.parent_run_id]=[]),n[a.parent_run_id].push(a),s[a.id]=a)}e.child_runs=n[e.id]||[];for(let a in n)a!==e.id&&(s[a].child_runs=n[a]);return e}async*listRuns(e){let{projectId:t,projectName:n,parentRunId:s,traceId:a,referenceExampleId:i,startTime:o,executionOrder:u,isRoot:c,runType:l,error:d,id:f,query:p,filter:m,traceFilter:h,treeFilter:g,limit:w,select:b,order:x}=e,I=[];if(t&&(I=Array.isArray(t)?t:[t]),n){let Z=Array.isArray(n)?n:[n],oe=await Promise.all(Z.map(de=>this.readProject({projectName:de}).then(fe=>fe.id)));I.push(...oe)}let P=["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"],K={session:I.length?I:null,run_type:l,reference_example:i,query:p,filter:m,trace_filter:h,tree_filter:g,execution_order:u,parent_run:s,start_time:o?o.toISOString():null,error:d,id:f,limit:w,trace:a,select:b||P,is_root:c,order:x};K.select.includes("child_run_ids")&&zi("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let V=0;for await(let Z of this._getCursorPaginatedList("/runs/query",K))if(w){if(V>=w)break;if(Z.length+V>w){yield*Z.slice(0,w-V);break}V+=Z.length,yield*Z}else yield*Z}async*listGroupRuns(e){let{projectId:t,projectName:n,groupBy:s,filter:a,startTime:i,endTime:o,limit:u,offset:c}=e,d={session_id:t||(await this.readProject({projectName:n})).id,group_by:s,filter:a,start_time:i?i.toISOString():null,end_time:o?o.toISOString():null,limit:Number(u)||100},f=Number(c)||0,p="/runs/group",m=`${this.apiUrl}${p}`;for(;;){let h={...d,offset:f},g=Object.fromEntries(Object.entries(h).filter(([K,V])=>V!==void 0)),w=JSON.stringify(g),x=await(await this.caller.call(async()=>{let K=await this._fetch(m,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:w});return await F(K,`Failed to fetch ${p}`),K})).json(),{groups:I,total:P}=x;if(I.length===0)break;for(let K of I)yield K;if(f+=I.length,f>=P)break}}async getRunStats({id:e,trace:t,parentRun:n,runType:s,projectNames:a,projectIds:i,referenceExampleIds:o,startTime:u,endTime:c,error:l,query:d,filter:f,traceFilter:p,treeFilter:m,isRoot:h,dataSourceType:g}){let w=i||[];a&&(w=[...i||[],...await Promise.all(a.map(V=>this.readProject({projectName:V}).then(Z=>Z.id)))]);let x=Object.fromEntries(Object.entries({id:e,trace:t,parent_run:n,run_type:s,session:w,reference_example:o,start_time:u,end_time:c,error:l,query:d,filter:f,trace_filter:p,tree_filter:m,is_root:h,data_source_type:g}).filter(([V,Z])=>Z!==void 0)),I=JSON.stringify(x);return await(await this.caller.call(async()=>{let V=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:I});return await F(V,"get run stats"),V})).json()}async shareRun(e,{shareId:t}={}){let n={run_id:e,share_token:t||_e()};ee(e);let s=JSON.stringify(n),i=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await F(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){ee(e),await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(t,"unshare run",!0),t})}async readRunSharedLink(e){ee(e);let n=await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(s,"read run shared link"),s})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){let n=new URLSearchParams({share_token:e});if(t!==void 0)for(let i of t)n.append("id",i);return ee(e),await(await this.caller.call(async()=>{let 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 F(i,"list shared runs"),i})).json()}async readDatasetSharedSchema(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id),ee(e);let s=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(a,"read dataset shared schema"),a})).json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async shareDataset(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id);let n={dataset_id:e};ee(e);let s=JSON.stringify(n),i=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await F(o,"share dataset"),o})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){ee(e),await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(t,"unshare dataset",!0),t})}async readSharedDataset(e){return ee(e),await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(s,"read shared dataset"),s})).json()}async listSharedExamples(e,t){let n={};t?.exampleIds&&(n.id=t.exampleIds);let s=new URLSearchParams;Object.entries(n).forEach(([o,u])=>{Array.isArray(u)?u.forEach(c=>s.append(o,c)):s.append(o,u)});let a=await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/public/${e}/examples?${s.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(o,"list shared examples"),o}),i=await a.json();if(!a.ok)throw"detail"in i?new Error(`Failed to list shared examples.
24
+ Status: ${a.status}
25
+ Message: ${Array.isArray(i.detail)?i.detail.join(`
26
+ `):"Unspecified error"}`):new Error(`Failed to list shared examples: ${a.status} ${a.statusText}`);return i.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:t=null,metadata:n=null,upsert:s=!1,projectExtra:a=null,referenceDatasetId:i=null}){let o=s?"?upsert=true":"",u=`${this.apiUrl}/sessions${o}`,c=a||{};n&&(c.metadata=n);let l={name:e,extra:c,description:t};i!==null&&(l.reference_dataset_id=i);let d=JSON.stringify(l);return await(await this.caller.call(async()=>{let m=await this._fetch(u,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});return await F(m,"create project"),m})).json()}async updateProject(e,{name:t=null,description:n=null,metadata:s=null,projectExtra:a=null,endTime:i=null}){let o=`${this.apiUrl}/sessions/${e}`,u=a;s&&(u={...u||{},metadata:s});let c=JSON.stringify({name:t,extra:u,description:n,end_time:i?new Date(i).toISOString():null});return await(await this.caller.call(async()=>{let f=await this._fetch(o,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await F(f,"update project"),f})).json()}async hasProject({projectId:e,projectName:t}){let n="/sessions",s=new URLSearchParams;if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)ee(e),n+=`/${e}`;else if(t!==void 0)s.append("name",t);else throw new Error("Must provide projectName or projectId");let a=await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}${n}?${s}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(i,"has project"),i});try{let i=await a.json();return a.ok?Array.isArray(i)?i.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:t,includeStats:n}){let s="/sessions",a=new URLSearchParams;if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)ee(e),s+=`/${e}`;else if(t!==void 0)a.append("name",t);else throw new Error("Must provide projectName or projectId");n!==void 0&&a.append("include_stats",n.toString());let i=await this._get(s,a),o;if(Array.isArray(i)){if(i.length===0)throw new Error(`Project[id=${e}, name=${t}] not found`);o=i[0]}else o=i;return o}async getProjectUrl({projectId:e,projectName:t}){if(e===void 0&&t===void 0)throw new Error("Must provide either projectName or projectId");let n=await this.readProject({projectId:e,projectName:t}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(e===void 0&&t===void 0)throw new Error("Must provide either datasetName or datasetId");let n=await this.readDataset({datasetId:e,datasetName:t}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let t of this._getPaginated("/sessions",e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:t,nameContains:n,referenceDatasetId:s,referenceDatasetName:a,includeStats:i,datasetVersion:o,referenceFree:u,metadata:c}={}){let l=new URLSearchParams;if(e!==void 0)for(let d of e)l.append("id",d);if(t!==void 0&&l.append("name",t),n!==void 0&&l.append("name_contains",n),s!==void 0)l.append("reference_dataset",s);else if(a!==void 0){let d=await this.readDataset({datasetName:a});l.append("reference_dataset",d.id)}i!==void 0&&l.append("include_stats",i.toString()),o!==void 0&&l.append("dataset_version",o),u!==void 0&&l.append("reference_free",u.toString()),c!==void 0&&l.append("metadata",JSON.stringify(c));for await(let d of this._getPaginated("/sessions",l))yield*d}async deleteProject({projectId:e,projectName:t}){let n;if(e===void 0&&t===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?n=(await this.readProject({projectName:t})).id:n=e,ee(n),await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(s,`delete session ${n} (${t})`,!0),s})}async uploadCsv({csvFile:e,fileName:t,inputKeys:n,outputKeys:s,description:a,dataType:i,name:o}){let u=`${this.apiUrl}/datasets/upload`,c=new FormData;return c.append("file",e,t),n.forEach(f=>{c.append("input_keys",f)}),s.forEach(f=>{c.append("output_keys",f)}),a&&c.append("description",a),i&&c.append("data_type",i),o&&c.append("name",o),await(await this.caller.call(async()=>{let f=await this._fetch(u,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await F(f,"upload CSV"),f})).json()}async createDataset(e,{description:t,dataType:n,inputsSchema:s,outputsSchema:a,metadata:i}={}){let o={name:e,description:t,extra:i?{metadata:i}:void 0};n&&(o.data_type=n),s&&(o.inputs_schema_definition=s),a&&(o.outputs_schema_definition=a);let u=JSON.stringify(o);return await(await this.caller.call(async()=>{let 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:u});return await F(d,"create dataset"),d})).json()}async readDataset({datasetId:e,datasetName:t}){let n="/datasets",s=new URLSearchParams({limit:"1"});if(e&&t)throw new Error("Must provide either datasetName or datasetId, not both");if(e)ee(e),n+=`/${e}`;else if(t)s.append("name",t);else throw new Error("Must provide datasetName or datasetId");let a=await this._get(n,s),i;if(Array.isArray(a)){if(a.length===0)throw new Error(`Dataset[id=${e}, name=${t}] not found`);i=a[0]}else i=a;return i}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(n){if(n instanceof Error&&n.message.toLocaleLowerCase().includes("not found"))return!1;throw n}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:n,toVersion:s}){let a=e;if(a===void 0&&t===void 0)throw new Error("Must provide either datasetName or datasetId");if(a!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");a===void 0&&(a=(await this.readDataset({datasetName:t})).id);let i=new URLSearchParams({from_version:typeof n=="string"?n:n.toISOString(),to_version:typeof s=="string"?s:s.toISOString()});return await this._get(`/datasets/${a}/versions/diff`,i)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){let n="/datasets";if(e===void 0)if(t!==void 0)e=(await this.readDataset({datasetName:t})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${n}/${e}/openai_ft`)).text()).trim().split(`
27
+ `).map(o=>JSON.parse(o))}async*listDatasets({limit:e=100,offset:t=0,datasetIds:n,datasetName:s,datasetNameContains:a,metadata:i}={}){let o="/datasets",u=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(n!==void 0)for(let c of n)u.append("id",c);s!==void 0&&u.append("name",s),a!==void 0&&u.append("name_contains",a),i!==void 0&&u.append("metadata",JSON.stringify(i));for await(let c of this._getPaginated(o,u))yield*c}async updateDataset(e){let{datasetId:t,datasetName:n,...s}=e;if(!t&&!n)throw new Error("Must provide either datasetName or datasetId");let a=t??(await this.readDataset({datasetName:n})).id;ee(a);let i=JSON.stringify(s);return await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${a}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await F(u,"update dataset"),u})).json()}async updateDatasetTag(e){let{datasetId:t,datasetName:n,asOf:s,tag:a}=e;if(!t&&!n)throw new Error("Must provide either datasetName or datasetId");let i=t??(await this.readDataset({datasetName:n})).id;ee(i);let o=JSON.stringify({as_of:typeof s=="string"?s:s.toISOString(),tag:a});await this.caller.call(async()=>{let u=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 F(u,"update dataset tags",!0),u})}async deleteDataset({datasetId:e,datasetName:t}){let n="/datasets",s=e;if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(t!==void 0&&(s=(await this.readDataset({datasetName:t})).id),s!==void 0)ee(s),n+=`/${s}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let a=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(a,`delete ${n}`,!0),a})}async indexDataset({datasetId:e,datasetName:t,tag:n}){let s=e;if(!s&&!t)throw new Error("Must provide either datasetName or datasetId");if(s&&t)throw new Error("Must provide either datasetName or datasetId, not both");s||(s=(await this.readDataset({datasetName:t})).id),ee(s);let i=JSON.stringify({tag:n});await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${s}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await F(u,"index dataset"),u})).json()}async similarExamples(e,t,n,{filter:s}={}){let a={limit:n,inputs:e};s!==void 0&&(a.filter=s),ee(t);let i=JSON.stringify(a);return(await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${t}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:i});return await F(c,"fetch similar examples"),c})).json()).examples}async createExample(e,t,n){if(tb(e)&&(t!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let s=t?n?.datasetId:e.dataset_id,a=t?n?.datasetName:e.dataset_name;if(s===void 0&&a===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&a!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:a})).id);let i=(t?n?.createdAt:e.created_at)||new Date,o;tb(e)?o=e:o={inputs:e,outputs:t,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};let u=await this._uploadExamplesMultipart(s,[o]);return await this.readExample(u.example_ids?.[0]??_e())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let b=e,x=b[0].dataset_id,I=b[0].dataset_name;if(x===void 0&&I===void 0)throw new Error("Must provide either datasetName or datasetId");if(x!==void 0&&I!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");x===void 0&&(x=(await this.readDataset({datasetName:I})).id);let P=await this._uploadExamplesMultipart(x,b);return await Promise.all(P.example_ids.map(V=>this.readExample(V)))}let{inputs:t,outputs:n,metadata:s,splits:a,sourceRunIds:i,useSourceRunIOs:o,useSourceRunAttachments:u,attachments:c,exampleIds:l,datasetId:d,datasetName:f}=e;if(t===void 0)throw new Error("Must provide inputs when using legacy parameters");let p=d,m=f;if(p===void 0&&m===void 0)throw new Error("Must provide either datasetName or datasetId");if(p!==void 0&&m!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");p===void 0&&(p=(await this.readDataset({datasetName:m})).id);let h=t.map((b,x)=>({dataset_id:p,inputs:b,outputs:n?.[x],metadata:s?.[x],split:a?.[x],id:l?.[x],attachments:c?.[x],source_run_id:i?.[x],use_source_run_io:o?.[x],use_source_run_attachments:u?.[x]})),g=await this._uploadExamplesMultipart(p,h);return await Promise.all(g.example_ids.map(b=>this.readExample(b)))}async createLLMExample(e,t,n){return this.createExample({input:e},{output:t},n)}async createChatExample(e,t,n){let s=e.map(i=>Vd(i)?qd(i):i),a=Vd(t)?qd(t):t;return this.createExample({input:s},{output:a},n)}async readExample(e){ee(e);let t=`/examples/${e}`,n=await this._get(t),{attachment_urls:s,...a}=n,i=a;return s&&(i.attachments=Object.entries(s).reduce((o,[u,c])=>(o[u.slice(11)]={presigned_url:c.presigned_url,mime_type:c.mime_type},o),{})),i}async*listExamples({datasetId:e,datasetName:t,exampleIds:n,asOf:s,splits:a,inlineS3Urls:i,metadata:o,limit:u,offset:c,filter:l,includeAttachments:d}={}){let f;if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)f=e;else if(t!==void 0)f=(await this.readDataset({datasetName:t})).id;else throw new Error("Must provide a datasetName or datasetId");let p=new URLSearchParams({dataset:f}),m=s?typeof s=="string"?s:s?.toISOString():void 0;m&&p.append("as_of",m);let h=i??!0;if(p.append("inline_s3_urls",h.toString()),n!==void 0)for(let w of n)p.append("id",w);if(a!==void 0)for(let w of a)p.append("splits",w);if(o!==void 0){let w=JSON.stringify(o);p.append("metadata",w)}u!==void 0&&p.append("limit",u.toString()),c!==void 0&&p.append("offset",c.toString()),l!==void 0&&p.append("filter",l),d===!0&&["attachment_urls","outputs","metadata"].forEach(w=>p.append("select",w));let g=0;for await(let w of this._getPaginated("/examples",p)){for(let b of w){let{attachment_urls:x,...I}=b,P=I;x&&(P.attachments=Object.entries(x).reduce((K,[V,Z])=>(K[V.slice(11)]={presigned_url:Z.presigned_url,mime_type:Z.mime_type||void 0},K),{})),yield P,g++}if(u!==void 0&&g>=u)break}}async deleteExample(e){ee(e);let t=`/examples/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(n,`delete ${t}`,!0),n})}async updateExample(e,t){let n;t?n=e:n=e.id,ee(n);let s;t?s={id:n,...t}:s=e;let a;return s.dataset_id!==void 0?a=s.dataset_id:a=(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(a,[s])}async updateExamples(e){let t;return e[0].dataset_id===void 0?t=(await this.readExample(e[0].id)).dataset_id:t=e[0].dataset_id,this._updateExamplesMultipart(t,e)}async readDatasetVersion({datasetId:e,datasetName:t,asOf:n,tag:s}){let a;if(e?a=e:a=(await this.readDataset({datasetName:t})).id,ee(a),n&&s||!n&&!s)throw new Error("Exactly one of asOf and tag must be specified.");let i=new URLSearchParams;return n!==void 0&&i.append("as_of",typeof n=="string"?n:n.toISOString()),s!==void 0&&i.append("tag",s),await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${a}/version?${i.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(u,"read dataset version"),u})).json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:n}){let s;if(e===void 0&&t===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?s=(await this.readDataset({datasetName:t})).id:s=e,ee(s);let a=new URLSearchParams,i=n?typeof n=="string"?n:n?.toISOString():void 0;return i&&a.append("as_of",i),await this._get(`/datasets/${s}/splits`,a)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:n,exampleIds:s,remove:a=!1}){let i;if(e===void 0&&t===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?i=(await this.readDataset({datasetName:t})).id:i=e,ee(i);let o={split_name:n,examples:s.map(c=>(ee(c),c)),remove:a},u=JSON.stringify(o);await this.caller.call(async()=>{let c=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:u});return await F(c,"update dataset splits",!0),c})}async evaluateRun(e,t,{sourceInfo:n,loadChildRuns:s,referenceExample:a}={loadChildRuns:!1}){zi("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:s});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&&(a=await this.readExample(i.reference_example_id));let o=await t.evaluateRun(i,a),[u,c]=await this._logEvaluationFeedback(o,i,n);return c[0]}async createFeedback(e,t,{score:n,value:s,correction:a,comment:i,sourceInfo:o,feedbackSourceType:u="api",sourceRunId:c,feedbackId:l,feedbackConfig:d,projectId:f,comparativeExperimentId:p}){if(!e&&!f)throw new Error("One of runId or projectId must be provided");if(e&&f)throw new Error("Only one of runId or projectId can be provided");let m={type:u??"api",metadata:o??{}};c!==void 0&&m?.metadata!==void 0&&!m.metadata.__run&&(m.metadata.__run={run_id:c}),m?.metadata!==void 0&&m.metadata.__run?.run_id!==void 0&&ee(m.metadata.__run.run_id);let h={id:l??_e(),run_id:e,key:t,score:Qy(n),value:s,correction:a,comment:i,feedback_source:m,comparative_experiment_id:p,feedbackConfig:d,session_id:f},g=JSON.stringify(h),w=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let b=await this._fetch(w,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:g});return await F(b,"create feedback",!0),b}),h}async updateFeedback(e,{score:t,value:n,correction:s,comment:a}){let i={};t!=null&&(i.score=Qy(t)),n!=null&&(i.value=n),s!=null&&(i.correction=s),a!=null&&(i.comment=a),ee(e);let o=JSON.stringify(i);await this.caller.call(async()=>{let u=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 F(u,"update feedback",!0),u})}async readFeedback(e){ee(e);let t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){ee(e);let t=`/feedback/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(n,`delete ${t}`,!0),n})}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:n}={}){let s=new URLSearchParams;if(e)for(let a of e)ee(a),s.append("run",a);if(t)for(let a of t)s.append("key",a);if(n)for(let a of n)s.append("source",a);for await(let a of this._getPaginated("/feedback",s))yield*a}async createPresignedFeedbackToken(e,t,{expiration:n,feedbackConfig:s}={}){let a={run_id:e,feedback_key:t,feedback_config:s};n?typeof n=="string"?a.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(a.expires_in=n):a.expires_in={hours:3};let i=JSON.stringify(a);return await(await this.caller.call(async()=>{let u=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 F(u,"create presigned feedback token"),u})).json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:n,createdAt:s,description:a,metadata:i,id:o}){if(t.length===0)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:t[0]})).reference_dataset_id),!n==null)throw new Error("A reference dataset is required");let u={id:o,name:e,experiment_ids:t,reference_dataset_id:n,description:a,created_at:(s??new Date)?.toISOString(),extra:{}};i&&(u.extra.metadata=i);let c=JSON.stringify(u);return(await this.caller.call(async()=>{let 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:c});return await F(d,"create comparative experiment"),d})).json()}async*listPresignedFeedbackTokens(e){ee(e);let t=new URLSearchParams({run_id:e});for await(let n of this._getPaginated("/feedback/tokens",t))yield*n}_selectEvalResults(e){let t;return"results"in e?t=e.results:Array.isArray(e)?t=e:t=[e],t}async _logEvaluationFeedback(e,t,n){let s=this._selectEvalResults(e),a=[];for(let i of s){let o=n||{};i.evaluatorInfo&&(o={...i.evaluatorInfo,...o});let u=null;i.targetRunId?u=i.targetRunId:t&&(u=t.id),a.push(await this.createFeedback(u,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[s,a]}async logEvaluationFeedback(e,t,n){let[s]=await this._logEvaluationFeedback(e,t,n);return s}async*listAnnotationQueues(e={}){let{queueIds:t,name:n,nameContains:s,limit:a}=e,i=new URLSearchParams;t&&t.forEach((u,c)=>{ee(u,`queueIds[${c}]`),i.append("ids",u)}),n&&i.append("name",n),s&&i.append("name_contains",s),i.append("limit",(a!==void 0?Math.min(a,100):100).toString());let o=0;for await(let u of this._getPaginated("/annotation-queues",i))if(yield*u,o++,a!==void 0&&o>=a)break}async createAnnotationQueue(e){let{name:t,description:n,queueId:s,rubricInstructions:a}=e,i={name:t,description:n,id:s||_e(),rubric_instructions:a},o=JSON.stringify(Object.fromEntries(Object.entries(i).filter(([c,l])=>l!==void 0)));return(await this.caller.call(async()=>{let c=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 F(c,"create annotation queue"),c})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${ee(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(e,t){let{name:n,description:s,rubricInstructions:a}=t,i=JSON.stringify({name:n,description:s,rubric_instructions:a});await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/annotation-queues/${ee(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await F(o,"update annotation queue",!0),o})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${ee(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(t,"delete annotation queue",!0),t})}async addRunsToAnnotationQueue(e,t){let n=JSON.stringify(t.map((s,a)=>ee(s,`runIds[${a}]`).toString()));await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/annotation-queues/${ee(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await F(s,"add runs to annotation queue",!0),s})}async getRunFromAnnotationQueue(e,t){let n=`/annotation-queues/${ee(e,"queueId")}/run`;return(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${n}/${t}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(a,"get run from annotation queue"),a})).json()}async deleteRunFromAnnotationQueue(e,t){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${ee(e,"queueId")}/runs/${ee(t,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(n,"delete run from annotation queue",!0),n})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${ee(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(n,"get size from annotation queue"),n})).json()}async _currentTenantIsOwner(e){let t=await this._getSettings();return e=="-"||t.tenant_handle===e}async _ownerConflictError(e,t){let n=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
28
+
29
+ Current tenant: ${n.tenant_handle}
30
+
31
+ Requested tenant: ${t}`)}async _getLatestCommitHash(e){let n=await(await this.caller.call(async()=>{let s=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 F(s,"get latest commit hash"),s})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){let[n,s,a]=Nr(e),i=JSON.stringify({like:t});return(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/likes/${n}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await F(u,`${t?"like":"unlike"} prompt`),u})).json()}async _getPromptUrl(e){let[t,n,s]=Nr(e);if(await this._currentTenantIsOwner(t)){let a=await this._getSettings();return s!=="latest"?`${this.getHostUrl()}/prompts/${n}/${s.substring(0,8)}?organizationId=${a.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${a.id}`}else return s!=="latest"?`${this.getHostUrl()}/hub/${t}/${n}/${s.substring(0,8)}`:`${this.getHostUrl()}/hub/${t}/${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(let t of this._getPaginated(`/commits/${e}/`,new URLSearchParams,n=>n.commits))yield*t}async*listPrompts(e){let t=new URLSearchParams;t.append("sort_field",e?.sortField??"updated_at"),t.append("sort_direction","desc"),t.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&t.append("is_public",e.isPublic.toString()),e?.query&&t.append("query",e.query);for await(let n of this._getPaginated("/repos",t,s=>s.repos))yield*n}async getPrompt(e){let[t,n,s]=Nr(e),i=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/repos/${t}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return o?.status===404?null:(await F(o,"get prompt"),o)}))?.json();return i?.repo?i.repo:null}async createPrompt(e,t){let n=await this._getSettings();if(t?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
32
+
33
+ creating a LangChain Hub handle.
34
+ You can add a handle by creating a public prompt at:
35
+
36
+ https://smith.langchain.com/prompts`);let[s,a,i]=Nr(e);if(!await this._currentTenantIsOwner(s))throw await this._ownerConflictError("create a prompt",s);let o={repo_handle:a,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic},u=JSON.stringify(o),c=await this.caller.call(async()=>{let 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:u});return await F(d,"create prompt"),d}),{repo:l}=await c.json();return l}async createCommit(e,t,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[s,a,i]=Nr(e),o=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${s}/${a}`):n?.parentCommitHash,u={manifest:JSON.parse(JSON.stringify(t)),parent_commit:o},c=JSON.stringify(u),d=await(await this.caller.call(async()=>{let f=await this._fetch(`${this.apiUrl}/commits/${s}/${a}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await F(f,"create commit"),f})).json();return this._getPromptUrl(`${s}/${a}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(e,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){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.");let n=new FormData;for(let i of t){let o=i.id,u={...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split}},c=at(u,`Serializing body for example with id: ${o}`),l=new Blob([c],{type:"application/json"});if(n.append(o,l),i.inputs){let d=at(i.inputs,`Serializing inputs for example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.inputs`,f)}if(i.outputs){let d=at(i.outputs,`Serializing outputs whle updating example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.outputs`,f)}if(i.attachments)for(let[d,f]of Object.entries(i.attachments)){let p,m;Array.isArray(f)?[p,m]=f:(p=f.mimeType,m=f.data);let h=new Blob([m],{type:`${p}; length=${m.byteLength}`});n.append(`${o}.attachment.${d}`,h)}if(i.attachments_operations){let d=at(i.attachments_operations,`Serializing attachments while updating example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.attachments_operations`,f)}}let s=e??t[0]?.dataset_id;return(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${s}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await F(i,"update examples"),i})).json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){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.");let n=new FormData;for(let a of t){let i=(a.id??_e()).toString(),o={created_at:a.created_at,...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split},...a.source_run_id&&{source_run_id:a.source_run_id},...a.use_source_run_io&&{use_source_run_io:a.use_source_run_io},...a.use_source_run_attachments&&{use_source_run_attachments:a.use_source_run_attachments}},u=at(o,`Serializing body for uploaded example with id: ${i}`),c=new Blob([u],{type:"application/json"});if(n.append(i,c),a.inputs){let l=at(a.inputs,`Serializing inputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});n.append(`${i}.inputs`,d)}if(a.outputs){let l=at(a.outputs,`Serializing outputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});n.append(`${i}.outputs`,d)}if(a.attachments)for(let[l,d]of Object.entries(a.attachments)){let f,p;Array.isArray(d)?[f,p]=d:(f=d.mimeType,p=d.data);let m=new Blob([p],{type:`${f}; length=${p.byteLength}`});n.append(`${i}.attachment.${l}`,m)}}return(await this.caller.call(async()=>{let a=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 F(a,"upload examples"),a})).json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[n,s]=Nr(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);let a={};if(t?.description!==void 0&&(a.description=t.description),t?.readme!==void 0&&(a.readme=t.readme),t?.tags!==void 0&&(a.tags=t.tags),t?.isPublic!==void 0&&(a.is_public=t.isPublic),t?.isArchived!==void 0&&(a.is_archived=t.isArchived),Object.keys(a).length===0)throw new Error("No valid update options provided");let i=JSON.stringify(a);return(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/repos/${n}/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await F(u,"update prompt"),u})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[t,n,s]=Nr(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);return(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/repos/${t}/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(i,"delete prompt"),i})).json()}async pullPromptCommit(e,t){let[n,s,a]=Nr(e),o=await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/commits/${n}/${s}/${a}${t?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await F(u,"pull prompt commit"),u})).json();return{owner:n,repo:s,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async _pullPrompt(e,t){let n=await this.pullPromptCommit(e,{includeModel:t?.includeModel});return JSON.stringify(n.manifest)}async pushPrompt(e,t){return await this.promptExists(e)?t&&Object.keys(t).some(s=>s!=="object")&&await this.updatePrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}):await this.createPrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}),t?.object?await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,t={}){let{sourceApiUrl:n=this.apiUrl,datasetName:s}=t,[a,i]=this.parseTokenOrUrl(e,n),o=new r({apiUrl:a,apiKey:"placeholder"}),u=await o.readSharedDataset(i),c=s||u.name;try{if(await this.hasDataset({datasetId:c})){console.log(`Dataset ${c} already exists in your tenant. Skipping.`);return}}catch{}let l=await o.listSharedExamples(i),d=await this.createDataset(c,{description:u.description,dataType:u.data_type||"kv",inputsSchema:u.inputs_schema_definition??void 0,outputsSchema:u.outputs_schema_definition??void 0});try{await this.createExamples({inputs:l.map(f=>f.inputs),outputs:l.flatMap(f=>f.outputs?[f.outputs]:[]),datasetId:d.id})}catch(f){throw console.error(`An error occurred while creating dataset ${c}. You should delete it manually.`),f}}parseTokenOrUrl(e,t,n=2,s="dataset"){try{return ee(e),[t,e]}catch{}try{let i=new URL(e).pathname.split("/").filter(o=>o!=="");if(i.length>=n){let o=i[i.length-n];return[t,o]}else throw new Error(`Invalid public ${s} URL: ${e}`)}catch{throw new Error(`Invalid public ${s} 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 Dg()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}});var rb,nb=_(()=>{"use strict";Cr();rb=r=>r!==void 0?r:!!["TRACING_V2","TRACING"].find(t=>Oe(t)==="true")});var cc,sb=_(()=>{"use strict";cc=Symbol.for("lc:context_variables")});function QT(r){return r.replace(/[-:.]/g,"")}function gp(r,e,t=1){let n=t.toFixed(0).slice(0,3).padStart(3,"0"),s=`${new Date(r).toISOString().slice(0,-1)}${n}Z`;return{dottedOrder:QT(s)+e,microsecondPrecisionDatestring:s}}function ib(r){return r!=null&&typeof r.createChild=="function"&&typeof r.postRun=="function"}function ob(r){return typeof r=="object"&&r!=null&&typeof r.name=="string"&&r.name==="langchain_tracer"}function ab(r){return Array.isArray(r)&&r.some(e=>ob(e))}function eP(r){return typeof r=="object"&&r!=null&&Array.isArray(r.handlers)}function tP(r){return r!=null&&typeof r.callbacks=="object"&&(ab(r.callbacks?.handlers)||ab(r.callbacks))}function rP(r){return r.split(".").map(t=>{let n=t.slice(0,-36),s=t.slice(-36),a=parseInt(n.slice(0,4)),i=parseInt(n.slice(4,6))-1,o=parseInt(n.slice(6,8)),u=parseInt(n.slice(9,11)),c=parseInt(n.slice(11,13)),l=parseInt(n.slice(13,15)),d=parseInt(n.slice(15,21));return[new Date(a,i,o,u,c,l,d/1e3),s]})}function nP(){let r=mt("LANGSMITH_RUNS_ENDPOINTS");if(!r)return[];try{let e=JSON.parse(r);if(Array.isArray(e)){let t=[];for(let 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}t.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key})}return t}else if(typeof e=="object"&&e!==null){aP(e);let t=[];for(let[n,s]of Object.entries(e)){let a=n.replace(/\/$/,"");if(typeof s=="string")t.push({apiUrl:a,apiKey:s});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof s}`);continue}}return t}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 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(Ky(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function sP(r){return r?r.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):nP()}function aP(r){if(Object.keys(r).length>0&&Oe("ENDPOINT"))throw new ac}var lc,Ut,Od=_(()=>{"use strict";ts();Ad();nb();pp();sb();Cr();Ed();Cr();Gd();lc=class r{constructor(e,t,n,s){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=t,this.project_name=n,this.replicas=s}static fromHeader(e){let t=e.split(","),n={},s=[],a,i;for(let o of t){let[u,c]=o.split("="),l=decodeURIComponent(c);u==="langsmith-metadata"?n=JSON.parse(l):u==="langsmith-tags"?s=l.split(","):u==="langsmith-project"?a=l:u==="langsmith-replicas"&&(i=JSON.parse(l))}return new r(n,s,a,i)}toHeader(){let 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(",")}},Ut=class r{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}),ib(e)){Object.assign(this,{...e});return}let t=r.getDefaultConfig(),{metadata:n,...s}=e,a=s.client??r.getSharedClient(),i={...n,...s?.extra?.metadata};if(s.extra={...s.extra,metadata:i},Object.assign(this,{...t,...s,client:a}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=sP(this.replicas),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){let{dottedOrder:o,microsecondPrecisionDatestring:u}=gp(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=u}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){return{id:_e(),run_type:"chain",project_name:Ni(),child_runs:[],api_url:mt("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:mt("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return r.sharedClient||(r.sharedClient=new ss),r.sharedClient}createChild(e){let t=this.child_execution_order+1,n=new r({...e,parent_run:this,project_name:this.project_name,replicas:this.replicas,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:t,child_execution_order:t});cc in this&&(n[cc]=this[cc]);let s=Symbol.for("lc:child_config"),a=e.extra?.[s]??this.extra[s];if(tP(a)){let u={...a},c=eP(u.callbacks)?u.callbacks.copy?.():void 0;c&&(Object.assign(c,{_parentRunId:n.id}),c.handlers?.find(ob)?.updateFromRunTree?.(n),u.callbacks=c),n.extra[s]=u}let i=new Set,o=this;for(;o!=null&&!i.has(o.id);)i.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,t),o=o.parent_run;return this.child_runs.push(n),n}async end(e,t,n=Date.now(),s){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??n,s&&Object.keys(s).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...s}}:{metadata:s})}_convertToCreate(e,t,n=!0){let s=e.extra??{};if(s?.runtime?.library===void 0&&(s.runtime||(s.runtime={}),t))for(let[o,u]of Object.entries(t))s.runtime[o]||(s.runtime[o]=u);let a,i;return n?(i=e.parent_run?.id??e.parent_run_id,a=[]):(a=e.child_runs.map(o=>this._convertToCreate(o,t,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:s,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:a,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,t,n=!0){let s=this._convertToCreate(this,t,n);if(e===this.project_name)return s;let a=d=>Tu(`${d}:${e}`,Tu.DNS),i=a(s.id),o=s.trace_id?a(s.trace_id):void 0,u=s.parent_run_id?a(s.parent_run_id):void 0,c;if(s.dotted_order){let d=rP(s.dotted_order),f=[];for(let m=0;m<d.length-1;m++){let[h,g]=d[m],w=a(g);f.push(h.toISOString().replace(/[-:]/g,"").replace(".","")+w)}let[p]=d[d.length-1];f.push(p.toISOString().replace(/[-:]/g,"").replace(".","")+i),c=f.join(".")}else c=void 0;return{...s,id:i,trace_id:o,parent_run_id:u,dotted_order:c,session_name:e}}async postRun(e=!0){try{let t=Du();if(this.replicas&&this.replicas.length>0)for(let{projectName:n,apiKey:s,apiUrl:a,workspaceId:i}of this.replicas){let o=this._remapForProject(n??this.project_name,t,!0);await this.client.createRun(o,{apiKey:s,apiUrl:a,workspaceId:i})}else{let n=this._convertToCreate(this,t,e);await this.client.createRun(n)}if(!e){zi("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(let n of this.child_runs)await n.postRun(!1)}}catch(t){console.error(`Error in postRun for run ${this.id}:`,t)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(let{projectName:t,apiKey:n,apiUrl:s,workspaceId:a,updates:i}of this.replicas){let o=this._remapForProject(t??this.project_name),u={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||(u.inputs=o.inputs),await this.client.updateRun(o.id,u,{apiKey:n,apiUrl:s,workspaceId:a})}else try{let t={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||(t.inputs=this.inputs),await this.client.updateRun(this.id,t)}catch(t){console.error(`Error in patchRun for run ${this.id}`,t)}}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,t){let n=e?.callbacks,s,a,i,o=rb();if(n){let c=n?.getParentRunId?.()??"",l=n?.handlers?.find(d=>d?.name=="langchain_tracer");s=l?.getRun?.(c),a=l?.projectName,i=l?.client,o=o||!!l}return s?new r({name:s.name,id:s.id,trace_id:s.trace_id,dotted_order:s.dotted_order,client:i,tracingEnabled:o,project_name:a,tags:[...new Set((s?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...s?.extra?.metadata,...e?.metadata}}}).createChild(t):new r({...t,client:i,tracingEnabled:o,project_name:a})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){let n="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,s=n["langsmith-trace"];if(!s||typeof s!="string")return;let a=s.trim(),i=a.split(".").map(c=>{let[l,d]=c.split("Z");return{strTime:l,time:Date.parse(l+"Z"),uuid:d}}),o=i[0].uuid,u={...t,name:t?.name??"parent",run_type:t?.run_type??"chain",start_time:t?.start_time??Date.now(),id:i.at(-1)?.uuid,trace_id:o,dotted_order:a};if(n.baggage&&typeof n.baggage=="string"){let c=lc.fromHeader(n.baggage);u.metadata=c.metadata,u.tags=c.tags,u.project_name=c.project_name,u.replicas=c.replicas}return new r(u)}toHeaders(e){let t={"langsmith-trace":this.dotted_order,baggage:new lc(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(let[n,s]of Object.entries(t))e.set(n,s);return t}};Object.defineProperty(Ut,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null})});var dc=_(()=>{"use strict";Od()});var cb=D((p1,ub)=>{"use strict";ub.exports=function(r,e){if(typeof r!="string")throw new TypeError("Expected a string");return e=typeof e>"u"?"_":e,r.replace(/([a-z\d])([A-Z])/g,"$1"+e+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+e+"$2").toLowerCase()}});var gb=D((f1,_p)=>{"use strict";var iP=/[\p{Lu}]/u,oP=/[\p{Ll}]/u,lb=/^[\p{Lu}](?![\p{Lu}])/gu,fb=/([\p{Alpha}\p{N}_]|$)/u,mb=/[_.\- ]+/,uP=new RegExp("^"+mb.source),db=new RegExp(mb.source+fb.source,"gu"),pb=new RegExp("\\d+"+fb.source,"gu"),cP=(r,e,t)=>{let n=!1,s=!1,a=!1;for(let i=0;i<r.length;i++){let o=r[i];n&&iP.test(o)?(r=r.slice(0,i)+"-"+r.slice(i),n=!1,a=s,s=!0,i++):s&&a&&oP.test(o)?(r=r.slice(0,i-1)+"-"+r.slice(i-1),a=s,s=!1,n=!0):(n=e(o)===o&&t(o)!==o,a=s,s=t(o)===o&&e(o)!==o)}return r},lP=(r,e)=>(lb.lastIndex=0,r.replace(lb,t=>e(t))),dP=(r,e)=>(db.lastIndex=0,pb.lastIndex=0,r.replace(db,(t,n)=>e(n)).replace(pb,t=>e(t))),hb=(r,e)=>{if(!(typeof r=="string"||Array.isArray(r)))throw new TypeError("Expected the input to be `string | string[]`");if(e={pascalCase:!1,preserveConsecutiveUppercase:!1,...e},Array.isArray(r)?r=r.map(a=>a.trim()).filter(a=>a.length).join("-"):r=r.trim(),r.length===0)return"";let t=e.locale===!1?a=>a.toLowerCase():a=>a.toLocaleLowerCase(e.locale),n=e.locale===!1?a=>a.toUpperCase():a=>a.toLocaleUpperCase(e.locale);return r.length===1?e.pascalCase?n(r):t(r):(r!==t(r)&&(r=cP(r,t,n)),r=r.replace(uP,""),e.preserveConsecutiveUppercase?r=lP(r,t):r=t(r),e.pascalCase&&(r=n(r.charAt(0))+r.slice(1)),dP(r,n))};_p.exports=hb;_p.exports.default=hb});function yb(r,e){return e?.[r]||(0,_b.default)(r)}function bb(r,e,t){let n={};for(let s in r)Object.hasOwn(r,s)&&(n[e(s,t)]=r[s]);return n}var _b,pP,wb=_(()=>{"use strict";_b=Dt(cb(),1),pP=Dt(gb(),1)});function vb(r){return Array.isArray(r)?[...r]:{...r}}function fP(r,e){let t=vb(r);for(let[n,s]of Object.entries(e)){let[a,...i]=n.split(".").reverse(),o=t;for(let u of i.reverse()){if(o[u]===void 0)break;o[u]=vb(o[u]),o=o[u]}o[a]!==void 0&&(o[a]={lc:1,type:"secret",id:[s]})}return t}function yp(r){let e=Object.getPrototypeOf(r);return typeof r.lc_name=="function"&&(typeof e.lc_name!="function"||r.lc_name()!==e.lc_name())?r.lc_name():r.name}var Bt,qi=_(()=>{"use strict";wb();Bt=class r{static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,yp(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...t){Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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 r||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let e={},t={},n=Object.keys(this.lc_kwargs).reduce((s,a)=>(s[a]=a in this?this[a]:this.lc_kwargs[a],s),{});for(let s=Object.getPrototypeOf(this);s;s=Object.getPrototypeOf(s))Object.assign(e,Reflect.get(s,"lc_aliases",this)),Object.assign(t,Reflect.get(s,"lc_secrets",this)),Object.assign(n,Reflect.get(s,"lc_attributes",this));return Object.keys(t).forEach(s=>{let a=this,i=n,[o,...u]=s.split(".").reverse();for(let c of u.reverse()){if(!(c in a)||a[c]===void 0)return;(!(c in i)||i[c]===void 0)&&(typeof a[c]=="object"&&a[c]!=null?i[c]={}:Array.isArray(a[c])&&(i[c]=[])),a=a[c],i=i[c]}o in a&&a[o]!==void 0&&(i[o]=i[o]||a[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:bb(Object.keys(t).length?fP(n,t):n,yb,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}});function Eb(){return bp===void 0&&(bp={library:"langchain-js",runtime:xb()}),bp}function we(r){try{return typeof process<"u"?process.env?.[r]:wp()?Deno?.env.get(r):void 0}catch{return}}var mP,hP,gP,wp,_P,xb,bp,is=_(()=>{"use strict";mP=()=>typeof window<"u"&&typeof window.document<"u",hP=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",gP=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),wp=()=>typeof Deno<"u",_P=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!wp(),xb=()=>{let r;return mP()?r="browser":_P()?r="node":hP()?r="webworker":gP()?r="jsdom":wp()?r="deno":r="other",r}});function xp(r){return"lc_prefer_streaming"in r&&r.lc_prefer_streaming}var vp,os,Ab,Gi=_(()=>{"use strict";ts();qi();is();vp=class{};os=class r extends vp{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,yp(this.constructor)]}constructor(e){super(),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ignoreLLM",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreChain",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreAgent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreRetriever",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreCustomEvent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"raiseError",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"awaitHandlers",{enumerable:!0,configurable:!0,writable:!0,value:we("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"}),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return Bt.prototype.toJSON.call(this)}toJSONNotImplemented(){return Bt.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends r{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:_e()}),Object.assign(this,e)}}return new t}},Ab=r=>{let e=r;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"}});function Ap(r,e){if(r)return new Ut({...r,start_time:r._serialized_start_time??r.start_time,parent_run:Ap(e),child_runs:r.child_runs.map(t=>Ap(t)).filter(t=>t!==void 0),extra:{...r.extra,runtime:Eb()},tracingEnabled:!1})}function Ep(r,e){return r&&!Array.isArray(r)&&typeof r=="object"?r:{[e]:r}}function ca(r){return typeof r._addRunToRunMap=="function"}var yP,St,us=_(()=>{"use strict";dc();Gi();is();yP=r=>{if(r)return r.events=r.events??[],r.child_runs=r.child_runs??[],r};St=class extends os{constructor(e){super(...arguments),Object.defineProperty(this,"runMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"runTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"usesRunTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:!1})}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?yP(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`
37
+
38
+ ${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){let{dottedOrder:t,microsecondPrecisionDatestring:n}=gp(new Date(e.start_time).getTime(),e.id,e.execution_order),s={...e},a=this.getRunById(s.parent_run_id);if(s.parent_run_id!==void 0?a&&(this._addChildRun(a,s),a.child_execution_order=Math.max(a.child_execution_order,s.child_execution_order),s.trace_id=a.trace_id,a.dotted_order!==void 0&&(s.dotted_order=[a.dotted_order,t].join("."),s._serialized_start_time=n)):(s.trace_id=s.id,s.dotted_order=t,s._serialized_start_time=n),this.usesRunTreeMap){let i=Ap(s,a);i!==void 0&&this.runTreeMap.set(s.id,i)}else this.runMap.set(s.id,s);return s}async _endTrace(e){let t=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){let t=e!==void 0&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,n,s,a,i,o,u){let c=this._getExecutionOrder(s),l=Date.now(),d=o?{...a,metadata:o}:a,f={id:n,name:u??e.id[e.id.length-1],parent_run_id:s,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{prompts:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(f)}async handleLLMStart(e,t,n,s,a,i,o,u){let c=this.getRunById(n)??this._createRunForLLMStart(e,t,n,s,a,i,o,u);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,t,n,s,a,i,o,u){let c=this._getExecutionOrder(s),l=Date.now(),d=o?{...a,metadata:o}:a,f={id:n,name:u??e.id[e.id.length-1],parent_run_id:s,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{messages:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(f)}async handleChatModelStart(e,t,n,s,a,i,o,u){let c=this.getRunById(n)??this._createRunForChatModelStart(e,t,n,s,a,i,o,u);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,t,n,s,a){let i=this.getRunById(t);if(!i||i?.run_type!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.outputs=e,i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...a},await this.onLLMEnd?.(i),await this._endTrace(i),i}async handleLLMError(e,t,n,s,a){let i=this.getRunById(t);if(!i||i?.run_type!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...a},await this.onLLMError?.(i),await this._endTrace(i),i}_createRunForChainStart(e,t,n,s,a,i,o,u){let c=this._getExecutionOrder(s),l=Date.now(),d={id:n,name:u??e.id[e.id.length-1],parent_run_id:s,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:t,execution_order:c,child_execution_order:c,run_type:o??"chain",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(d)}async handleChainStart(e,t,n,s,a,i,o,u){let c=this.getRunById(n)??this._createRunForChainStart(e,t,n,s,a,i,o,u);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,t,n,s,a){let i=this.getRunById(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=Ep(e,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),a?.inputs!==void 0&&(i.inputs=Ep(a.inputs,"input")),await this.onChainEnd?.(i),await this._endTrace(i),i}async handleChainError(e,t,n,s,a){let i=this.getRunById(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),a?.inputs!==void 0&&(i.inputs=Ep(a.inputs,"input")),await this.onChainError?.(i),await this._endTrace(i),i}_createRunForToolStart(e,t,n,s,a,i,o){let u=this._getExecutionOrder(s),c=Date.now(),l={id:n,name:o??e.id[e.id.length-1],parent_run_id:s,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:t},execution_order:u,child_execution_order:u,run_type:"tool",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(l)}async handleToolStart(e,t,n,s,a,i,o){let u=this.getRunById(n)??this._createRunForToolStart(e,t,n,s,a,i,o);return await this.onRunCreate?.(u),await this.onToolStart?.(u),u}async handleToolEnd(e,t){let n=this.getRunById(t);if(!n||n?.run_type!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.outputs={output:e},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await this.onToolEnd?.(n),await this._endTrace(n),n}async handleToolError(e,t){let n=this.getRunById(t);if(!n||n?.run_type!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await this.onToolError?.(n),await this._endTrace(n),n}async handleAgentAction(e,t){let n=this.getRunById(t);if(!n||n?.run_type!=="chain")return;let s=n;s.actions=s.actions||[],s.actions.push(e),s.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(n)}async handleAgentEnd(e,t){let n=this.getRunById(t);!n||n?.run_type!=="chain"||(n.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(n))}_createRunForRetrieverStart(e,t,n,s,a,i,o){let u=this._getExecutionOrder(s),c=Date.now(),l={id:n,name:o??e.id[e.id.length-1],parent_run_id:s,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:t},execution_order:u,child_execution_order:u,run_type:"retriever",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(e,t,n,s,a,i,o){let u=this.getRunById(n)??this._createRunForRetrieverStart(e,t,n,s,a,i,o);return await this.onRunCreate?.(u),await this.onRetrieverStart?.(u),u}async handleRetrieverEnd(e,t){let n=this.getRunById(t);if(!n||n?.run_type!=="retriever")throw new Error("No retriever run to end");return n.end_time=Date.now(),n.outputs={documents:e},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await this.onRetrieverEnd?.(n),await this._endTrace(n),n}async handleRetrieverError(e,t){let n=this.getRunById(t);if(!n||n?.run_type!=="retriever")throw new Error("No retriever run to end");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await this.onRetrieverError?.(n),await this._endTrace(n),n}async handleText(e,t){let n=this.getRunById(t);!n||n?.run_type!=="chain"||(n.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(n))}async handleLLMNewToken(e,t,n,s,a,i){let o=this.getRunById(n);if(!o||o?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return o.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:i?.chunk}}),await this.onLLMNewToken?.(o,e,{chunk:i?.chunk}),o}}});var Pb=D((O1,Tb)=>{"use strict";var Ob=(r=0)=>e=>`\x1B[${38+r};5;${e}m`,Ib=(r=0)=>(e,t,n)=>`\x1B[${38+r};2;${e};${t};${n}m`;function bP(){let r=new Map,e={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]}};e.color.gray=e.color.blackBright,e.bgColor.bgGray=e.bgColor.bgBlackBright,e.color.grey=e.color.blackBright,e.bgColor.bgGrey=e.bgColor.bgBlackBright;for(let[t,n]of Object.entries(e)){for(let[s,a]of Object.entries(n))e[s]={open:`\x1B[${a[0]}m`,close:`\x1B[${a[1]}m`},n[s]=e[s],r.set(a[0],a[1]);Object.defineProperty(e,t,{value:n,enumerable:!1})}return Object.defineProperty(e,"codes",{value:r,enumerable:!1}),e.color.close="\x1B[39m",e.bgColor.close="\x1B[49m",e.color.ansi256=Ob(),e.color.ansi16m=Ib(),e.bgColor.ansi256=Ob(10),e.bgColor.ansi16m=Ib(10),Object.defineProperties(e,{rgbToAnsi256:{value:(t,n,s)=>t===n&&n===s?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(s/255*5),enumerable:!1},hexToRgb:{value:t=>{let n=/(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(t.toString(16));if(!n)return[0,0,0];let{colorString:s}=n.groups;s.length===3&&(s=s.split("").map(i=>i+i).join(""));let a=Number.parseInt(s,16);return[a>>16&255,a>>8&255,a&255]},enumerable:!1},hexToAnsi256:{value:t=>e.rgbToAnsi256(...e.hexToRgb(t)),enumerable:!1}}),e}Object.defineProperty(Tb,"exports",{enumerable:!0,get:bP})});function We(r,e){return`${r.open}${e}${r.close}`}function kt(r,e){try{return JSON.stringify(r,null,2)}catch{return e}}function Sb(r){return typeof r=="string"?r.trim():r==null?r:kt(r,r.toString())}function on(r){if(!r.end_time)return"";let e=r.end_time-r.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}var Op,it,Hi,kb=_(()=>{"use strict";Op=Dt(Pb(),1);us();({color:it}=Op.default),Hi=class extends St{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"console_callback_handler"})}persistRun(e){return Promise.resolve()}getParents(e){let t=[],n=e;for(;n.parent_run_id;){let s=this.runMap.get(n.parent_run_id);if(s)t.push(s),n=s;else break}return t}getBreadcrumbs(e){let n=[...this.getParents(e).reverse(),e].map((s,a,i)=>{let o=`${s.execution_order}:${s.run_type}:${s.name}`;return a===i.length-1?We(Op.default.bold,o):o}).join(" > ");return We(it.grey,n)}onChainStart(e){let t=this.getBreadcrumbs(e);console.log(`${We(it.green,"[chain/start]")} [${t}] Entering Chain run with input: ${kt(e.inputs,"[inputs]")}`)}onChainEnd(e){let t=this.getBreadcrumbs(e);console.log(`${We(it.cyan,"[chain/end]")} [${t}] [${on(e)}] Exiting Chain run with output: ${kt(e.outputs,"[outputs]")}`)}onChainError(e){let t=this.getBreadcrumbs(e);console.log(`${We(it.red,"[chain/error]")} [${t}] [${on(e)}] Chain run errored with error: ${kt(e.error,"[error]")}`)}onLLMStart(e){let t=this.getBreadcrumbs(e),n="prompts"in e.inputs?{prompts:e.inputs.prompts.map(s=>s.trim())}:e.inputs;console.log(`${We(it.green,"[llm/start]")} [${t}] Entering LLM run with input: ${kt(n,"[inputs]")}`)}onLLMEnd(e){let t=this.getBreadcrumbs(e);console.log(`${We(it.cyan,"[llm/end]")} [${t}] [${on(e)}] Exiting LLM run with output: ${kt(e.outputs,"[response]")}`)}onLLMError(e){let t=this.getBreadcrumbs(e);console.log(`${We(it.red,"[llm/error]")} [${t}] [${on(e)}] LLM run errored with error: ${kt(e.error,"[error]")}`)}onToolStart(e){let t=this.getBreadcrumbs(e);console.log(`${We(it.green,"[tool/start]")} [${t}] Entering Tool run with input: "${Sb(e.inputs.input)}"`)}onToolEnd(e){let t=this.getBreadcrumbs(e);console.log(`${We(it.cyan,"[tool/end]")} [${t}] [${on(e)}] Exiting Tool run with output: "${Sb(e.outputs?.output)}"`)}onToolError(e){let t=this.getBreadcrumbs(e);console.log(`${We(it.red,"[tool/error]")} [${t}] [${on(e)}] Tool run errored with error: ${kt(e.error,"[error]")}`)}onRetrieverStart(e){let t=this.getBreadcrumbs(e);console.log(`${We(it.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${kt(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){let t=this.getBreadcrumbs(e);console.log(`${We(it.cyan,"[retriever/end]")} [${t}] [${on(e)}] Exiting Retriever run with output: ${kt(e.outputs,"[outputs]")}`)}onRetrieverError(e){let t=this.getBreadcrumbs(e);console.log(`${We(it.red,"[retriever/error]")} [${t}] [${on(e)}] Retriever run errored with error: ${kt(e.error,"[error]")}`)}onAgentAction(e){let t=e,n=this.getBreadcrumbs(e);console.log(`${We(it.blue,"[agent/action]")} [${n}] Agent selected action: ${kt(t.actions[t.actions.length-1],"[action]")}`)}}});function un(r,e){return r.lc_error_code=e,r.message=`${r.message}
39
+
40
+ Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
41
+ `,r}var Ki=_(()=>{"use strict"});function cn(r){return!!(r&&typeof r=="object"&&"type"in r&&r.type==="tool_call")}function Rb(r){return!!(r&&typeof r=="object"&&"toolCall"in r&&r.toolCall!=null&&typeof r.toolCall=="object"&&"id"in r.toolCall&&typeof r.toolCall.id=="string")}var cs,pc=_(()=>{"use strict";cs=class extends Error{constructor(e,t){super(e),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=t}}});function Ip(r,e=la){r=r.trim();let t=r.indexOf("```");if(t===-1)return e(r);let n=r.substring(t+3);n.startsWith(`json
42
+ `)?n=n.substring(5):n.startsWith("json")?n=n.substring(4):n.startsWith(`
43
+ `)&&(n=n.substring(1));let s=n.indexOf("```"),a=n;return s!==-1&&(a=n.substring(0,s)),e(a.trim())}function la(r){if(typeof r>"u")return null;try{return JSON.parse(r)}catch{}let e="",t=[],n=!1,s=!1;for(let a of r){if(n)a==='"'&&!s?n=!1:a===`
44
+ `&&!s?a="\\n":a==="\\"?s=!s:s=!1;else if(a==='"')n=!0,s=!1;else if(a==="{")t.push("}");else if(a==="[")t.push("]");else if(a==="}"||a==="]")if(t&&t[t.length-1]===a)t.pop();else return null;e+=a}n&&(e+='"');for(let a=t.length-1;a>=0;a-=1)e+=t[a];try{return JSON.parse(e)}catch{return null}}var Tp=_(()=>{"use strict"});function jr(r){return typeof r=="object"&&r!==null&&"type"in r&&typeof r.type=="string"&&"source_type"in r&&(r.source_type==="url"||r.source_type==="base64"||r.source_type==="text"||r.source_type==="id")}function Cb(r){return jr(r)&&r.source_type==="url"&&"url"in r&&typeof r.url=="string"}function $b(r){return jr(r)&&r.source_type==="base64"&&"data"in r&&typeof r.data=="string"}function Nb(r){if(jr(r)){if(r.source_type==="url")return{type:"image_url",image_url:{url:r.url}};if(r.source_type==="base64"){if(!r.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${r.mime_type};base64,${r.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function Pp(r){let e=r.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${r}" - does not match type/subtype format.`);let t=e[0].trim(),n=e[1].trim();if(t===""||n==="")throw new Error(`Invalid mime type: "${r}" - type or subtype is empty.`);let s={};for(let a of r.split(";").slice(1)){let i=a.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${r}".`);let o=i[0].trim(),u=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${r}".`);s[o]=u}return{type:t,subtype:n,parameters:s}}function Sp({dataUrl:r,asTypedArray:e=!1}){let t=r.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),n;if(t){n=t[1].toLowerCase();let s=e?Uint8Array.from(atob(t[2]),a=>a.charCodeAt(0)):t[2];return{mime_type:n,data:s}}}function kp(r,e){if(r.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(r)}if(r.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(r)}if(r.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(r)}if(r.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(r)}throw new Error(`Unable to convert content block type '${r.type}' to provider-specific format: not recognized.`)}var Rp=_(()=>{"use strict"});function Rt(r,e){return typeof r=="string"?r===""?e:typeof e=="string"?r+e:Array.isArray(e)&&e.some(t=>jr(t))?[{type:"text",source_type:"text",text:r},...e]:[{type:"text",text:r},...e]:Array.isArray(e)?Wi(r,e)??[...r,...e]:e===""?r:Array.isArray(r)&&r.some(t=>jr(t))?[...r,{type:"file",source_type:"text",text:e}]:[...r,{type:"text",text:e}]}function jb(r,e){return r==="error"||e==="error"?"error":"success"}function wP(r,e){function t(n,s){if(typeof n!="object"||n===null||n===void 0)return n;if(s>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(i=>t(i,s+1));let a={};for(let i of Object.keys(n))a[i]=t(n[i],s+1);return a}return JSON.stringify(t(r,0),null,2)}function ve(r,e){let t={...r};for(let[n,s]of Object.entries(e))if(t[n]==null)t[n]=s;else{if(s==null)continue;if(typeof t[n]!=typeof s||Array.isArray(t[n])!==Array.isArray(s))throw new Error(`field[${n}] already exists in the message chunk, but with a different type.`);if(typeof t[n]=="string"){if(n==="type")continue;["id","name","output_version","model_provider"].includes(n)?t[n]=s:t[n]+=s}else if(typeof t[n]=="object"&&!Array.isArray(t[n]))t[n]=ve(t[n],s);else if(Array.isArray(t[n]))t[n]=Wi(t[n],s);else{if(t[n]===s)continue;console.warn(`field[${n}] already exists in this message chunk and value has unsupported type.`)}}return t}function Wi(r,e){if(!(r===void 0&&e===void 0)){if(r===void 0||e===void 0)return r||e;{let t=[...r];for(let n of e)if(typeof n=="object"&&n!==null&&"index"in n&&typeof n.index=="number"){let s=t.findIndex(a=>{let i=typeof a=="object",o="index"in a&&a.index===n.index,u="id"in a&&"id"in n&&a?.id===n?.id,c=!("id"in a)||!a?.id||!("id"in n)||!n?.id;return i&&o&&(u||c)});s!==-1&&typeof t[s]=="object"&&t[s]!==null?t[s]=ve(t[s],n):t.push(n)}else{if(typeof n=="object"&&n!==null&&"text"in n&&n.text==="")continue;t.push(n)}return t}}}function Mb(r,e){if(!r&&!e)throw new Error("Cannot merge two undefined objects.");if(!r||!e)return r||e;if(typeof r!=typeof e)throw new Error(`Cannot merge objects of different types.
45
+ Left ${typeof r}
46
+ Right ${typeof e}`);if(typeof r=="string"&&typeof e=="string")return r+e;if(Array.isArray(r)&&Array.isArray(e))return Wi(r,e);if(typeof r=="object"&&typeof e=="object")return ve(r,e);if(r===e)return r;throw new Error(`Can not merge objects of different types.
47
+ Left ${r}
48
+ Right ${e}`)}function zb(r){return typeof r.role=="string"}function cr(r){return typeof r?._getType=="function"}function Cp(r){return cr(r)&&typeof r.concat=="function"}var Ie,ot,Ct=_(()=>{"use strict";qi();Rp();Ie=class extends Bt{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}getType(){return this._getType()}constructor(e,t){typeof e=="string"&&(e={content:e,additional_kwargs:t,response_metadata:{}}),e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","messages"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"content",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"additional_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.content=e.content,this.additional_kwargs=e.additional_kwargs,this.response_metadata=e.response_metadata,this.id=e.id}toDict(){return{type:this._getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;let t=wP(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}};ot=class extends Ie{}});function Lb(r){return r!=null&&typeof r=="object"&&"lc_direct_tool_output"in r&&r.lc_direct_tool_output===!0}function Db(r){let e=[],t=[];for(let n of r)if(n.function){let s=n.function.name;try{let a=JSON.parse(n.function.arguments),i={name:s||"",args:a||{},id:n.id};e.push(i)}catch{t.push({name:s,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,t]}var Mr,da,pa=_(()=>{"use strict";Ct();Mr=class extends Ie{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}constructor(e,t,n){typeof e=="string"&&(e={content:e,name:n,tool_call_id:t}),super(e),Object.defineProperty(this,"lc_direct_tool_output",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status,this.metadata=e.metadata}_getType(){return"tool"}static isInstance(e){return e._getType()==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},da=class r extends ot{constructor(e){super(e),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}_getType(){return"tool"}concat(e){return new r({content:Rt(this.content,e.content),additional_kwargs:ve(this.additional_kwargs,e.additional_kwargs),response_metadata:ve(this.response_metadata,e.response_metadata),artifact:Mb(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:jb(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}});function ln(r){return r._getType()==="ai"}function $p(r){return r._getType()==="ai"}var Je,ht,ls=_(()=>{"use strict";Tp();Ct();pa();Je=class extends Ie{get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(e,t){let n;if(typeof e=="string")n={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:t??{}};else{n=e;let s=n.additional_kwargs?.tool_calls,a=n.tool_calls;s!=null&&s.length>0&&(a===void 0||a.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
49
+
50
+ Please upgrade your packages to versions that set`,"message tool calls. e.g., `yarn add @langchain/anthropic`,","yarn add @langchain/openai`, etc."].join(" "));try{if(s!=null&&a===void 0){let[i,o]=Db(s);n.tool_calls=i??[],n.invalid_tool_calls=o??[]}else n.tool_calls=n.tool_calls??[],n.invalid_tool_calls=n.invalid_tool_calls??[]}catch{n.tool_calls=[],n.invalid_tool_calls=[]}}super(n),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof n!="string"&&(this.tool_calls=n.tool_calls??this.tool_calls,this.invalid_tool_calls=n.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=n.usage_metadata}static lc_name(){return"AIMessage"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}};ht=class r extends ot{constructor(e){let t;if(typeof e=="string")t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{let n=e.tool_call_chunks.reduce((i,o)=>{let u=i.findIndex(([c])=>"id"in o&&o.id&&"index"in o&&o.index!==void 0?o.id===c.id&&o.index===c.index:"id"in o&&o.id?o.id===c.id:"index"in o&&o.index!==void 0?o.index===c.index:!1);return u!==-1?i[u].push(o):i.push([o]),i},[]),s=[],a=[];for(let i of n){let o={},u=i[0]?.name??"",c=i.map(f=>f.args||"").join(""),l=c.length?c:"{}",d=i[0]?.id;try{if(o=la(l),!d||o===null||typeof o!="object"||Array.isArray(o))throw new Error("Malformed tool call chunk args.");s.push({name:u,args:o,id:d,type:"tool_call"})}catch{a.push({name:u,args:l,id:d,error:"Malformed args.",type:"invalid_tool_call"})}}t={...e,tool_calls:s,invalid_tool_calls:a,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(t),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tool_call_chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){let t={content:Rt(this.content,e.content),additional_kwargs:ve(this.additional_kwargs,e.additional_kwargs),response_metadata:ve(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){let n=Wi(this.tool_call_chunks,e.tool_call_chunks);n!==void 0&&n.length>0&&(t.tool_call_chunks=n)}if(this.usage_metadata!==void 0||e.usage_metadata!==void 0){let n={...(this.usage_metadata?.input_token_details?.audio!==void 0||e.usage_metadata?.input_token_details?.audio!==void 0)&&{audio:(this.usage_metadata?.input_token_details?.audio??0)+(e.usage_metadata?.input_token_details?.audio??0)},...(this.usage_metadata?.input_token_details?.cache_read!==void 0||e.usage_metadata?.input_token_details?.cache_read!==void 0)&&{cache_read:(this.usage_metadata?.input_token_details?.cache_read??0)+(e.usage_metadata?.input_token_details?.cache_read??0)},...(this.usage_metadata?.input_token_details?.cache_creation!==void 0||e.usage_metadata?.input_token_details?.cache_creation!==void 0)&&{cache_creation:(this.usage_metadata?.input_token_details?.cache_creation??0)+(e.usage_metadata?.input_token_details?.cache_creation??0)}},s={...(this.usage_metadata?.output_token_details?.audio!==void 0||e.usage_metadata?.output_token_details?.audio!==void 0)&&{audio:(this.usage_metadata?.output_token_details?.audio??0)+(e.usage_metadata?.output_token_details?.audio??0)},...(this.usage_metadata?.output_token_details?.reasoning!==void 0||e.usage_metadata?.output_token_details?.reasoning!==void 0)&&{reasoning:(this.usage_metadata?.output_token_details?.reasoning??0)+(e.usage_metadata?.output_token_details?.reasoning??0)}},a=this.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},i=e.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},o={input_tokens:a.input_tokens+i.input_tokens,output_tokens:a.output_tokens+i.output_tokens,total_tokens:a.total_tokens+i.total_tokens,...Object.keys(n).length>0&&{input_token_details:n},...Object.keys(s).length>0&&{output_token_details:s}};t.usage_metadata=o}return new r(t)}}});var Zt,ds,fc=_(()=>{"use strict";Ct();Zt=class r extends Ie{static lc_name(){return"ChatMessage"}static _chatMessageClass(){return r}constructor(e,t){typeof e=="string"&&(e={content:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){return"generic"}static isInstance(e){return e._getType()==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},ds=class r extends ot{static lc_name(){return"ChatMessageChunk"}constructor(e,t){typeof e=="string"&&(e={content:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){return"generic"}concat(e){return new r({content:Rt(this.content,e.content),additional_kwargs:ve(this.additional_kwargs,e.additional_kwargs),response_metadata:ve(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}get _printableFields(){return{...super._printableFields,role:this.role}}}});var ps,mc=_(()=>{"use strict";Ct();ps=class r extends ot{static lc_name(){return"FunctionMessageChunk"}_getType(){return"function"}concat(e){return new r({content:Rt(this.content,e.content),additional_kwargs:ve(this.additional_kwargs,e.additional_kwargs),response_metadata:ve(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}}});var ut,fs,Ji=_(()=>{"use strict";Ct();ut=class extends Ie{static lc_name(){return"HumanMessage"}_getType(){return"human"}constructor(e,t){super(e,t)}},fs=class r extends ot{static lc_name(){return"HumanMessageChunk"}_getType(){return"human"}constructor(e,t){super(e,t)}concat(e){return new r({content:Rt(this.content,e.content),additional_kwargs:ve(this.additional_kwargs,e.additional_kwargs),response_metadata:ve(this.response_metadata,e.response_metadata),id:this.id??e.id})}}});var Xi,hc=_(()=>{"use strict";Ct();Xi=class extends Ie{constructor(e){super({...e,content:""}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.id=e.id}_getType(){return"remove"}get _printableFields(){return{...super._printableFields,id:this.id}}}});var dn,pn,gc=_(()=>{"use strict";Ct();dn=class extends Ie{static lc_name(){return"SystemMessage"}_getType(){return"system"}constructor(e,t){super(e,t)}},pn=class r extends ot{static lc_name(){return"SystemMessageChunk"}_getType(){return"system"}constructor(e,t){super(e,t)}concat(e){return new r({content:Rt(this.content,e.content),additional_kwargs:ve(this.additional_kwargs,e.additional_kwargs),response_metadata:ve(this.response_metadata,e.response_metadata),id:this.id??e.id})}}});function xP(r){return cn(r)?r:typeof r.id=="string"&&r.type==="function"&&typeof r.function=="object"&&r.function!==null&&"arguments"in r.function&&typeof r.function.arguments=="string"&&"name"in r.function&&typeof r.function.name=="string"?{id:r.id,args:JSON.parse(r.function.arguments),name:r.function.name,type:"tool_call"}:r}function EP(r){return typeof r=="object"&&r!=null&&r.lc===1&&Array.isArray(r.id)&&r.kwargs!=null&&typeof r.kwargs=="object"}function Np(r){let e,t;if(EP(r)){let n=r.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",t=r.kwargs}else{let{type:n,...s}=r;e=n,t=s}if(e==="human"||e==="user")return new ut(t);if(e==="ai"||e==="assistant"){let{tool_calls:n,...s}=t;if(!Array.isArray(n))return new Je(t);let a=n.map(xP);return new Je({...s,tool_calls:a})}else{if(e==="system")return new dn(t);if(e==="developer")return new dn({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in t)return new Mr({...t,content:t.content,tool_call_id:t.tool_call_id,name:t.name});if(e==="remove"&&"id"in t&&typeof t.id=="string")return new Xi({...t,id:t.id});throw un(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
51
+
52
+ Received: ${JSON.stringify(r,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Vt(r){if(typeof r=="string")return new ut(r);if(cr(r))return r;if(Array.isArray(r)){let[e,t]=r;return Np({type:e,content:t})}else if(zb(r)){let{role:e,...t}=r;return Np({...t,type:e})}else return Np(r)}function Yi(r,e="Human",t="AI"){let n=[];for(let s of r){let a;if(s._getType()==="human")a=e;else if(s._getType()==="ai")a=t;else if(s._getType()==="system")a="System";else if(s._getType()==="function")a="Function";else if(s._getType()==="tool")a="Tool";else if(s._getType()==="generic")a=s.role;else throw new Error(`Got unsupported message type: ${s._getType()}`);let i=s.name?`${s.name}, `:"",o=typeof s.content=="string"?s.content:JSON.stringify(s.content,null,2);n.push(`${a}: ${i}${o}`)}return n.join(`
53
+ `)}function jp(r){let e=r._getType();if(e==="human")return new fs({...r});if(e==="ai"){let t={...r};return"tool_calls"in t&&(t={...t,tool_call_chunks:t.tool_calls?.map(n=>({...n,type:"tool_call_chunk",index:void 0,args:JSON.stringify(n.args)}))}),new ht({...t})}else{if(e==="system")return new pn({...r});if(e==="function")return new ps({...r});if(Zt.isInstance(r))return new ds({...r});throw new Error("Unknown message type.")}}var fn=_(()=>{"use strict";Ki();pc();ls();Ct();fc();mc();Ji();hc();gc();pa()});var _c=_(()=>{"use strict";Lu()});var Mp,zp,Lp=_(()=>{"use strict";_c();is();zp=()=>{if(Mp===void 0){let r=we("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};Mp=new ss(r)}return Mp}});var fa,Fb=_(()=>{"use strict";_c();dc();md();us();Lp();fa=class r extends St{constructor(e={}){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"usesRunTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:!0});let{exampleId:t,projectName:n,client:s,replicas:a}=e;this.projectName=n??Ni(),this.replicas=a,this.exampleId=t,this.client=s??zp();let i=r.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 t=e,n=new Set;for(;t.parent_run&&!(n.has(t.id)||(n.add(t.id),!t.parent_run));)t=t.parent_run;n.clear();let s=[t];for(;s.length>0;){let a=s.shift();!a||n.has(a.id)||(n.add(a.id),this.runTreeMap.set(a.id,a),a.child_runs&&s.push(...a.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){let t=this.runTreeMap.get(e);if(t)return new Ut({...t,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return Yh(!0)}catch{return}}}});var Ub,ms,Bb,mn,Qi=_(()=>{"use strict";Ub=Symbol.for("ls:tracing_async_local_storage"),ms=Symbol.for("lc:context_variables"),Bb=r=>{globalThis[Ub]=r},mn=()=>globalThis[Ub]});function AP(){let r="default"in yc.default?yc.default.default:yc.default;return new r({autoStart:!0,concurrency:1})}function OP(){return typeof eo>"u"&&(eo=AP()),eo}async function xe(r,e){if(e===!0){let t=mn();t!==void 0?await t.run(void 0,async()=>r()):await r()}else eo=OP(),eo.add(async()=>{let t=mn();t!==void 0?await t.run(void 0,async()=>r()):await r()})}var yc,eo,Zb=_(()=>{"use strict";yc=Dt(Hu(),1);Qi();Lp()});var Vb=_(()=>{"use strict";Zb()});var qb,Gb=_(()=>{"use strict";is();qb=r=>r!==void 0?r:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(t=>we(t)==="true")});function Dp(r){let e=mn();return e===void 0?void 0:e.getStore()?.[ms]?.[r]}var IP,Hb,Kb=_(()=>{"use strict";dc();Qi();IP=Symbol("lc:configure_hooks"),Hb=()=>Dp(IP)||[]});function Wb(r){return r?Array.isArray(r)||"name"in r?{callbacks:r}:r:{}}function to(r){return"name"in r?r:os.fromMethods(r)}var Fp,ma,Up,bc,Bp,Zp,Le,ha=_(()=>{"use strict";ts();Gi();kb();fn();is();Fb();Vb();Gb();us();Kb();Fp=class{setHandler(e){return this.setHandlers([e])}},ma=class{constructor(e,t,n,s,a,i,o,u){Object.defineProperty(this,"runId",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:o}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:u})}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>xe(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}async handleCustomEvent(e,t,n,s,a){await Promise.all(this.handlers.map(i=>xe(async()=>{try{await i.handleCustomEvent?.(e,t,this.runId,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)))}},Up=class extends ma{getChild(e){let t=new Le(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>xe(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw n}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>xe(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${n}`),t.raiseError)throw e}},t.awaitHandlers)))}},bc=class extends ma{async handleLLMNewToken(e,t,n,s,a,i){await Promise.all(this.handlers.map(o=>xe(async()=>{if(!o.ignoreLLM)try{await o.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,i)}catch(u){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleLLMNewToken: ${u}`),o.raiseError)throw u}},o.awaitHandlers)))}async handleLLMError(e,t,n,s,a){await Promise.all(this.handlers.map(i=>xe(async()=>{if(!i.ignoreLLM)try{await i.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,a)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMError: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleLLMEnd(e,t,n,s,a){await Promise.all(this.handlers.map(i=>xe(async()=>{if(!i.ignoreLLM)try{await i.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,a)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMEnd: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}},Bp=class extends ma{getChild(e){let t=new Le(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,n,s,a){await Promise.all(this.handlers.map(i=>xe(async()=>{if(!i.ignoreChain)try{await i.handleChainError?.(e,this.runId,this._parentRunId,this.tags,a)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainError: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleChainEnd(e,t,n,s,a){await Promise.all(this.handlers.map(i=>xe(async()=>{if(!i.ignoreChain)try{await i.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,a)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainEnd: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>xe(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>xe(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}},Zp=class extends ma{getChild(e){let t=new Le(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>xe(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>xe(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}},Le=class r extends Fp{constructor(e,t){super(),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"callback_manager"}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.handlers=t?.handlers??this.handlers,this.inheritableHandlers=t?.inheritableHandlers??this.inheritableHandlers,this.tags=t?.tags??this.tags,this.inheritableTags=t?.inheritableTags??this.inheritableTags,this.metadata=t?.metadata??this.metadata,this.inheritableMetadata=t?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,t,n=void 0,s=void 0,a=void 0,i=void 0,o=void 0,u=void 0){return Promise.all(t.map(async(c,l)=>{let d=l===0&&n?n:_e();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return ca(f)&&f._createRunForLLMStart(e,[c],d,this._parentRunId,a,this.tags,this.metadata,u),xe(async()=>{try{await f.handleLLMStart?.(e,[c],d,this._parentRunId,a,this.tags,this.metadata,u)}catch(p){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${p}`),f.raiseError)throw p}},f.awaitHandlers)})),new bc(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,n=void 0,s=void 0,a=void 0,i=void 0,o=void 0,u=void 0){return Promise.all(t.map(async(c,l)=>{let d=l===0&&n?n:_e();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return ca(f)&&f._createRunForChatModelStart(e,[c],d,this._parentRunId,a,this.tags,this.metadata,u),xe(async()=>{try{if(f.handleChatModelStart)await f.handleChatModelStart?.(e,[c],d,this._parentRunId,a,this.tags,this.metadata,u);else if(f.handleLLMStart){let p=Yi(c);await f.handleLLMStart?.(e,[p],d,this._parentRunId,a,this.tags,this.metadata,u)}}catch(p){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${p}`),f.raiseError)throw p}},f.awaitHandlers)})),new bc(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,n=_e(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreChain)return ca(u)&&u._createRunForChainStart(e,t,n,this._parentRunId,this.tags,this.metadata,s,o),xe(async()=>{try{await u.handleChainStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,s,o)}catch(c){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleChainStart: ${c}`),u.raiseError)throw c}},u.awaitHandlers)})),new Bp(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,n=_e(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreAgent)return ca(u)&&u._createRunForToolStart(e,t,n,this._parentRunId,this.tags,this.metadata,o),xe(async()=>{try{await u.handleToolStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,o)}catch(c){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleToolStart: ${c}`),u.raiseError)throw c}},u.awaitHandlers)})),new Zp(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,n=_e(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreRetriever)return ca(u)&&u._createRunForRetrieverStart(e,t,n,this._parentRunId,this.tags,this.metadata,o),xe(async()=>{try{await u.handleRetrieverStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,o)}catch(c){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleRetrieverStart: ${c}`),u.raiseError)throw c}},u.awaitHandlers)})),new Up(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,n,s,a){await Promise.all(this.handlers.map(i=>xe(async()=>{if(!i.ignoreCustomEvent)try{await i.handleCustomEvent?.(e,t,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,t=!0){this.handlers.push(e),t&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(t=>t!==e),this.inheritableHandlers=this.inheritableHandlers.filter(t=>t!==e)}setHandlers(e,t=!0){this.handlers=[],this.inheritableHandlers=[];for(let n of e)this.addHandler(n,t)}addTags(e,t=!0){this.removeTags(e),this.tags.push(...e),t&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(t=>!e.includes(t)),this.inheritableTags=this.inheritableTags.filter(t=>!e.includes(t))}addMetadata(e,t=!0){this.metadata={...this.metadata,...e},t&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(let t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(e=[],t=!0){let n=new r(this._parentRunId);for(let s of this.handlers){let a=this.inheritableHandlers.includes(s);n.addHandler(s,a)}for(let s of this.tags){let a=this.inheritableTags.includes(s);n.addTags([s],a)}for(let s of Object.keys(this.metadata)){let a=Object.keys(this.inheritableMetadata).includes(s);n.addMetadata({[s]:this.metadata[s]},a)}for(let s of e)n.handlers.filter(a=>a.name==="console_callback_handler").some(a=>a.name===s.name)||n.addHandler(s,t);return n}static fromHandlers(e){class t extends os{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:_e()}),Object.assign(this,e)}}let n=new this;return n.addHandler(new t),n}static configure(e,t,n,s,a,i,o){return this._configureSync(e,t,n,s,a,i,o)}static _configureSync(e,t,n,s,a,i,o){let u;(e||t)&&(Array.isArray(e)||!e?(u=new r,u.setHandlers(e?.map(to)??[],!0)):u=e,u=u.copy(Array.isArray(t)?t.map(to):t?.handlers,!1));let c=we("LANGCHAIN_VERBOSE")==="true"||o?.verbose,l=fa.getTraceableRunTree()?.tracingEnabled||qb(),d=l||(we("LANGCHAIN_TRACING")??!1);if(c||d){if(u||(u=new r),c&&!u.handlers.some(f=>f.name===Hi.prototype.name)){let f=new Hi;u.addHandler(f,!0)}if(d&&!u.handlers.some(f=>f.name==="langchain_tracer")&&l){let f=new fa;u.addHandler(f,!0)}if(l){let f=fa.getTraceableRunTree();f&&u._parentRunId===void 0&&(u._parentRunId=f.id,u.handlers.find(m=>m.name==="langchain_tracer")?.updateFromRunTree(f))}}for(let{contextVar:f,inheritable:p=!0,handlerClass:m,envVar:h}of Hb()){let g=h&&we(h)==="true"&&m,w,b=f!==void 0?Dp(f):void 0;b&&Ab(b)?w=b:g&&(w=new m({})),w!==void 0&&(u||(u=new r),u.handlers.some(x=>x.name===w.name)||u.addHandler(w,p))}return(n||s)&&u&&(u.addTags(n??[]),u.addTags(s??[],!1)),(a||i)&&u&&(u.addMetadata(a??{}),u.addMetadata(i??{},!1)),u}}});var wc,TP,Jb,Vp,Xe,Xb=_(()=>{"use strict";_c();Qi();ha();wc=class{getStore(){}run(e,t){return t()}enterWith(e){}},TP=new wc,Jb=Symbol.for("lc:child_config"),Vp=class{getInstance(){return mn()??TP}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[Jb]}runWithConfig(e,t,n){let s=Le._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),a=this.getInstance(),i=a.getStore(),o=s?.getParentRunId(),u=s?.handlers?.find(l=>l?.name==="langchain_tracer"),c;return u&&o?c=u.getRunTreeWithTracingConfig(o):n||(c=new Ut({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[Jb]:e}),i!==void 0&&i[ms]!==void 0&&(c===void 0&&(c={}),c[ms]=i[ms]),a.run(c,t)}initializeGlobalInstance(e){mn()===void 0&&Bb(e)}},Xe=new Vp});var hs=_(()=>{"use strict";Xb();Qi()});async function ct(r){return Le._configureSync(r?.callbacks,void 0,r?.tags,void 0,r?.metadata)}function ga(...r){let e={};for(let t of r.filter(n=>!!n))for(let n of Object.keys(t))if(n==="metadata")e[n]={...e[n],...t[n]};else if(n==="tags"){let s=e[n]??[];e[n]=[...new Set(s.concat(t[n]??[]))]}else if(n==="configurable")e[n]={...e[n],...t[n]};else if(n==="timeout")e.timeout===void 0?e.timeout=t.timeout:t.timeout!==void 0&&(e.timeout=Math.min(e.timeout,t.timeout));else if(n==="signal")e.signal===void 0?e.signal=t.signal:t.signal!==void 0&&("any"in AbortSignal?e.signal=AbortSignal.any([e.signal,t.signal]):e.signal=t.signal);else if(n==="callbacks"){let s=e.callbacks,a=t.callbacks;if(Array.isArray(a))if(!s)e.callbacks=a;else if(Array.isArray(s))e.callbacks=s.concat(a);else{let i=s.copy();for(let o of a)i.addHandler(to(o),!0);e.callbacks=i}else if(a)if(!s)e.callbacks=a;else if(Array.isArray(s)){let i=a.copy();for(let o of s)i.addHandler(to(o),!0);e.callbacks=i}else e.callbacks=new Le(a._parentRunId,{handlers:s.handlers.concat(a.handlers),inheritableHandlers:s.inheritableHandlers.concat(a.inheritableHandlers),tags:Array.from(new Set(s.tags.concat(a.tags))),inheritableTags:Array.from(new Set(s.inheritableTags.concat(a.inheritableTags))),metadata:{...s.metadata,...a.metadata}})}else{let s=n;e[s]=t[s]??e[s]}return e}function ue(r){let e=Xe.getRunnableConfig(),t={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){let{runId:n,runName:s,...a}=e;t=Object.entries(a).reduce((i,[o,u])=>(u!==void 0&&(i[o]=u),i),t)}if(r&&(t=Object.entries(r).reduce((n,[s,a])=>(a!==void 0&&(n[s]=a),n),t)),t?.configurable)for(let n of Object.keys(t.configurable))PP.has(typeof t.configurable[n])&&!t.metadata?.[n]&&(t.metadata||(t.metadata={}),t.metadata[n]=t.configurable[n]);if(t.timeout!==void 0){if(t.timeout<=0)throw new Error("Timeout must be a positive number");let n=AbortSignal.timeout(t.timeout);t.signal!==void 0?"any"in AbortSignal&&(t.signal=AbortSignal.any([t.signal,n])):t.signal=n,delete t.timeout}return t}function Ee(r={},{callbacks:e,maxConcurrency:t,recursionLimit:n,runName:s,configurable:a,runId:i}={}){let o=ue(r);return e!==void 0&&(delete o.runName,o.callbacks=e),n!==void 0&&(o.recursionLimit=n),t!==void 0&&(o.maxConcurrency=t),s!==void 0&&(o.runName=s),a!==void 0&&(o.configurable={...o.configurable,...a}),i!==void 0&&delete o.runId,o}function $t(r){return r?{configurable:r.configurable,recursionLimit:r.recursionLimit,callbacks:r.callbacks,tags:r.tags,metadata:r.metadata,maxConcurrency:r.maxConcurrency,timeout:r.timeout,signal:r.signal}:void 0}var vc,PP,zr=_(()=>{"use strict";ha();hs();vc=25;PP=new Set(["string","number","boolean"])});async function lr(r,e){if(e===void 0)return r;let t;return Promise.race([r.catch(n=>{if(!e?.aborted)throw n}),new Promise((n,s)=>{t=()=>{s(new Error("Aborted"))},e.addEventListener("abort",t),e.aborted&&s(new Error("Aborted"))})]).finally(()=>e.removeEventListener("abort",t))}var qp=_(()=>{"use strict"});function Gp(r,e=2){let t=Array.from({length:e},()=>[]);return t.map(async function*(s){for(;;)if(s.length===0){let a=await r.next();for(let i of t)i.push(a)}else{if(s[0].done)return;yield s.shift().value}})}function Dr(r,e){if(Array.isArray(r)&&Array.isArray(e))return r.concat(e);if(typeof r=="string"&&typeof e=="string")return r+e;if(typeof r=="number"&&typeof e=="number")return r+e;if("concat"in r&&typeof r.concat=="function")return r.concat(e);if(typeof r=="object"&&typeof e=="object"){let t={...r};for(let[n,s]of Object.entries(e))n in t&&!Array.isArray(t[n])?t[n]=Dr(t[n],s):t[n]=s;return t}else throw new Error(`Cannot concat ${typeof r} and ${typeof e}`)}async function Yb(r,e,t,n,...s){let a=new Lr({generator:e,startSetup:t,signal:n}),i=await a.setup;return{output:r(a,i,...s),setup:i}}var Ve,Lr,Fr=_(()=>{"use strict";zr();hs();qp();Ve=class r extends ReadableStream{constructor(){super(...arguments),Object.defineProperty(this,"reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{let 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){let e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){let t=this.reader.cancel();this.reader.releaseLock(),await t}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){let t=e.getReader();return new r({start(n){return s();function s(){return t.read().then(({done:a,value:i})=>{if(a){n.close();return}return n.enqueue(i),s()})}},cancel(){t.releaseLock()}})}static fromAsyncGenerator(e){return new r({async pull(t){let{value:n,done:s}=await e.next();s&&t.close(),t.enqueue(n)},async cancel(t){await e.return(t)}})}};Lr=class{constructor(e){Object.defineProperty(this,"generator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"setup",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signal",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResult",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResultUsed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,n)=>{Xe.runWithConfig($t(e.config),async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,n):this.firstResult.then(s=>t(void 0),n)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?Xe.runWithConfig($t(this.config),this.signal?async()=>lr(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}}});async function Qb(r,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.");let{inputs:t}=r;if(["retriever","llm","prompt"].includes(r.run_type))return t;if(!(Object.keys(t).length===1&&t?.input===""))return t.input}async function ew(r,e){let{outputs:t}=r;return e==="original"||["retriever","llm","prompt"].includes(r.run_type)?t:t!==void 0&&Object.keys(t).length===1&&t?.output!==void 0?t.output:t}function SP(r){return r!==void 0&&r.message!==void 0}var qt,ro,tw,no,rw=_(()=>{"use strict";gd();us();Fr();ls();qt=class{constructor(e){Object.defineProperty(this,"ops",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),n=an({},t);return new ro({ops:t,state:n[n.length-1].newDocument})}},ro=class r extends qt{constructor(e){super(e),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.state=e.state}concat(e){let t=this.ops.concat(e.ops),n=an(this.state,e.ops);return new r({ops:t,state:n[n.length-1].newDocument})}static fromRunLogPatch(e){let t=an({},e.ops);return new r({ops:e.ops,state:t[t.length-1].newDocument})}},tw=r=>r.name==="log_stream_tracer";no=class extends St{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schemaFormat",{enumerable:!0,configurable:!0,writable:!0,value:"original"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keyMapByRunId",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"counterMapByRunName",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"log_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Ve.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;let t=e.tags??[],n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(n=n||t.find(s=>this.includeTags?.includes(s))!==void 0),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(n=n&&t.every(s=>!this.excludeTags?.includes(s))),n}async*tapOutputIterable(e,t){for await(let n of t){if(e!==this.rootId){let s=this.keyMapByRunId[e];s&&await this.writer.write(new qt({ops:[{op:"add",path:`/logs/${s}/streamed_output/-`,value:n}]}))}yield n}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new qt({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;let t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;let n={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(n.inputs=await Qb(e,this._schemaFormat)),await this.writer.write(new qt({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:n}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(t===void 0)return;let n=[];this._schemaFormat==="streaming_events"&&n.push({op:"replace",path:`/logs/${t}/inputs`,value:await Qb(e,this._schemaFormat)}),n.push({op:"add",path:`/logs/${t}/final_output`,value:await ew(e,this._schemaFormat)}),e.end_time!==void 0&&n.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let s=new qt({ops:n});await this.writer.write(s)}finally{if(e.id===this.rootId){let t=new qt({ops:[{op:"replace",path:"/final_output",value:await ew(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,n){let s=this.keyMapByRunId[e.id];if(s===void 0)return;let a=e.inputs.messages!==void 0,i;a?SP(n?.chunk)?i=n?.chunk:i=new ht({id:`run-${e.id}`,content:t}):i=t;let o=new qt({ops:[{op:"add",path:`/logs/${s}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${s}/streamed_output/-`,value:i}]});await this.writer.write(o)}}});var xc,dr,Ur,_a=_(()=>{"use strict";xc="__run",dr=class r{constructor(e){Object.defineProperty(this,"text",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"generationInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new r({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}},Ur=class r extends dr{constructor(e){super(e),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.message=e.message}concat(e){return new r({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo},message:this.message.concat(e.message)})}}});function Ec({name:r,serialized:e}){return r!==void 0?r:e?.name!==void 0?e.name:e?.id!==void 0&&Array.isArray(e?.id)?e.id[e.id.length-1]:"Unnamed"}var nw,Ac,sw=_(()=>{"use strict";us();Fr();ls();_a();nw=r=>r.name==="event_stream_tracer",Ac=class extends St{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"runInfoMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"tappedPromises",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"event_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Ve.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let t=e.tags??[],n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(n=n||t.find(s=>this.includeTags?.includes(s))!==void 0),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(n=n&&t.every(s=>!this.excludeTags?.includes(s))),n}async*tapOutputIterable(e,t){let n=await t.next();if(n.done)return;let s=this.runInfoMap.get(e);if(s===void 0){yield n.value;return}function a(o,u){return o==="llm"&&typeof u=="string"?new dr({text:u}):u}let i=this.tappedPromises.get(e);if(i===void 0){let o;i=new Promise(u=>{o=u}),this.tappedPromises.set(e,i);try{let u={event:`on_${s.runType}_stream`,run_id:e,name:s.name,tags:s.tags,metadata:s.metadata,data:{}};await this.send({...u,data:{chunk:a(s.runType,n.value)}},s),yield n.value;for await(let c of t)s.runType!=="tool"&&s.runType!=="retriever"&&await this.send({...u,data:{chunk:a(s.runType,c)}},s),yield c}finally{o()}}else{yield n.value;for await(let o of t)yield o}}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){let n=this.tappedPromises.get(e.run_id);n!==void 0?n.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){let t=Ec(e),n=e.inputs.messages!==void 0?"chat_model":"llm",s={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:n,inputs:e.inputs};this.runInfoMap.set(e.id,s);let a=`on_${n}_start`;await this.send({event:a,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},s)}async onLLMNewToken(e,t,n){let s=this.runInfoMap.get(e.id),a,i;if(s===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(s.runType==="chat_model")i="on_chat_model_stream",n?.chunk===void 0?a=new ht({content:t,id:`run-${e.id}`}):a=n.chunk.message;else if(s.runType==="llm")i="on_llm_stream",n?.chunk===void 0?a=new dr({text:t}):a=n.chunk;else throw new Error(`Unexpected run type ${s.runType}`);await this.send({event:i,data:{chunk:a},run_id:e.id,name:s.name,tags:s.tags,metadata:s.metadata},s)}}async onLLMEnd(e){let t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let n;if(t===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let s=e.outputs?.generations,a;if(t.runType==="chat_model"){for(let i of s??[]){if(a!==void 0)break;a=i[0]?.message}n="on_chat_model_end"}else if(t.runType==="llm")a={generations:s?.map(i=>i.map(o=>({text:o.text,generationInfo:o.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},n="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:n,data:{output:a,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){let t=Ec(e),n=e.run_type??"chain",s={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type},a={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(a={},s.inputs={}):e.inputs.input!==void 0?(a.input=e.inputs.input,s.inputs=e.inputs.input):(a.input=e.inputs,s.inputs=e.inputs),this.runInfoMap.set(e.id,s),await this.send({event:`on_${n}_start`,data:a,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},s)}async onChainEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);let n=`on_${e.run_type}_end`,s=e.inputs??t.inputs??{},i={output:e.outputs?.output??e.outputs,input:s};s.input&&Object.keys(s).length===1&&(i.input=s.input,t.inputs=s.input),await this.sendEndEvent({event:n,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){let t=Ec(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,n),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},n)}async onToolEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);let n=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:n,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){let t=Ec(e),s={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,s),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},s)}async onRetrieverEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,n){let s=this.runInfoMap.get(n);if(s===void 0)throw new Error(`handleCustomEvent: Run ID ${n} not found in run map.`);await this.send({event:"on_custom_event",run_id:n,name:e,tags:s.tags,metadata:s.metadata,data:t},s)}async finish(){let e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}}});var aw,Oc,kP,RP,Br,so=_(()=>{"use strict";aw=Dt(Eu(),1),Oc=Dt(Hu(),1),kP=[400,401,402,403,404,405,406,407,409],RP=r=>{if(r.message.startsWith("Cancel")||r.message.startsWith("AbortError")||r.name==="AbortError"||r?.code==="ECONNABORTED")throw r;let e=r?.response?.status??r?.status;if(e&&kP.includes(+e))throw r;if(r?.error?.code==="insufficient_quota"){let t=new Error(r?.message);throw t.name="InsufficientQuotaError",t}},Br=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,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??RP;let t="default"in Oc.default?Oc.default.default:Oc.default;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>(0,aw.default)(()=>e(...t).catch(n=>{throw n instanceof Error?n:new Error(n)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){return e.signal?Promise.race([this.call(t,...n),new Promise((s,a)=>{e.signal?.addEventListener("abort",()=>{a(new Error("AbortError"))})})]):this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}}});var ao,iw=_(()=>{"use strict";us();ao=class extends St{constructor({config:e,onStart:t,onEnd:n,onError:s}){super({_awaitHandler:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RootListenersTracer"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnEnd",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.config=e,this.argOnStart=t,this.argOnEnd=n,this.argOnError=s}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}}});function io(r){return r?r.lc_runnable:!1}var Ic,Hp=_(()=>{"use strict";Ic=class{constructor(e){Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,s=e.tags??[];return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(t)),this.includeTags!==void 0&&(n=n||s.some(a=>this.includeTags?.includes(a))),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(n=n&&s.every(a=>!this.excludeTags?.includes(a))),n}}});function Kp(r){return r.replace(/[^a-zA-Z-_0-9]/g,"_")}function $P(r){let e="";for(let[t,n]of Object.entries(r))e+=` classDef ${t} ${n};
54
+ `;return e}function ow(r,e,t){let{firstNode:n,lastNode:s,nodeColors:a,withStyles:i=!0,curveStyle:o="linear",wrapLabelNWords:u=9}=t??{},c=i?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
55
+ graph TD;
56
+ `:`graph TD;
57
+ `;if(i){let p="default",m={[p]:"{0}({1})"};n!==void 0&&(m[n]="{0}([{1}]):::first"),s!==void 0&&(m[s]="{0}([{1}]):::last");for(let[h,g]of Object.entries(r)){let w=g.name.split(":").pop()??"",x=CP.some(P=>w.startsWith(P)&&w.endsWith(P))?`<p>${w}</p>`:w;Object.keys(g.metadata??{}).length&&(x+=`<hr/><small><em>${Object.entries(g.metadata??{}).map(([P,K])=>`${P} = ${K}`).join(`
58
+ `)}</em></small>`);let I=(m[h]??m[p]).replace("{0}",Kp(h)).replace("{1}",x);c+=` ${I}
59
+ `}}let l={};for(let p of e){let m=p.source.split(":"),h=p.target.split(":"),g=m.filter((w,b)=>w===h[b]).join(":");l[g]||(l[g]=[]),l[g].push(p)}let d=new Set;function f(p,m){let h=p.length===1&&p[0].source===p[0].target;if(m&&!h){let g=m.split(":").pop();if(d.has(g))throw new Error(`Found duplicate subgraph '${g}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(g),c+=` subgraph ${g}
60
+ `}for(let g of p){let{source:w,target:b,data:x,conditional:I}=g,P="";if(x!==void 0){let K=x,V=K.split(" ");V.length>u&&(K=Array.from({length:Math.ceil(V.length/u)},(Z,oe)=>V.slice(oe*u,(oe+1)*u).join(" ")).join("&nbsp;<br>&nbsp;")),P=I?` -. &nbsp;${K}&nbsp; .-> `:` -- &nbsp;${K}&nbsp; --> `}else P=I?" -.-> ":" --> ";c+=` ${Kp(w)}${P}${Kp(b)};
61
+ `}for(let g in l)g.startsWith(`${m}:`)&&g!==m&&f(l[g],g);m&&!h&&(c+=` end
62
+ `)}f(l[""]??[],"");for(let p in l)!p.includes(":")&&p!==""&&f(l[p],p);return i&&(c+=$P(a??{})),c}async function uw(r,e){return NP(r,{...e,imageType:"png"})}async function NP(r,e){let t=e?.backgroundColor??"white",n=e?.imageType??"png",s=btoa(r);t!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(t)||(t=`!${t}`));let a=`https://mermaid.ink/img/${s}?bgColor=${t}&type=${n}`,i=await fetch(a);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(`
63
+ `));return await i.blob()}var CP,cw=_(()=>{"use strict";CP=["*","_","`"]});function ya(r,e,t){function n(o,u){var c;Object.defineProperty(o,"_zod",{value:o._zod??{},enumerable:!1}),(c=o._zod).traits??(c.traits=new Set),o._zod.traits.add(r),e(o,u);for(let l in i.prototype)l in o||Object.defineProperty(o,l,{value:i.prototype[l].bind(o)});o._zod.constr=i,o._zod.def=u}let s=t?.Parent??Object;class a extends s{}Object.defineProperty(a,"name",{value:r});function i(o){var u;let c=t?.Parent?new a:this;n(c,o),(u=c._zod).deferred??(u.deferred=[]);for(let l of c._zod.deferred)l();return c}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:o=>t?.Parent&&o instanceof t.Parent?!0:o?._zod?.traits?.has(r)}),Object.defineProperty(i,"name",{value:r}),i}function ba(r){return r&&Object.assign(Wp,r),Wp}var bM,wM,hn,Wp,oo=_(()=>{"use strict";bM=Object.freeze({status:"aborted"});wM=Symbol("zod_brand"),hn=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Wp={}});function Jp(r){let e=Object.values(r).filter(n=>typeof n=="number");return Object.entries(r).filter(([n,s])=>e.indexOf(+n)===-1).map(([n,s])=>s)}function dw(r,e){return typeof e=="bigint"?e.toString():e}function pw(r){return{get value(){{let t=r();return Object.defineProperty(this,"value",{value:t}),t}throw new Error("cached value already set")}}}function wa(r,e,t){let n=new r._zod.constr(e??r._zod.def);return(!e||t?.parent)&&(n._zod.parent=r),n}function fw(r){let e=r;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function Pc(r,e=0){for(let t=e;t<r.issues.length;t++)if(r.issues[t]?.continue!==!0)return!0;return!1}function Tc(r){return typeof r=="string"?r:r?.message}function va(r,e,t){let n={...r,path:r.path??[]};if(!r.message){let s=Tc(r.inst?._zod.def?.error?.(r))??Tc(e?.error?.(r))??Tc(t.customError?.(r))??Tc(t.localeError?.(r))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}var Xp,jP,vM,gn=_(()=>{"use strict";Xp=Error.captureStackTrace?Error.captureStackTrace:(...r)=>{},jP=pw(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let r=Function;return new r(""),!0}catch{return!1}});vM={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}});var mw,hw,uo,Yp=_(()=>{"use strict";oo();gn();mw=(r,e)=>{r.name="$ZodError",Object.defineProperty(r,"_zod",{value:r._zod,enumerable:!1}),Object.defineProperty(r,"issues",{value:e,enumerable:!1}),Object.defineProperty(r,"message",{get(){return JSON.stringify(e,dw,2)},enumerable:!0}),Object.defineProperty(r,"toString",{value:()=>r.message,enumerable:!1})},hw=ya("$ZodError",mw),uo=ya("$ZodError",mw,{Parent:Error})});var zP,Sc,LP,gw,DP,_w,FP,yw,Qp=_(()=>{"use strict";oo();Yp();gn();zP=r=>(e,t,n,s)=>{let a=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:t,issues:[]},a);if(i instanceof Promise)throw new hn;if(i.issues.length){let o=new(s?.Err??r)(i.issues.map(u=>va(u,a,ba())));throw Xp(o,s?.callee),o}return i.value},Sc=zP(uo),LP=r=>async(e,t,n,s)=>{let a=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:t,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){let o=new(s?.Err??r)(i.issues.map(u=>va(u,a,ba())));throw Xp(o,s?.callee),o}return i.value},gw=LP(uo),DP=r=>(e,t,n)=>{let s=n?{...n,async:!1}:{async:!1},a=e._zod.run({value:t,issues:[]},s);if(a instanceof Promise)throw new hn;return a.issues.length?{success:!1,error:new(r??hw)(a.issues.map(i=>va(i,s,ba())))}:{success:!0,data:a.value}},_w=DP(uo),FP=r=>async(e,t,n)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},a=e._zod.run({value:t,issues:[]},s);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new r(a.issues.map(i=>va(i,s,ba())))}:{success:!0,data:a.value}},yw=FP(uo)});var UP,AM,bw=_(()=>{"use strict";UP="(?:(?:\\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])))",AM=new RegExp(`^${UP}$`)});var ww=_(()=>{"use strict"});var vw=_(()=>{"use strict"});var xw,ef=_(()=>{"use strict";xw={major:4,minor:0,patch:0}});var ZP,Ew,Aw=_(()=>{"use strict";oo();Qp();gn();ef();gn();ZP=ya("$ZodType",(r,e)=>{var t;r??(r={}),r._zod.def=e,r._zod.bag=r._zod.bag||{},r._zod.version=xw;let n=[...r._zod.def.checks??[]];r._zod.traits.has("$ZodCheck")&&n.unshift(r);for(let s of n)for(let a of s._zod.onattach)a(r);if(n.length===0)(t=r._zod).deferred??(t.deferred=[]),r._zod.deferred?.push(()=>{r._zod.run=r._zod.parse});else{let s=(a,i,o)=>{let u=Pc(a),c;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(a))continue}else if(u)continue;let d=a.issues.length,f=l._zod.check(a);if(f instanceof Promise&&o?.async===!1)throw new hn;if(c||f instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await f,a.issues.length!==d&&(u||(u=Pc(a,d)))});else{if(a.issues.length===d)continue;u||(u=Pc(a,d))}}return c?c.then(()=>a):a};r._zod.run=(a,i)=>{let o=r._zod.parse(a,i);if(o instanceof Promise){if(i.async===!1)throw new hn;return o.then(u=>s(u,n,i))}return s(o,n,i)}}r["~standard"]={validate:s=>{try{let a=_w(r,s);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return yw(r,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Ew=ya("$ZodNever",(r,e)=>{ZP.init(r,e),r._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:r}),t)})});var Ow=_(()=>{"use strict"});function qP(){return new co}var ZM,VM,co,pr,tf=_(()=>{"use strict";ZM=Symbol("ZodOutput"),VM=Symbol("ZodInput"),co=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};pr=qP()});function Iw(r,e){return new r({type:"never",...fw(e)})}var Tw=_(()=>{"use strict";gn()});var Pw=_(()=>{"use strict"});function lo(r,e){if(r instanceof co){let n=new kc(e),s={};for(let o of r._idmap.entries()){let[u,c]=o;n.process(c)}let a={},i={registry:r,uri:e?.uri,defs:s};for(let o of r._idmap.entries()){let[u,c]=o;a[u]=n.emit(c,{...e,external:i})}if(Object.keys(s).length>0){let o=n.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[o]:s}}return{schemas:a}}let t=new kc(e);return t.process(r),t.emit(r,e)}function Pe(r,e){let t=e??{seen:new Set};if(t.seen.has(r))return!1;t.seen.add(r);let s=r._zod.def;switch(s.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Pe(s.element,t);case"object":{for(let a in s.shape)if(Pe(s.shape[a],t))return!0;return!1}case"union":{for(let a of s.options)if(Pe(a,t))return!0;return!1}case"intersection":return Pe(s.left,t)||Pe(s.right,t);case"tuple":{for(let a of s.items)if(Pe(a,t))return!0;return!!(s.rest&&Pe(s.rest,t))}case"record":return Pe(s.keyType,t)||Pe(s.valueType,t);case"map":return Pe(s.keyType,t)||Pe(s.valueType,t);case"set":return Pe(s.valueType,t);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Pe(s.innerType,t);case"lazy":return Pe(s.getter(),t);case"default":return Pe(s.innerType,t);case"prefault":return Pe(s.innerType,t);case"custom":return!1;case"transform":return!0;case"pipe":return Pe(s.in,t)||Pe(s.out,t);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${s.type}`)}var kc,Sw=_(()=>{"use strict";tf();gn();kc=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??pr,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,t={path:[],schemaPath:[]}){var n;let s=e._zod.def,a={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,t.schemaPath.includes(e)&&(i.cycle=t.path),i.schema;let o={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,o);let u=e._zod.toJSONSchema?.();if(u)o.schema=u;else{let d={...t,schemaPath:[...t.schemaPath,e],path:t.path},f=e._zod.parent;if(f)o.ref=f,this.process(f,d),this.seen.get(f).isParent=!0;else{let p=o.schema;switch(s.type){case"string":{let m=p;m.type="string";let{minimum:h,maximum:g,format:w,patterns:b,contentEncoding:x}=e._zod.bag;if(typeof h=="number"&&(m.minLength=h),typeof g=="number"&&(m.maxLength=g),w&&(m.format=a[w]??w,m.format===""&&delete m.format),x&&(m.contentEncoding=x),b&&b.size>0){let I=[...b];I.length===1?m.pattern=I[0].source:I.length>1&&(o.schema.allOf=[...I.map(P=>({...this.target==="draft-7"?{type:"string"}:{},pattern:P.source}))])}break}case"number":{let m=p,{minimum:h,maximum:g,format:w,multipleOf:b,exclusiveMaximum:x,exclusiveMinimum:I}=e._zod.bag;typeof w=="string"&&w.includes("int")?m.type="integer":m.type="number",typeof I=="number"&&(m.exclusiveMinimum=I),typeof h=="number"&&(m.minimum=h,typeof I=="number"&&(I>=h?delete m.minimum:delete m.exclusiveMinimum)),typeof x=="number"&&(m.exclusiveMaximum=x),typeof g=="number"&&(m.maximum=g,typeof x=="number"&&(x<=g?delete m.maximum:delete m.exclusiveMaximum)),typeof b=="number"&&(m.multipleOf=b);break}case"boolean":{let m=p;m.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":{p.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":{p.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let m=p,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(m.minItems=h),typeof g=="number"&&(m.maxItems=g),m.type="array",m.items=this.process(s.element,{...d,path:[...d.path,"items"]});break}case"object":{let m=p;m.type="object",m.properties={};let h=s.shape;for(let b in h)m.properties[b]=this.process(h[b],{...d,path:[...d.path,"properties",b]});let g=new Set(Object.keys(h)),w=new Set([...g].filter(b=>{let x=s.shape[b]._zod;return this.io==="input"?x.optin===void 0:x.optout===void 0}));w.size>0&&(m.required=Array.from(w)),s.catchall?._zod.def.type==="never"?m.additionalProperties=!1:s.catchall?s.catchall&&(m.additionalProperties=this.process(s.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=p;m.anyOf=s.options.map((h,g)=>this.process(h,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let m=p,h=this.process(s.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(s.right,{...d,path:[...d.path,"allOf",1]}),w=x=>"allOf"in x&&Object.keys(x).length===1,b=[...w(h)?h.allOf:[h],...w(g)?g.allOf:[g]];m.allOf=b;break}case"tuple":{let m=p;m.type="array";let h=s.items.map((b,x)=>this.process(b,{...d,path:[...d.path,"prefixItems",x]}));if(this.target==="draft-2020-12"?m.prefixItems=h:m.items=h,s.rest){let b=this.process(s.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?m.items=b:m.additionalItems=b}s.rest&&(m.items=this.process(s.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:w}=e._zod.bag;typeof g=="number"&&(m.minItems=g),typeof w=="number"&&(m.maxItems=w);break}case"record":{let m=p;m.type="object",m.propertyNames=this.process(s.keyType,{...d,path:[...d.path,"propertyNames"]}),m.additionalProperties=this.process(s.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":{let m=p,h=Jp(s.entries);h.every(g=>typeof g=="number")&&(m.type="number"),h.every(g=>typeof g=="string")&&(m.type="string"),m.enum=h;break}case"literal":{let m=p,h=[];for(let g of s.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(g))}else h.push(g);if(h.length!==0)if(h.length===1){let g=h[0];m.type=g===null?"null":typeof g,m.const=g}else h.every(g=>typeof g=="number")&&(m.type="number"),h.every(g=>typeof g=="string")&&(m.type="string"),h.every(g=>typeof g=="boolean")&&(m.type="string"),h.every(g=>g===null)&&(m.type="null"),m.enum=h;break}case"file":{let m=p,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:w,mime:b}=e._zod.bag;g!==void 0&&(h.minLength=g),w!==void 0&&(h.maxLength=w),b?b.length===1?(h.contentMediaType=b[0],Object.assign(m,h)):m.anyOf=b.map(x=>({...h,contentMediaType:x})):Object.assign(m,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(s.innerType,d);p.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,d),o.ref=s.innerType;break}case"success":{let m=p;m.type="boolean";break}case"default":{this.process(s.innerType,d),o.ref=s.innerType,p.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,d),o.ref=s.innerType,this.io==="input"&&(p._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,d),o.ref=s.innerType;let m;try{m=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}p.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=p,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=h.source;break}case"pipe":{let m=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(m,d),o.ref=m;break}case"readonly":{this.process(s.innerType,d),o.ref=s.innerType,p.readOnly=!0;break}case"promise":{this.process(s.innerType,d),o.ref=s.innerType;break}case"optional":{this.process(s.innerType,d),o.ref=s.innerType;break}case"lazy":{let m=e._zod.innerType;this.process(m,d),o.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let c=this.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),this.io==="input"&&Pe(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,t){let n={cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");let a=l=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(l[0])?.id,g=n.external.uri??(b=>b);if(h)return{ref:g(h)};let w=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=w,{defId:w,ref:`${g("__shared")}#/${d}/${w}`}}if(l[1]===s)return{ref:"#"};let p=`#/${d}/`,m=l[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:p+m}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:f,defId:p}=a(l);d.def={...d.schema},p&&(d.defId=p);let m=d.schema;for(let h in m)delete m[h];m.$ref=f};if(n.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
64
+
65
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let d=l[1];if(e===l[0]){i(l);continue}if(n.external){let p=n.external.registry.get(l[0])?.id;if(e!==l[0]&&p){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}}let o=(l,d)=>{let f=this.seen.get(l),p=f.def??f.schema,m={...p};if(f.ref===null)return;let h=f.ref;if(f.ref=null,h){o(h,d);let g=this.seen.get(h).schema;g.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(g)):(Object.assign(p,g),Object.assign(p,m))}f.isParent||this.override({zodSchema:l,jsonSchema:p,path:f.path??[]})};for(let l of[...this.seen.entries()].reverse())o(l[0],{target:this.target});let u={};if(this.target==="draft-2020-12"?u.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?u.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let l=n.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");u.$id=n.external.uri(l)}Object.assign(u,s.def);let c=n.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(c[d.defId]=d.def)}n.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?u.$defs=c:u.definitions=c);try{return JSON.parse(JSON.stringify(u))}catch{throw new Error("Error converting schema to JSON.")}}}});var kw=_(()=>{"use strict"});var Rc=_(()=>{"use strict";oo();Qp();Yp();Aw();ww();ef();gn();bw();Ow();tf();vw();Pw();Tw();Sw();kw()});var Cw,Rw,$w,Cc=_(()=>{"use strict";Cw=Symbol("Let zodToJsonSchema decide on which parser to use"),Rw={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"},$w=r=>typeof r=="string"?{...Rw,name:r}:{...Rw,...r}});var Nw,rf=_(()=>{"use strict";Cc();Nw=r=>{let e=$w(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function nf(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function ce(r,e,t,n,s){r[e]=t,nf(r,e,n,s)}var _n=_(()=>{"use strict"});var $c,Nc=_(()=>{"use strict";$c=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return[(r.length-t).toString(),...e.slice(t)].join("/")}});var gs=_(()=>{"use strict";bu()});function ge(r){if(r.target!=="openAi")return{};let e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];return r.flags.hasReferencedOpenAiAnyType=!0,{$ref:r.$refStrategy==="relative"?$c(e,r.currentPath):e.join("/")}}var Nt=_(()=>{"use strict";Nc()});function jw(r,e){let t={type:"array"};return r.type?._def&&r.type?._def?.typeName!==v.ZodAny&&(t.items=H(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&ce(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&ce(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(ce(t,"minItems",r.exactLength.value,r.exactLength.message,e),ce(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}var sf=_(()=>{"use strict";gs();_n();Te()});function Mw(r,e){let t={type:"integer",format:"int64"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ce(t,"minimum",n.value,n.message,e):ce(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),ce(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(t,"maximum",n.value,n.message,e):ce(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),ce(t,"maximum",n.value,n.message,e));break;case"multipleOf":ce(t,"multipleOf",n.value,n.message,e);break}return t}var af=_(()=>{"use strict";_n()});function zw(){return{type:"boolean"}}var of=_(()=>{"use strict"});function jc(r,e){return H(r.type._def,e)}var Mc=_(()=>{"use strict";Te()});var Lw,uf=_(()=>{"use strict";Te();Lw=(r,e)=>H(r.innerType._def,e)});function cf(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,a)=>cf(r,e,s))};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 GP(r,e)}}var GP,lf=_(()=>{"use strict";_n();GP=(r,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let n of r.checks)switch(n.kind){case"min":ce(t,"minimum",n.value,n.message,e);break;case"max":ce(t,"maximum",n.value,n.message,e);break}return t}});function Dw(r,e){return{...H(r.innerType._def,e),default:r.defaultValue()}}var df=_(()=>{"use strict";Te()});function Fw(r,e){return e.effectStrategy==="input"?H(r.schema._def,e):ge(e)}var pf=_(()=>{"use strict";Te();Nt()});function Uw(r){return{type:"string",enum:Array.from(r.values)}}var ff=_(()=>{"use strict"});function Bw(r,e){let t=[H(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),H(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return t.forEach(a=>{if(HP(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(n=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){let{additionalProperties:o,...u}=a;i=u}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}var HP,mf=_(()=>{"use strict";Te();HP=r=>"type"in r&&r.type==="string"?!1:"allOf"in r});function Zw(r,e){let t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}var hf=_(()=>{"use strict"});function zc(r,e){let t={type:"string"};if(r.checks)for(let n of r.checks)switch(n.kind){case"min":ce(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":ce(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Ht(t,"email",n.message,e);break;case"format:idn-email":Ht(t,"idn-email",n.message,e);break;case"pattern:zod":Ye(t,Gt.email,n.message,e);break}break;case"url":Ht(t,"uri",n.message,e);break;case"uuid":Ht(t,"uuid",n.message,e);break;case"regex":Ye(t,n.regex,n.message,e);break;case"cuid":Ye(t,Gt.cuid,n.message,e);break;case"cuid2":Ye(t,Gt.cuid2,n.message,e);break;case"startsWith":Ye(t,RegExp(`^${_f(n.value,e)}`),n.message,e);break;case"endsWith":Ye(t,RegExp(`${_f(n.value,e)}$`),n.message,e);break;case"datetime":Ht(t,"date-time",n.message,e);break;case"date":Ht(t,"date",n.message,e);break;case"time":Ht(t,"time",n.message,e);break;case"duration":Ht(t,"duration",n.message,e);break;case"length":ce(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),ce(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ye(t,RegExp(_f(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Ht(t,"ipv4",n.message,e),n.version!=="v4"&&Ht(t,"ipv6",n.message,e);break}case"base64url":Ye(t,Gt.base64url,n.message,e);break;case"jwt":Ye(t,Gt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ye(t,Gt.ipv4Cidr,n.message,e),n.version!=="v4"&&Ye(t,Gt.ipv6Cidr,n.message,e);break}case"emoji":Ye(t,Gt.emoji(),n.message,e);break;case"ulid":{Ye(t,Gt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ht(t,"binary",n.message,e);break}case"contentEncoding:base64":{ce(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ye(t,Gt.base64,n.message,e);break}}break}case"nanoid":Ye(t,Gt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function _f(r,e){return e.patternStrategy==="escape"?WP(r):r}function WP(r){let e="";for(let t=0;t<r.length;t++)KP.has(r[t])||(e+="\\"),e+=r[t];return e}function Ht(r,e,t,n){r.format||r.anyOf?.some(s=>s.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})):ce(r,"format",e,t,n)}function Ye(r,e,t,n){r.pattern||r.allOf?.some(s=>s.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:Vw(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):ce(r,"pattern",Vw(e,n),t,n)}function Vw(r,e){if(!e.applyRegexFlags||!r.flags)return r.source;let t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=t.i?r.source.toLowerCase():r.source,s="",a=!1,i=!1,o=!1;for(let u=0;u<n.length;u++){if(a){s+=n[u],a=!1;continue}if(t.i){if(i){if(n[u].match(/[a-z]/)){o?(s+=n[u],s+=`${n[u-2]}-${n[u]}`.toUpperCase(),o=!1):n[u+1]==="-"&&n[u+2]?.match(/[a-z]/)?(s+=n[u],o=!0):s+=`${n[u]}${n[u].toUpperCase()}`;continue}}else if(n[u].match(/[a-z]/)){s+=`[${n[u]}${n[u].toUpperCase()}]`;continue}}if(t.m){if(n[u]==="^"){s+=`(^|(?<=[\r
66
+ ]))`;continue}else if(n[u]==="$"){s+=`($|(?=[\r
67
+ ]))`;continue}}if(t.s&&n[u]==="."){s+=i?`${n[u]}\r
68
+ `:`[${n[u]}\r
69
+ ]`;continue}s+=n[u],n[u]==="\\"?a=!0:i&&n[u]==="]"?i=!1:!i&&n[u]==="["&&(i=!0)}try{new RegExp(s)}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`),r.source}return s}var gf,Gt,KP,Lc=_(()=>{"use strict";_n();Gt={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:()=>(gf===void 0&&(gf=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),gf),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-_]*$/};KP=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Dc(r,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"&&r.keyType?._def.typeName===v.ZodEnum)return{type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((n,s)=>({...n,[s]:H(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??ge(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:H(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(r.keyType?._def.typeName===v.ZodString&&r.keyType._def.checks?.length){let{type:n,...s}=zc(r.keyType._def,e);return{...t,propertyNames:s}}else{if(r.keyType?._def.typeName===v.ZodEnum)return{...t,propertyNames:{enum:r.keyType._def.values}};if(r.keyType?._def.typeName===v.ZodBranded&&r.keyType._def.type._def.typeName===v.ZodString&&r.keyType._def.type._def.checks?.length){let{type:n,...s}=jc(r.keyType._def,e);return{...t,propertyNames:s}}}return t}var Fc=_(()=>{"use strict";gs();Te();Lc();Mc();Nt()});function qw(r,e){if(e.mapStrategy==="record")return Dc(r,e);let t=H(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ge(e),n=H(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ge(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}var yf=_(()=>{"use strict";Te();Fc();Nt()});function Gw(r){let e=r.values,n=Object.keys(r.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),s=Array.from(new Set(n.map(a=>typeof a)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}var bf=_(()=>{"use strict"});function Hw(r){return r.target==="openAi"?void 0:{not:ge({...r,currentPath:[...r.currentPath,"not"]})}}var wf=_(()=>{"use strict";Nt()});function Kw(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var vf=_(()=>{"use strict"});function Jw(r,e){if(e.target==="openApi3")return Ww(r,e);let t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(n=>n._def.typeName in po&&(!n._def.checks||!n._def.checks.length))){let n=t.reduce((s,a)=>{let i=po[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(t.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=t.reduce((s,a)=>{let i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(a._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===t.length){let s=n.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:t.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(t.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((n,s)=>[...n,...s._def.values.filter(a=>!n.includes(a))],[])};return Ww(r,e)}var po,Ww,Uc=_(()=>{"use strict";Te();po={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Ww=(r,e)=>{let t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((n,s)=>H(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return t.length?{anyOf:t}:void 0}});function Xw(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length))return e.target==="openApi3"?{type:po[r.innerType._def.typeName],nullable:!0}:{type:[po[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=H(r.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let t=H(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}var xf=_(()=>{"use strict";Te();Uc()});function Yw(r,e){let t={type:"number"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"int":t.type="integer",nf(t,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ce(t,"minimum",n.value,n.message,e):ce(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),ce(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(t,"maximum",n.value,n.message,e):ce(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),ce(t,"maximum",n.value,n.message,e));break;case"multipleOf":ce(t,"multipleOf",n.value,n.message,e);break}return t}var Ef=_(()=>{"use strict";_n()});function Qw(r,e){let t=e.target==="openAi",n={type:"object",properties:{}},s=[],a=r.shape();for(let o in a){let u=a[o];if(u===void 0||u._def===void 0)continue;let c=XP(u);c&&t&&(u._def.typeName==="ZodOptional"&&(u=u._def.innerType),u.isNullable()||(u=u.nullable()),c=!1);let l=H(u._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});l!==void 0&&(n.properties[o]=l,c||s.push(o))}s.length&&(n.required=s);let i=JP(r,e);return i!==void 0&&(n.additionalProperties=i),n}function JP(r,e){if(r.catchall._def.typeName!=="ZodNever")return H(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(r.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function XP(r){try{return r.isOptional()}catch{return!0}}var Af=_(()=>{"use strict";Te()});var ev,Of=_(()=>{"use strict";Te();Nt();ev=(r,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return H(r.innerType._def,e);let t=H(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:ge(e)},t]}:ge(e)}});var tv,If=_(()=>{"use strict";Te();tv=(r,e)=>{if(e.pipeStrategy==="input")return H(r.in._def,e);if(e.pipeStrategy==="output")return H(r.out._def,e);let t=H(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=H(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,n].filter(s=>s!==void 0)}}});function rv(r,e){return H(r.type._def,e)}var Tf=_(()=>{"use strict";Te()});function nv(r,e){let n={type:"array",uniqueItems:!0,items:H(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&ce(n,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&ce(n,"maxItems",r.maxSize.value,r.maxSize.message,e),n}var Pf=_(()=>{"use strict";_n();Te()});function sv(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,n)=>H(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:H(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,n)=>H(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}var Sf=_(()=>{"use strict";Te()});function av(r){return{not:ge(r)}}var kf=_(()=>{"use strict";Nt()});function iv(r){return ge(r)}var Rf=_(()=>{"use strict";Nt()});var ov,Cf=_(()=>{"use strict";Te();ov=(r,e)=>H(r.innerType._def,e)});var uv,$f=_(()=>{"use strict";gs();Nt();sf();af();of();Mc();uf();lf();df();pf();ff();mf();hf();yf();bf();wf();vf();xf();Ef();Af();Of();If();Tf();Fc();Pf();Lc();Sf();kf();Uc();Rf();Cf();uv=(r,e,t)=>{switch(e){case v.ZodString:return zc(r,t);case v.ZodNumber:return Yw(r,t);case v.ZodObject:return Qw(r,t);case v.ZodBigInt:return Mw(r,t);case v.ZodBoolean:return zw();case v.ZodDate:return cf(r,t);case v.ZodUndefined:return av(t);case v.ZodNull:return Kw(t);case v.ZodArray:return jw(r,t);case v.ZodUnion:case v.ZodDiscriminatedUnion:return Jw(r,t);case v.ZodIntersection:return Bw(r,t);case v.ZodTuple:return sv(r,t);case v.ZodRecord:return Dc(r,t);case v.ZodLiteral:return Zw(r,t);case v.ZodEnum:return Uw(r);case v.ZodNativeEnum:return Gw(r);case v.ZodNullable:return Xw(r,t);case v.ZodOptional:return ev(r,t);case v.ZodMap:return qw(r,t);case v.ZodSet:return nv(r,t);case v.ZodLazy:return()=>r.getter()._def;case v.ZodPromise:return rv(r,t);case v.ZodNaN:case v.ZodNever:return Hw(t);case v.ZodEffects:return Fw(r,t);case v.ZodAny:return ge(t);case v.ZodUnknown:return iv(t);case v.ZodDefault:return Dw(r,t);case v.ZodBranded:return jc(r,t);case v.ZodReadonly:return ov(r,t);case v.ZodCatch:return Lw(r,t);case v.ZodPipeline:return tv(r,t);case v.ZodFunction:case v.ZodVoid:case v.ZodSymbol:return;default:return(n=>{})(e)}}});function H(r,e,t=!1){let n=e.seen.get(r);if(e.override){let o=e.override?.(r,e,n,t);if(o!==Cw)return o}if(n&&!t){let o=YP(n,e);if(o!==void 0)return o}let s={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,s);let a=uv(r,r.typeName,e),i=typeof a=="function"?H(a(),e):a;if(i&&QP(r,e,i),e.postProcess){let o=e.postProcess(i,r,e);return s.jsonSchema=i,o}return s.jsonSchema=i,i}var YP,QP,Te=_(()=>{"use strict";Cc();$f();Nc();Nt();YP=(r,e)=>{switch(e.$refStrategy){case"root":return{$ref:r.path.join("/")};case"relative":return{$ref:$c(e.currentPath,r.path)};case"none":case"seen":return r.path.length<e.currentPath.length&&r.path.every((t,n)=>e.currentPath[n]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),ge(e)):e.$refStrategy==="seen"?ge(e):void 0}},QP=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t)});var cv=_(()=>{"use strict"});var Nf,jf=_(()=>{"use strict";Te();rf();Nt();Nf=(r,e)=>{let t=Nw(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((u,[c,l])=>({...u,[c]:H(l._def,{...t,currentPath:[...t.basePath,t.definitionPath,c]},!0)??ge(t)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,a=H(r._def,s===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,s]},!1)??ge(t),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(a.title=i),t.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[t.openAiAnyTypeName]||(n[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}));let o=s===void 0?n?{...a,[t.definitionPath]:n}:a:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,s].join("/"),[t.definitionPath]:{...n,[s]:a}};return t.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o}});var lv=_(()=>{"use strict";Cc();rf();_n();Nc();Te();cv();Nt();sf();af();of();Mc();uf();lf();df();pf();ff();mf();hf();yf();bf();wf();vf();xf();Ef();Af();Of();If();Tf();Cf();Fc();Pf();Lc();Sf();kf();Uc();Rf();$f();jf();jf()});function Zr(r,e){let t=typeof r;if(t!==typeof e)return!1;if(Array.isArray(r)){if(!Array.isArray(e))return!1;let n=r.length;if(n!==e.length)return!1;for(let s=0;s<n;s++)if(!Zr(r[s],e[s]))return!1;return!0}if(t==="object"){if(!r||!e)return r===e;let n=Object.keys(r),s=Object.keys(e);if(n.length!==s.length)return!1;for(let i of n)if(!Zr(r[i],e[i]))return!1;return!0}return r===e}var Mf=_(()=>{"use strict"});function gt(r){return encodeURI(eS(r))}function eS(r){return r.replace(/~/g,"~0").replace(/\//g,"~1")}var Bc=_(()=>{"use strict"});function yn(r,e=Object.create(null),t=sS,n=""){if(r&&typeof r=="object"&&!Array.isArray(r)){let a=r.$id||r.id;if(a){let i=new URL(a,t.href);i.hash.length>1?e[i.href]=r:(i.hash="",n===""?t=i:yn(r,e,t))}}else if(r!==!0&&r!==!1)return e;let s=t.href+(n?"#"+n:"");if(e[s]!==void 0)throw new Error(`Duplicate schema URI "${s}".`);if(e[s]=r,r===!0||r===!1)return e;if(r.__absolute_uri__===void 0&&Object.defineProperty(r,"__absolute_uri__",{enumerable:!1,value:s}),r.$ref&&r.__absolute_ref__===void 0){let a=new URL(r.$ref,t.href);a.hash=a.hash,Object.defineProperty(r,"__absolute_ref__",{enumerable:!1,value:a.href})}if(r.$recursiveRef&&r.__absolute_recursive_ref__===void 0){let a=new URL(r.$recursiveRef,t.href);a.hash=a.hash,Object.defineProperty(r,"__absolute_recursive_ref__",{enumerable:!1,value:a.href})}if(r.$anchor){let a=new URL("#"+r.$anchor,t.href);e[a.href]=r}for(let a in r){if(nS[a])continue;let i=`${n}/${gt(a)}`,o=r[a];if(Array.isArray(o)){if(tS[a]){let u=o.length;for(let c=0;c<u;c++)yn(o[c],e,t,`${i}/${c}`)}}else if(rS[a])for(let u in o)yn(o[u],e,t,`${i}/${gt(u)}`);else yn(o,e,t,i)}return e}var tS,rS,nS,sS,Zc=_(()=>{"use strict";Bc();tS={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},rS={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},nS={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},sS=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 fr(r){return r.test.bind(r)}function wS(r){return r%4===0&&(r%100!==0||r%400===0)}function dv(r){let e=r.match(aS);if(!e)return!1;let t=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n==2&&wS(t)?29:iS[n])}function pv(r,e){let t=e.match(oS);if(!t)return!1;let n=+t[1],s=+t[2],a=+t[3],i=!!t[5];return(n<=23&&s<=59&&a<=59||n==23&&s==59&&a==60)&&(!r||i)}function xS(r){let e=r.split(vS);return e.length==2&&dv(e[0])&&pv(!0,e[1])}function OS(r){return ES.test(r)&&AS.test(r)}function TS(r){if(IS.test(r))return!1;try{return new RegExp(r,"u"),!0}catch{return!1}}var aS,iS,oS,uS,cS,lS,dS,pS,fS,mS,hS,gS,_S,yS,bS,zf,vS,ES,AS,IS,Lf=_(()=>{"use strict";aS=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,iS=[0,31,28,31,30,31,30,31,31,30,31,30,31],oS=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,uS=/^(?=.{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,cS=/^(?:[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,lS=/^(?:(?:[^\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,dS=/^(?:(?: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,pS=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,fS=/^(?:\/(?:[^~/]|~0|~1)*)*$/,mS=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,hS=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,gS=r=>{if(r[0]==='"')return!1;let[e,t,...n]=r.split("@");return!e||!t||n.length!==0||e.length>64||t.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(t)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:t.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},_S=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,yS=/^((([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,bS=r=>r.length>1&&r.length<80&&(/^P\d+([.,]\d+)?W$/.test(r)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(r)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(r));zf={date:dv,time:pv.bind(void 0,!1),"date-time":xS,duration:bS,uri:OS,"uri-reference":fr(cS),"uri-template":fr(lS),url:fr(dS),email:gS,hostname:fr(uS),ipv4:fr(_S),ipv6:fr(yS),regex:TS,uuid:fr(pS),"json-pointer":fr(fS),"json-pointer-uri-fragment":fr(mS),"relative-json-pointer":fr(hS)};vS=/t|\s/i;ES=/\/|:/,AS=/^(?:[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;IS=/[^\\]\\Z/});var fv,mv=_(()=>{"use strict";(function(r){r[r.Flag=1]="Flag",r[r.Basic=2]="Basic",r[r.Detailed=4]="Detailed"})(fv||(fv={}))});function hv(r){let e=0,t=r.length,n=0,s;for(;n<t;)e++,s=r.charCodeAt(n++),s>=55296&&s<=56319&&n<t&&(s=r.charCodeAt(n),(s&64512)==56320&&n++);return e}var Df=_(()=>{"use strict"});function he(r,e,t="2019-09",n=yn(e),s=!0,a=null,i="#",o="#",u=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."}]};let c=typeof r,l;switch(c){case"boolean":case"number":case"string":l=c;break;case"object":r===null?l="null":Array.isArray(r)?l="array":l="object";break;default:throw new Error(`Instances of "${c}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:w,not:b,anyOf:x,allOf:I,oneOf:P,if:K,then:V,else:Z,format:oe,properties:de,patternProperties:fe,additionalProperties:nr,unevaluatedProperties:Ws,minProperties:Ei,maxProperties:Js,propertyNames:mh,dependentRequired:Hl,dependentSchemas:Kl,dependencies:Wl,prefixItems:Jl,items:Ai,additionalItems:hh,unevaluatedItems:gh,contains:_h,minContains:Tr,maxContains:au,minItems:Xl,maxItems:Yl,uniqueItems:L0,minimum:Mn,maximum:zn,exclusiveMinimum:Oi,exclusiveMaximum:Ii,multipleOf:iu,minLength:ou,maxLength:uu,pattern:yh,__absolute_ref__:cu,__absolute_recursive_ref__:D0}=e,N=[];if(p===!0&&a===null&&(a=e),f==="#"){let J=a===null?n[D0]:a,B=`${o}/$recursiveRef`,Q=he(r,a===null?e:a,t,n,s,J,i,B,u);Q.valid||N.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:B,error:"A subschema had errors."},...Q.errors)}if(d!==void 0){let B=n[cu||d];if(B===void 0){let S=`Unresolved $ref "${d}".`;throw cu&&cu!==d&&(S+=` Absolute URI "${cu}".`),S+=`
70
+ Known schemas:
71
+ - ${Object.keys(n).join(`
72
+ - `)}`,new Error(S)}let Q=`${o}/$ref`,M=he(r,B,t,n,s,a,i,Q,u);if(M.valid||N.push({instanceLocation:i,keyword:"$ref",keywordLocation:Q,error:"A subschema had errors."},...M.errors),t==="4"||t==="7")return{valid:N.length===0,errors:N}}if(Array.isArray(m)){let J=m.length,B=!1;for(let Q=0;Q<J;Q++)if(l===m[Q]||m[Q]==="integer"&&l==="number"&&r%1===0&&r===r){B=!0;break}B||N.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${m.join('", "')}".`})}else m==="integer"?(l!=="number"||r%1||r!==r)&&N.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${m}".`}):m!==void 0&&l!==m&&N.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${m}".`});if(h!==void 0&&(l==="object"||l==="array"?Zr(r,h)||N.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):r!==h&&N.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(l==="object"||l==="array"?g.some(J=>Zr(r,J))||N.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(J=>r===J)||N.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),b!==void 0){let J=`${o}/not`;he(r,b,t,n,s,a,i,J).valid&&N.push({instanceLocation:i,keyword:"not",keywordLocation:J,error:'Instance matched "not" schema.'})}let lu=[];if(x!==void 0){let J=`${o}/anyOf`,B=N.length,Q=!1;for(let M=0;M<x.length;M++){let S=x[M],Y=Object.create(u),X=he(r,S,t,n,s,p===!0?a:null,i,`${J}/${M}`,Y);N.push(...X.errors),Q=Q||X.valid,X.valid&&lu.push(Y)}Q?N.length=B:N.splice(B,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:J,error:"Instance does not match any subschemas."})}if(I!==void 0){let J=`${o}/allOf`,B=N.length,Q=!0;for(let M=0;M<I.length;M++){let S=I[M],Y=Object.create(u),X=he(r,S,t,n,s,p===!0?a:null,i,`${J}/${M}`,Y);N.push(...X.errors),Q=Q&&X.valid,X.valid&&lu.push(Y)}Q?N.length=B:N.splice(B,0,{instanceLocation:i,keyword:"allOf",keywordLocation:J,error:"Instance does not match every subschema."})}if(P!==void 0){let J=`${o}/oneOf`,B=N.length,Q=P.filter((M,S)=>{let Y=Object.create(u),X=he(r,M,t,n,s,p===!0?a:null,i,`${J}/${S}`,Y);return N.push(...X.errors),X.valid&&lu.push(Y),X.valid}).length;Q===1?N.length=B:N.splice(B,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:J,error:`Instance does not match exactly one subschema (${Q} matches).`})}if((l==="object"||l==="array")&&Object.assign(u,...lu),K!==void 0){let J=`${o}/if`;if(he(r,K,t,n,s,a,i,J,u).valid){if(V!==void 0){let Q=he(r,V,t,n,s,a,i,`${o}/then`,u);Q.valid||N.push({instanceLocation:i,keyword:"if",keywordLocation:J,error:'Instance does not match "then" schema.'},...Q.errors)}}else if(Z!==void 0){let Q=he(r,Z,t,n,s,a,i,`${o}/else`,u);Q.valid||N.push({instanceLocation:i,keyword:"if",keywordLocation:J,error:'Instance does not match "else" schema.'},...Q.errors)}}if(l==="object"){if(w!==void 0)for(let M of w)M in r||N.push({instanceLocation:i,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${M}".`});let J=Object.keys(r);if(Ei!==void 0&&J.length<Ei&&N.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${Ei} properties.`}),Js!==void 0&&J.length>Js&&N.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${Js} properties.`}),mh!==void 0){let M=`${o}/propertyNames`;for(let S in r){let Y=`${i}/${gt(S)}`,X=he(S,mh,t,n,s,a,Y,M);X.valid||N.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:M,error:`Property name "${S}" does not match schema.`},...X.errors)}}if(Hl!==void 0){let M=`${o}/dependantRequired`;for(let S in Hl)if(S in r){let Y=Hl[S];for(let X of Y)X in r||N.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:M,error:`Instance has "${S}" but does not have "${X}".`})}}if(Kl!==void 0)for(let M in Kl){let S=`${o}/dependentSchemas`;if(M in r){let Y=he(r,Kl[M],t,n,s,a,i,`${S}/${gt(M)}`,u);Y.valid||N.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:S,error:`Instance has "${M}" but does not match dependant schema.`},...Y.errors)}}if(Wl!==void 0){let M=`${o}/dependencies`;for(let S in Wl)if(S in r){let Y=Wl[S];if(Array.isArray(Y))for(let X of Y)X in r||N.push({instanceLocation:i,keyword:"dependencies",keywordLocation:M,error:`Instance has "${S}" but does not have "${X}".`});else{let X=he(r,Y,t,n,s,a,i,`${M}/${gt(S)}`);X.valid||N.push({instanceLocation:i,keyword:"dependencies",keywordLocation:M,error:`Instance has "${S}" but does not match dependant schema.`},...X.errors)}}}let B=Object.create(null),Q=!1;if(de!==void 0){let M=`${o}/properties`;for(let S in de){if(!(S in r))continue;let Y=`${i}/${gt(S)}`,X=he(r[S],de[S],t,n,s,a,Y,`${M}/${gt(S)}`);if(X.valid)u[S]=B[S]=!0;else if(Q=s,N.push({instanceLocation:i,keyword:"properties",keywordLocation:M,error:`Property "${S}" does not match schema.`},...X.errors),Q)break}}if(!Q&&fe!==void 0){let M=`${o}/patternProperties`;for(let S in fe){let Y=new RegExp(S,"u"),X=fe[S];for(let tt in r){if(!Y.test(tt))continue;let bh=`${i}/${gt(tt)}`,wh=he(r[tt],X,t,n,s,a,bh,`${M}/${gt(S)}`);wh.valid?u[tt]=B[tt]=!0:(Q=s,N.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:M,error:`Property "${tt}" matches pattern "${S}" but does not match associated schema.`},...wh.errors))}}}if(!Q&&nr!==void 0){let M=`${o}/additionalProperties`;for(let S in r){if(B[S])continue;let Y=`${i}/${gt(S)}`,X=he(r[S],nr,t,n,s,a,Y,M);X.valid?u[S]=!0:(Q=s,N.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:M,error:`Property "${S}" does not match additional properties schema.`},...X.errors))}}else if(!Q&&Ws!==void 0){let M=`${o}/unevaluatedProperties`;for(let S in r)if(!u[S]){let Y=`${i}/${gt(S)}`,X=he(r[S],Ws,t,n,s,a,Y,M);X.valid?u[S]=!0:N.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:M,error:`Property "${S}" does not match unevaluated properties schema.`},...X.errors)}}}else if(l==="array"){Yl!==void 0&&r.length>Yl&&N.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${r.length} > ${Yl}).`}),Xl!==void 0&&r.length<Xl&&N.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${r.length} < ${Xl}).`});let J=r.length,B=0,Q=!1;if(Jl!==void 0){let M=`${o}/prefixItems`,S=Math.min(Jl.length,J);for(;B<S;B++){let Y=he(r[B],Jl[B],t,n,s,a,`${i}/${B}`,`${M}/${B}`);if(u[B]=!0,!Y.valid&&(Q=s,N.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:M,error:"Items did not match schema."},...Y.errors),Q))break}}if(Ai!==void 0){let M=`${o}/items`;if(Array.isArray(Ai)){let S=Math.min(Ai.length,J);for(;B<S;B++){let Y=he(r[B],Ai[B],t,n,s,a,`${i}/${B}`,`${M}/${B}`);if(u[B]=!0,!Y.valid&&(Q=s,N.push({instanceLocation:i,keyword:"items",keywordLocation:M,error:"Items did not match schema."},...Y.errors),Q))break}}else for(;B<J;B++){let S=he(r[B],Ai,t,n,s,a,`${i}/${B}`,M);if(u[B]=!0,!S.valid&&(Q=s,N.push({instanceLocation:i,keyword:"items",keywordLocation:M,error:"Items did not match schema."},...S.errors),Q))break}if(!Q&&hh!==void 0){let S=`${o}/additionalItems`;for(;B<J;B++){let Y=he(r[B],hh,t,n,s,a,`${i}/${B}`,S);u[B]=!0,Y.valid||(Q=s,N.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:S,error:"Items did not match additional items schema."},...Y.errors))}}}if(_h!==void 0)if(J===0&&Tr===void 0)N.push({instanceLocation:i,keyword:"contains",keywordLocation:`${o}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Tr!==void 0&&J<Tr)N.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array has less items (${J}) than minContains (${Tr}).`});else{let M=`${o}/contains`,S=N.length,Y=0;for(let X=0;X<J;X++){let tt=he(r[X],_h,t,n,s,a,`${i}/${X}`,M);tt.valid?(u[X]=!0,Y++):N.push(...tt.errors)}Y>=(Tr||0)&&(N.length=S),Tr===void 0&&au===void 0&&Y===0?N.splice(S,0,{instanceLocation:i,keyword:"contains",keywordLocation:M,error:"Array does not contain item matching schema."}):Tr!==void 0&&Y<Tr?N.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array must contain at least ${Tr} items matching schema. Only ${Y} items were found.`}):au!==void 0&&Y>au&&N.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${au} items matching schema. ${Y} items were found.`})}if(!Q&&gh!==void 0){let M=`${o}/unevaluatedItems`;for(B;B<J;B++){if(u[B])continue;let S=he(r[B],gh,t,n,s,a,`${i}/${B}`,M);u[B]=!0,S.valid||N.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:M,error:"Items did not match unevaluated items schema."},...S.errors)}}if(L0)for(let M=0;M<J;M++){let S=r[M],Y=typeof S=="object"&&S!==null;for(let X=0;X<J;X++){if(M===X)continue;let tt=r[X];(S===tt||Y&&(typeof tt=="object"&&tt!==null)&&Zr(S,tt))&&(N.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${o}/uniqueItems`,error:`Duplicate items at indexes ${M} and ${X}.`}),M=Number.MAX_SAFE_INTEGER,X=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(t==="4"?(Mn!==void 0&&(Oi===!0&&r<=Mn||r<Mn)&&N.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${r} is less than ${Oi?"or equal to ":""} ${Mn}.`}),zn!==void 0&&(Ii===!0&&r>=zn||r>zn)&&N.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${r} is greater than ${Ii?"or equal to ":""} ${zn}.`})):(Mn!==void 0&&r<Mn&&N.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${r} is less than ${Mn}.`}),zn!==void 0&&r>zn&&N.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${r} is greater than ${zn}.`}),Oi!==void 0&&r<=Oi&&N.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${r} is less than ${Oi}.`}),Ii!==void 0&&r>=Ii&&N.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${r} is greater than or equal to ${Ii}.`})),iu!==void 0){let J=r%iu;Math.abs(0-J)>=11920929e-14&&Math.abs(iu-J)>=11920929e-14&&N.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${r} is not a multiple of ${iu}.`})}}else if(l==="string"){let J=ou===void 0&&uu===void 0?0:hv(r);ou!==void 0&&J<ou&&N.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${J} < ${ou}).`}),uu!==void 0&&J>uu&&N.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${J} > ${uu}).`}),yh!==void 0&&!new RegExp(yh,"u").test(r)&&N.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),oe!==void 0&&zf[oe]&&!zf[oe](r)&&N.push({instanceLocation:i,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${oe}".`})}return{valid:N.length===0,errors:N}}var Ff=_(()=>{"use strict";Mf();Zc();Lf();Bc();Df()});var gv=_(()=>{"use strict";Zc();Ff()});var fo=_(()=>{"use strict";Mf();Zc();Lf();Bc();mv();Df();Ff();gv()});function _t(r){if(typeof r!="object"||r===null)return!1;let e=r;if(!("_zod"in e))return!1;let t=e._zod;return typeof t=="object"&&t!==null&&"def"in t}function jt(r){if(typeof r!="object"||r===null)return!1;let e=r;if(!("_def"in e)||"_zod"in e)return!1;let t=e._def;return typeof t=="object"&&t!=null&&"typeName"in t}function yt(r){return!r||typeof r!="object"||Array.isArray(r)?!1:!!(_t(r)||jt(r))}async function _v(r,e){if(_t(r))try{return{success:!0,data:await gw(r,e)}}catch(t){return{success:!1,error:t}}if(jt(r))return r.safeParse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function Oa(r,e){if(_t(r))return Sc(r,e);if(jt(r))return r.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function _s(r){if(_t(r))return pr.get(r)?.description;if(jt(r)||"description"in r&&typeof r.description=="string")return r.description}function Uf(r){return yt(r)?jt(r)?r._def.typeName==="ZodString":_t(r)?r._zod.def.type==="string":!1:!1}function Aa(r){return _t(r)?typeof r=="object"&&r!==null&&"_zod"in r&&typeof r._zod=="object"&&r._zod!==null&&"def"in r._zod&&typeof r._zod.def=="object"&&r._zod.def!==null&&"type"in r._zod.def&&r._zod.def.type==="object":!1}function yv(r){return _t(r)?typeof r=="object"&&r!==null&&"_zod"in r&&typeof r._zod=="object"&&r._zod!==null&&"def"in r._zod&&typeof r._zod.def=="object"&&r._zod.def!==null&&"type"in r._zod.def&&r._zod.def.type==="array":!1}function Vc(r,e=!1){if(jt(r))return r.strict();if(Aa(r)){let t=r._zod.def.shape;if(e)for(let[a,i]of Object.entries(r._zod.def.shape)){if(Aa(i)){let u=Vc(i,e);t[a]=u}else if(yv(i)){let u=i._zod.def.element;Aa(u)&&(u=Vc(u,e)),t[a]=wa(i,{...i._zod.def,element:u})}else t[a]=i;let o=pr.get(i);o&&pr.add(t[a],o)}let n=wa(r,{...r._zod.def,shape:t,catchall:Iw(Ew)}),s=pr.get(r);return s&&pr.add(n,s),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function PS(r){return jt(r)&&"typeName"in r._def&&r._def.typeName==="ZodEffects"}function SS(r){return _t(r)&&r._zod.def.type==="pipe"}function Ea(r,e=!1){if(jt(r))return PS(r)?Ea(r._def.schema,e):r;if(_t(r)){let t=r;if(SS(r)&&(t=Ea(r._zod.def.in,e)),e){if(Aa(t)){let s=t._zod.def.shape;for(let[a,i]of Object.entries(t._zod.def.shape))s[a]=Ea(i,e);t=wa(t,{...t._zod.def,shape:s})}else if(yv(t)){let s=Ea(t._zod.def.element,e);t=wa(t,{...t._zod.def,element:s})}}let n=pr.get(r);return n&&pr.add(t,n),t}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}var Vr=_(()=>{"use strict";Rc()});function lt(r){if(_t(r)){let e=Ea(r,!0);if(Aa(e)){let t=Vc(e,!0);return lo(t)}else return lo(r)}return jt(r)?Nf(r):r}var ys=_(()=>{"use strict";Rc();lv();fo();Vr();fo()});function kS(r,e){if(r!==void 0&&!sn(r))return r;if(io(e))try{let t=e.getName();return t=t.startsWith("Runnable")?t.slice(8):t,t}catch{return e.getName()}else return e.name??"UnknownSchema"}function RS(r){return io(r.data)?{type:"runnable",data:{id:r.data.lc_id,name:r.data.getName()}}:{type:"schema",data:{...lt(r.data.schema),title:r.data.name}}}function bv(r,e=[]){let t=new Set(r.edges.filter(s=>!e.includes(s.source)).map(s=>s.target)),n=[];for(let s of Object.values(r.nodes))!e.includes(s.id)&&!t.has(s.id)&&n.push(s);return n.length===1?n[0]:void 0}function wv(r,e=[]){let t=new Set(r.edges.filter(s=>!e.includes(s.target)).map(s=>s.source)),n=[];for(let s of Object.values(r.nodes))!e.includes(s.id)&&!t.has(s.id)&&n.push(s);return n.length===1?n[0]:void 0}var mo,vv=_(()=>{"use strict";ts();Hp();cw();ys();mo=class r{constructor(e){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){let e={};return Object.values(this.nodes).forEach((t,n)=>{e[t.id]=sn(t.id)?n:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...RS(t)})),edges:this.edges.map(t=>{let n={source:e[t.source],target:e[t.target]};return typeof t.data<"u"&&(n.data=t.data),typeof t.conditional<"u"&&(n.conditional=t.conditional),n})}}addNode(e,t,n){if(t!==void 0&&this.nodes[t]!==void 0)throw new Error(`Node with id ${t} already exists`);let s=t??_e(),a={id:s,data:e,name:kS(t,e),metadata:n};return this.nodes[s]=a,a}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(t=>t.source!==e.id&&t.target!==e.id)}addEdge(e,t,n,s){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[t.id]===void 0)throw new Error(`Target node ${t.id} not in graph`);let a={source:e.id,target:t.id,data:n,conditional:s};return this.edges.push(a),a}firstNode(){return bv(this)}lastNode(){return wv(this)}extend(e,t=""){let n=t;Object.values(e.nodes).map(c=>c.id).every(sn)&&(n="");let a=c=>n?`${n}:${c}`:c;Object.entries(e.nodes).forEach(([c,l])=>{this.nodes[a(c)]={...l,id:a(c)}});let i=e.edges.map(c=>({...c,source:a(c.source),target:a(c.target)}));this.edges=[...this.edges,...i];let o=e.firstNode(),u=e.lastNode();return[o?{id:a(o.id),data:o.data}:void 0,u?{id:a(u.id),data:u.data}:void 0]}trimFirstNode(){let e=this.firstNode();e&&bv(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&wv(this,[e.id])&&this.removeNode(e)}reid(){let e=Object.fromEntries(Object.values(this.nodes).map(s=>[s.id,s.name])),t=new Map;Object.values(e).forEach(s=>{t.set(s,(t.get(s)||0)+1)});let n=s=>{let a=e[s];return sn(s)&&t.get(a)===1?a:s};return new r({nodes:Object.fromEntries(Object.entries(this.nodes).map(([s,a])=>[n(s),{...a,id:n(s)}])),edges:this.edges.map(s=>({...s,source:n(s.source),target:n(s.target)}))})}drawMermaid(e){let{withStyles:t,curveStyle:n,nodeColors:s={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:a}=e??{},i=this.reid(),o=i.firstNode(),u=i.lastNode();return ow(i.nodes,i.edges,{firstNode:o?.id,lastNode:u?.id,withStyles:t,curveStyle:n,nodeColors:s,wrapLabelNWords:a})}async drawMermaidPng(e){let t=this.drawMermaid(e);return uw(t,{backgroundColor:e?.backgroundColor})}}});function xv(r){let e=new TextEncoder,t=new ReadableStream({async start(n){for await(let s of r)n.enqueue(e.encode(`event: data
73
+ data: ${JSON.stringify(s)}
74
+
75
+ `));n.enqueue(e.encode(`event: end
76
+
77
+ `)),n.close()}});return Ve.fromReadableStream(t)}var Ev=_(()=>{"use strict";Fr()});function Bf(r){return typeof r=="object"&&r!==null&&typeof r[Symbol.iterator]=="function"&&typeof r.next=="function"}function qc(r){return typeof r=="object"&&r!==null&&typeof r[Symbol.asyncIterator]=="function"}function*Zf(r,e){for(;;){let{value:t,done:n}=Xe.runWithConfig($t(r),e.next.bind(e),!0);if(n)break;yield t}}async function*Gc(r,e){let t=e[Symbol.asyncIterator]();for(;;){let{value:n,done:s}=await Xe.runWithConfig($t(r),t.next.bind(e),!0);if(s)break;yield n}}var Av,Ov=_(()=>{"use strict";hs();zr();Av=r=>r!=null&&typeof r=="object"&&"next"in r&&typeof r.next=="function"});function Se(r,e){return r&&!Array.isArray(r)&&!(r instanceof Date)&&typeof r=="object"?r:{[e]:r}}function CS(r){if(Pu(r))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}function qr(r){if(typeof r=="function")return new Wt({func:r});if(pe.isRunnable(r))return r;if(!Array.isArray(r)&&typeof r=="object"){let e={};for(let[t,n]of Object.entries(r))e[t]=qr(n);return new bn({steps:e})}else throw new Error(`Expected a Runnable, function or object.
78
+ Instead got an unsupported type.`)}function $S(r,e){let t=e.name??r.getName(),n=e.description??_s(e.schema);return Uf(e.schema)?new go({name:t,description:n,schema:ft.object({input:ft.string()}).transform(s=>s.input),bound:r}):new go({name:t,description:n,schema:e.schema,bound:r})}var Vf,pe,mr,Hc,ho,Kt,bn,qf,Wt,Kc,Ia,Wc,go,dt=_(()=>{"use strict";wu();Vf=Dt(Eu(),1);ts();md();rw();sw();qi();Fr();qp();zr();so();iw();Hp();hs();vv();Ev();Ov();pc();Vr();pe=class extends Bt{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(e){let t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}bind(e){return new mr({bound:this,kwargs:e,config:{}})}map(){return new Hc({bound:this})}withRetry(e){return new ho({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new mr({bound:this,config:e,kwargs:{}})}withFallbacks(e){let t=Array.isArray(e)?e:e.fallbacks;return new Kc({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(ue);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");let n=Object.fromEntries(Object.entries(e).filter(([s])=>s!=="runId"));return Array.from({length:t},(s,a)=>ue(a===0?e:n))}return Array.from({length:t},()=>ue(e))}async batch(e,t,n){let s=this._getOptionsList(t??{},e.length),a=s[0]?.maxConcurrency??n?.maxConcurrency,i=new Br({maxConcurrency:a,onFailedAttempt:u=>{throw u}}),o=e.map((u,c)=>i.call(async()=>{try{return await this.invoke(u,s[c])}catch(l){if(n?.returnExceptions)return l;throw l}}));return Promise.all(o)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){let n=ue(t),s=new Lr({generator:this._streamIterator(e,n),config:n});return await s.setup,Ve.fromAsyncGenerator(s)}_separateRunnableConfigFromCallOptions(e){let t;e===void 0?t=ue(e):t=ue({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});let n={...e};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[t,n]}async _callWithConfig(e,t,n){let s=ue(n),i=await(await ct(s))?.handleChainStart(this.toJSON(),Se(t,"input"),s.runId,s?.runType,void 0,void 0,s?.runName??this.getName());delete s.runId;let o;try{let u=e.call(this,t,s,i);o=await lr(u,n?.signal)}catch(u){throw await i?.handleChainError(u),u}return await i?.handleChainEnd(Se(o,"output")),o}async _batchWithConfig(e,t,n,s){let a=this._getOptionsList(n??{},t.length),i=await Promise.all(a.map(ct)),o=await Promise.all(i.map(async(c,l)=>{let d=await c?.handleChainStart(this.toJSON(),Se(t[l],"input"),a[l].runId,a[l].runType,void 0,void 0,a[l].runName??this.getName());return delete a[l].runId,d})),u;try{let c=e.call(this,t,a,o,s);u=await lr(c,a?.[0]?.signal)}catch(c){throw await Promise.all(o.map(l=>l?.handleChainError(c))),c}return await Promise.all(o.map(c=>c?.handleChainEnd(Se(u,"output")))),u}_concatOutputChunks(e,t){return Dr(e,t)}async*_transformStreamWithConfig(e,t,n){let s,a=!0,i,o=!0,u=ue(n),c=await ct(u),l=this;async function*d(){for await(let p of e){if(a)if(s===void 0)s=p;else try{s=l._concatOutputChunks(s,p)}catch{s=void 0,a=!1}yield p}}let f;try{let p=await Yb(t.bind(this),d(),async()=>c?.handleChainStart(this.toJSON(),{input:""},u.runId,u.runType,void 0,void 0,u.runName??this.getName()),n?.signal,u);delete u.runId,f=p.setup;let m=f?.handlers.find(nw),h=p.output;m!==void 0&&f!==void 0&&(h=m.tapOutputIterable(f.runId,h));let g=f?.handlers.find(tw);g!==void 0&&f!==void 0&&(h=g.tapOutputIterable(f.runId,h));for await(let w of h)if(yield w,o)if(i===void 0)i=w;else try{i=this._concatOutputChunks(i,w)}catch{i=void 0,o=!1}}catch(p){throw await f?.handleChainError(p,void 0,void 0,void 0,{inputs:Se(s,"input")}),p}await f?.handleChainEnd(i??{},void 0,void 0,void 0,{inputs:Se(s,"input")})}getGraph(e){let t=new mo,n=t.addNode({name:`${this.getName()}Input`,schema:ft.any()}),s=t.addNode(this),a=t.addNode({name:`${this.getName()}Output`,schema:ft.any()});return t.addEdge(n,s),t.addEdge(s,a),t}pipe(e){return new Kt({first:this,last:qr(e)})}pick(e){return this.pipe(new Wc(e))}assign(e){return this.pipe(new Ia(new bn({steps:e})))}async*transform(e,t){let n;for await(let s of e)n===void 0?n=s:n=this._concatOutputChunks(n,s);yield*this._streamIterator(n,ue(t))}async*streamLog(e,t,n){let s=new no({...n,autoClose:!1,_schemaFormat:"original"}),a=ue(t);yield*this._streamLog(e,s,a)}async*_streamLog(e,t,n){let{callbacks:s}=n;if(s===void 0)n.callbacks=[t];else if(Array.isArray(s))n.callbacks=s.concat([t]);else{let u=s.copy();u.addHandler(t,!0),n.callbacks=u}let a=this.stream(e,n);async function i(){try{let u=await a;for await(let c of u){let l=new qt({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await t.writer.write(l)}}finally{await t.writer.close()}}let o=i();try{for await(let u of t)yield u}finally{await o}}streamEvents(e,t,n){let s;if(t.version==="v1")s=this._streamEventsV1(e,t,n);else if(t.version==="v2")s=this._streamEventsV2(e,t,n);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return t.encoding==="text/event-stream"?xv(s):Ve.fromAsyncGenerator(s)}async*_streamEventsV2(e,t,n){let s=new Ac({...n,autoClose:!1}),a=ue(t),i=a.runId??_e();a.runId=i;let o=a.callbacks;if(o===void 0)a.callbacks=[s];else if(Array.isArray(o))a.callbacks=o.concat(s);else{let m=o.copy();m.addHandler(s,!0),a.callbacks=m}let u=new AbortController,c=this;async function l(){let m,h=null;try{t?.signal?"any"in AbortSignal?m=AbortSignal.any([u.signal,t.signal]):(m=t.signal,h=()=>{u.abort()},t.signal.addEventListener("abort",h,{once:!0})):m=u.signal;let g=await c.stream(e,{...a,signal:m}),w=s.tapOutputIterable(i,g);for await(let b of w)if(u.signal.aborted)break}finally{await s.finish(),m&&h&&m.removeEventListener("abort",h)}}let d=l(),f=!1,p;try{for await(let m of s){if(!f){m.data.input=e,f=!0,p=m.run_id,yield m;continue}m.run_id===p&&m.event.endsWith("_end")&&m.data?.input&&delete m.data.input,yield m}}finally{u.abort(),await d}}async*_streamEventsV1(e,t,n){let s,a=!1,i=ue(t),o=i.tags??[],u=i.metadata??{},c=i.runName??this.getName(),l=new no({...n,autoClose:!1,_schemaFormat:"streaming_events"}),d=new Ic({...n}),f=this._streamLog(e,l,i);for await(let m of f){if(s?s=s.concat(m):s=ro.fromRunLogPatch(m),s.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!a){a=!0;let b={...s.state},x={run_id:b.id,event:`on_${b.type}_start`,name:c,tags:o,metadata:u,data:{input:e}};d.includeEvent(x,b.type)&&(yield x)}let h=m.ops.filter(b=>b.path.startsWith("/logs/")).map(b=>b.path.split("/")[2]),g=[...new Set(h)];for(let b of g){let x,I={},P=s.state.logs[b];if(P.end_time===void 0?P.streamed_output.length>0?x="stream":x="start":x="end",x==="start")P.inputs!==void 0&&(I.input=P.inputs);else if(x==="end")P.inputs!==void 0&&(I.input=P.inputs),I.output=P.final_output;else if(x==="stream"){let K=P.streamed_output.length;if(K!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${K} instead. Encountered in: "${P.name}"`);I={chunk:P.streamed_output[0]},P.streamed_output=[]}yield{event:`on_${P.type}_${x}`,name:P.name,run_id:P.id,tags:P.tags,metadata:P.metadata,data:I}}let{state:w}=s;if(w.streamed_output.length>0){let b=w.streamed_output.length;if(b!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${b} instead. Encountered in: "${w.name}"`);let x={chunk:w.streamed_output[0]};w.streamed_output=[];let I={event:`on_${w.type}_stream`,run_id:w.id,tags:o,metadata:u,name:c,data:x};d.includeEvent(I,w.type)&&(yield I)}}let p=s?.state;if(p!==void 0){let m={event:`on_${p.type}_end`,name:c,run_id:p.id,tags:o,metadata:u,data:{output:p.final_output}};d.includeEvent(m,p.type)&&(yield m)}}static isRunnable(e){return io(e)}withListeners({onStart:e,onEnd:t,onError:n}){return new mr({bound:this,config:{},configFactories:[s=>({callbacks:[new ao({config:s,onStart:e,onEnd:t,onError:n})]})]})}asTool(e){return $S(this,e)}},mr=class r extends pe{static lc_name(){return"RunnableBinding"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"configFactories",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){let t=ga(this.config,...e);return ga(t,...this.configFactories?await Promise.all(this.configFactories.map(async n=>await n(t))):[])}bind(e){return new this.constructor({bound:this.bound,kwargs:{...this.kwargs,...e},config:this.config})}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new ho({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(ue(t),this.kwargs))}async batch(e,t,n){let s=Array.isArray(t)?await Promise.all(t.map(async a=>this._mergeConfig(ue(a),this.kwargs))):await this._mergeConfig(ue(t),this.kwargs);return this.bound.batch(e,s,n)}_concatOutputChunks(e,t){return this.bound._concatOutputChunks(e,t)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(ue(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(ue(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(ue(t),this.kwargs))}streamEvents(e,t,n){let s=this,a=async function*(){yield*s.bound.streamEvents(e,{...await s._mergeConfig(ue(t),s.kwargs),version:t.version},n)};return Ve.fromAsyncGenerator(a())}static isRunnableBinding(e){return e.bound&&pe.isRunnable(e.bound)}withListeners({onStart:e,onEnd:t,onError:n}){return new r({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[s=>({callbacks:[new ao({config:s,onStart:e,onEnd:t,onError:n})]})]})}},Hc=class r extends pe{static lc_name(){return"RunnableEach"}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound}bind(e){return new r({bound:this.bound.bind(e)})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _invoke(e,t,n){return this.bound.batch(e,Ee(t,{callbacks:n?.getChild()}))}withListeners({onStart:e,onEnd:t,onError:n}){return new r({bound:this.bound.withListeners({onStart:e,onEnd:t,onError:n})})}},ho=class extends mr{static lc_name(){return"RunnableRetry"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"maxAttemptNumber",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:()=>{}}),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,n){let s=e>1?`retry:attempt:${e}`:void 0;return Ee(t,{callbacks:n?.getChild(s)})}async _invoke(e,t,n){return(0,Vf.default)(s=>super.invoke(e,this._patchConfigForRetry(s,t,n)),{onFailedAttempt:s=>this.onFailedAttempt(s,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,n,s){let a={};try{await(0,Vf.default)(async i=>{let o=e.map((f,p)=>p).filter(f=>a[f.toString()]===void 0||a[f.toString()]instanceof Error),u=o.map(f=>e[f]),c=o.map(f=>this._patchConfigForRetry(i,t?.[f],n?.[f])),l=await super.batch(u,c,{...s,returnExceptions:!0}),d;for(let f=0;f<l.length;f+=1){let p=l[f],m=o[f];p instanceof Error&&d===void 0&&(d=p,d.input=u[f]),a[m.toString()]=p}if(d)throw d;return l},{onFailedAttempt:i=>this.onFailedAttempt(i,i.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(i){if(s?.returnExceptions!==!0)throw i}return Object.keys(a).sort((i,o)=>parseInt(i,10)-parseInt(o,10)).map(i=>a[parseInt(i,10)])}async batch(e,t,n){return this._batchWithConfig(this._batch.bind(this),e,t,n)}},Kt=class r extends pe{static lc_name(){return"RunnableSequence"}constructor(e){super(e),Object.defineProperty(this,"first",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"middle",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"last",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitSequenceTags",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){let n=ue(t),a=await(await ct(n))?.handleChainStart(this.toJSON(),Se(e,"input"),n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let i=e,o;try{let u=[this.first,...this.middle];for(let c=0;c<u.length;c+=1){let d=u[c].invoke(i,Ee(n,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`)}));i=await lr(d,t?.signal)}if(t?.signal?.aborted)throw new Error("Aborted");o=await this.last.invoke(i,Ee(n,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(u){throw await a?.handleChainError(u),u}return await a?.handleChainEnd(Se(o,"output")),o}async batch(e,t,n){let s=this._getOptionsList(t??{},e.length),a=await Promise.all(s.map(ct)),i=await Promise.all(a.map(async(u,c)=>{let l=await u?.handleChainStart(this.toJSON(),Se(e[c],"input"),s[c].runId,void 0,void 0,void 0,s[c].runName);return delete s[c].runId,l})),o=e;try{for(let u=0;u<this.steps.length;u+=1){let l=this.steps[u].batch(o,i.map((d,f)=>{let p=d?.getChild(this.omitSequenceTags?void 0:`seq:step:${u+1}`);return Ee(s[f],{callbacks:p})}),n);o=await lr(l,s[0]?.signal)}}catch(u){throw await Promise.all(i.map(c=>c?.handleChainError(u))),u}return await Promise.all(i.map(u=>u?.handleChainEnd(Se(o,"output")))),o}_concatOutputChunks(e,t){return this.last._concatOutputChunks(e,t)}async*_streamIterator(e,t){let n=await ct(t),{runId:s,...a}=t??{},i=await n?.handleChainStart(this.toJSON(),Se(e,"input"),s,void 0,void 0,void 0,a?.runName),o=[this.first,...this.middle,this.last],u=!0,c;async function*l(){yield e}try{let d=o[0].transform(l(),Ee(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let f=1;f<o.length;f+=1)d=await o[f].transform(d,Ee(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${f+1}`)}));for await(let f of d)if(t?.signal?.throwIfAborted(),yield f,u)if(c===void 0)c=f;else try{c=this._concatOutputChunks(c,f)}catch{c=void 0,u=!1}}catch(d){throw await i?.handleChainError(d),d}await i?.handleChainEnd(Se(c,"output"))}getGraph(e){let t=new mo,n=null;return this.steps.forEach((s,a)=>{let i=s.getGraph(e);a!==0&&i.trimFirstNode(),a!==this.steps.length-1&&i.trimLastNode(),t.extend(i);let o=i.firstNode();if(!o)throw new Error(`Runnable ${s} has no first node`);n&&t.addEdge(n,o),n=i.lastNode()}),t}pipe(e){return r.isRunnableSequence(e)?new r({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new r({first:this.first,middle:[...this.middle,this.last],last:qr(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&pe.isRunnable(e)}static from([e,...t],n){let s={};return typeof n=="string"?s.name=n:n!==void 0&&(s=n),new r({...s,first:qr(e),middle:t.slice(0,-1).map(qr),last:qr(t[t.length-1])})}},bn=class r extends pe{static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"steps",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.steps={};for(let[t,n]of Object.entries(e.steps))this.steps[t]=qr(n)}static from(e){return new r({steps:e})}async invoke(e,t){let n=ue(t),a=await(await ct(n))?.handleChainStart(this.toJSON(),{input:e},n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let i={};try{let o=Object.entries(this.steps).map(async([u,c])=>{i[u]=await c.invoke(e,Ee(n,{callbacks:a?.getChild(`map:key:${u}`)}))});await lr(Promise.all(o),t?.signal)}catch(o){throw await a?.handleChainError(o),o}return await a?.handleChainEnd(i),i}async*_transform(e,t,n){let s={...this.steps},a=Gp(e,Object.keys(s).length),i=new Map(Object.entries(s).map(([o,u],c)=>{let l=u.transform(a[c],Ee(n,{callbacks:t?.getChild(`map:key:${o}`)}));return[o,l.next().then(d=>({key:o,gen:l,result:d}))]}));for(;i.size;){let o=Promise.race(i.values()),{key:u,result:c,gen:l}=await lr(o,n?.signal);i.delete(u),c.done||(yield{[u]:c.value},i.set(u,l.next().then(d=>({key:u,gen:l,result:d}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let s=ue(t),a=new Lr({generator:this.transform(n(),s),config:s});return await a.setup,Ve.fromAsyncGenerator(a)}},qf=class r extends pe{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!Pu(e.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,t){let[n]=this._getOptionsList(t??{},1),s=await ct(n),a=this.func(Ee(n,{callbacks:s}),e);return lr(a,n?.signal)}async*_streamIterator(e,t){let[n]=this._getOptionsList(t??{},1),s=await this.invoke(e,t);if(qc(s)){for await(let a of s)n?.signal?.throwIfAborted(),yield a;return}if(Av(s)){for(;;){n?.signal?.throwIfAborted();let a=s.next();if(a.done)break;yield a.value}return}yield s}static from(e){return new r({func:e})}};Wt=class r extends pe{static lc_name(){return"RunnableLambda"}constructor(e){if(Pu(e.func))return qf.from(e.func);super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),CS(e.func),this.func=e.func}static from(e){return new r({func:e})}async _invoke(e,t,n){return new Promise((s,a)=>{let i=Ee(t,{callbacks:n?.getChild(),recursionLimit:(t?.recursionLimit??vc)-1});Xe.runWithConfig($t(i),async()=>{try{let o=await this.func(e,{...i});if(o&&pe.isRunnable(o)){if(t?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(e,{...i,recursionLimit:(i.recursionLimit??vc)-1})}else if(qc(o)){let u;for await(let c of Gc(i,o))if(t?.signal?.throwIfAborted(),u===void 0)u=c;else try{u=this._concatOutputChunks(u,c)}catch{u=c}o=u}else if(Bf(o)){let u;for(let c of Zf(i,o))if(t?.signal?.throwIfAborted(),u===void 0)u=c;else try{u=this._concatOutputChunks(u,c)}catch{u=c}o=u}s(o)}catch(o){a(o)}})})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async*_transform(e,t,n){let s;for await(let o of e)if(s===void 0)s=o;else try{s=this._concatOutputChunks(s,o)}catch{s=o}let a=Ee(n,{callbacks:t?.getChild(),recursionLimit:(n?.recursionLimit??vc)-1}),i=await new Promise((o,u)=>{Xe.runWithConfig($t(a),async()=>{try{let c=await this.func(s,{...a,config:a});o(c)}catch(c){u(c)}})});if(i&&pe.isRunnable(i)){if(n?.recursionLimit===0)throw new Error("Recursion limit reached.");let o=await i.stream(s,a);for await(let u of o)yield u}else if(qc(i))for await(let o of Gc(a,i))n?.signal?.throwIfAborted(),yield o;else if(Bf(i))for(let o of Zf(a,i))n?.signal?.throwIfAborted(),yield o;else yield i}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let s=ue(t),a=new Lr({generator:this.transform(n(),s),config:s});return await a.setup,Ve.fromAsyncGenerator(a)}},Kc=class extends pe{static lc_name(){return"RunnableWithFallbacks"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"runnable",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fallbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(let e of this.fallbacks)yield e}async invoke(e,t){let n=ue(t),s=await ct(n),{runId:a,...i}=n,o=await s?.handleChainStart(this.toJSON(),Se(e,"input"),a,void 0,void 0,void 0,i?.runName),u=Ee(i,{callbacks:o?.getChild()});return await Xe.runWithConfig(u,async()=>{let l;for(let d of this.runnables()){n?.signal?.throwIfAborted();try{let f=await d.invoke(e,u);return await o?.handleChainEnd(Se(f,"output")),f}catch(f){l===void 0&&(l=f)}}throw l===void 0?new Error("No error stored at end of fallback."):(await o?.handleChainError(l),l)})}async*_streamIterator(e,t){let n=ue(t),s=await ct(n),{runId:a,...i}=n,o=await s?.handleChainStart(this.toJSON(),Se(e,"input"),a,void 0,void 0,void 0,i?.runName),u,c;for(let d of this.runnables()){n?.signal?.throwIfAborted();let f=Ee(i,{callbacks:o?.getChild()});try{let p=await d.stream(e,f);c=Gc(f,p);break}catch(p){u===void 0&&(u=p)}}if(c===void 0){let d=u??new Error("No error stored at end of fallback.");throw await o?.handleChainError(d),d}let l;try{for await(let d of c){yield d;try{l=l===void 0?l:this._concatOutputChunks(l,d)}catch{l=void 0}}}catch(d){throw await o?.handleChainError(d),d}await o?.handleChainEnd(Se(l,"output"))}async batch(e,t,n){if(n?.returnExceptions)throw new Error("Not implemented.");let s=this._getOptionsList(t??{},e.length),a=await Promise.all(s.map(u=>ct(u))),i=await Promise.all(a.map(async(u,c)=>{let l=await u?.handleChainStart(this.toJSON(),Se(e[c],"input"),s[c].runId,void 0,void 0,void 0,s[c].runName);return delete s[c].runId,l})),o;for(let u of this.runnables()){s[0].signal?.throwIfAborted();try{let c=await u.batch(e,i.map((l,d)=>Ee(s[d],{callbacks:l?.getChild()})),n);return await Promise.all(i.map((l,d)=>l?.handleChainEnd(Se(c[d],"output")))),c}catch(c){o===void 0&&(o=c)}}throw o?(await Promise.all(i.map(u=>u?.handleChainError(o))),o):new Error("No error stored at end of fallbacks.")}};Ia=class extends pe{static lc_name(){return"RunnableAssign"}constructor(e){e instanceof bn&&(e={mapper:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mapper=e.mapper}async invoke(e,t){let n=await this.mapper.invoke(e,t);return{...e,...n}}async*_transform(e,t,n){let s=this.mapper.getStepsKeys(),[a,i]=Gp(e),o=this.mapper.transform(i,Ee(n,{callbacks:t?.getChild()})),u=o.next();for await(let 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}`);let l=Object.fromEntries(Object.entries(c).filter(([d])=>!s.includes(d)));Object.keys(l).length>0&&(yield l)}yield(await u).value;for await(let c of o)yield c}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let s=ue(t),a=new Lr({generator:this.transform(n(),s),config:s});return await a.setup,Ve.fromAsyncGenerator(a)}},Wc=class extends pe{static lc_name(){return"RunnablePick"}constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"keys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keys=e.keys}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{let t=this.keys.map(n=>[n,e[n]]).filter(n=>n[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(let t of e){let n=await this._pick(t);n!==void 0&&(yield n)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let s=ue(t),a=new Lr({generator:this.transform(n(),s),config:s});return await a.setup,Ve.fromAsyncGenerator(a)}},go=class extends mr{constructor(e){let t=Kt.from([Wt.from(async n=>{let s;if(cn(n))try{s=await Oa(this.schema,n.args)}catch{throw new cs("Received tool input did not match expected schema",JSON.stringify(n.args))}else s=n;return s}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:t,config:e.config??{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}}});var _o,Ta,Pa,Jc,yo=_(()=>{"use strict";qi();Ji();fn();_o=class extends Bt{},Ta=class extends _o{static lc_name(){return"StringPromptValue"}constructor(e){super({value:e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.value=e}toString(){return this.value}toChatMessages(){return[new ut(this.value)]}},Pa=class extends _o{static lc_name(){return"ChatPromptValue"}constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.messages=e.messages}toString(){return Yi(this.messages)}toChatMessages(){return this.messages}},Jc=class extends _o{static lc_name(){return"ImagePromptValue"}constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"imageUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new ut({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}}});var Gr,bo=_(()=>{"use strict";yo();Sa();Gr=class extends Hr{async formatPromptValue(e){let t=await this.format(e);return new Ta(t)}}});function Hf(r){return typeof r=="function"}function jS(r){return Ra(r)?"array":typeof r}function Gf(r){return r.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Iv(r,e){return r!=null&&typeof r=="object"&&e in r}function MS(r,e){return r!=null&&typeof r!="object"&&r.hasOwnProperty&&r.hasOwnProperty(e)}function LS(r,e){return zS.call(r,e)}function FS(r){return!LS(DS,r)}function BS(r){return String(r).replace(/[&<>"'`=\/]/g,function(t){return US[t]})}function HS(r,e){if(!r)return[];var t=!1,n=[],s=[],a=[],i=!1,o=!1,u="",c=0;function l(){if(i&&!o)for(;a.length;)delete s[a.pop()];else a=[];i=!1,o=!1}var d,f,p;function m(Z){if(typeof Z=="string"&&(Z=Z.split(VS,2)),!Ra(Z)||Z.length!==2)throw new Error("Invalid tags: "+Z);d=new RegExp(Gf(Z[0])+"\\s*"),f=new RegExp("\\s*"+Gf(Z[1])),p=new RegExp("\\s*"+Gf("}"+Z[1]))}m(e||Mt.tags);for(var h=new vo(r),g,w,b,x,I,P;!h.eos();){if(g=h.pos,b=h.scanUntil(d),b)for(var K=0,V=b.length;K<V;++K)x=b.charAt(K),FS(x)?(a.push(s.length),u+=x):(o=!0,t=!0,u+=" "),s.push(["text",x,g,g+1]),g+=1,x===`
79
+ `&&(l(),u="",c=0,t=!1);if(!h.scan(d))break;if(i=!0,w=h.scan(GS)||"name",h.scan(ZS),w==="="?(b=h.scanUntil(Tv),h.scan(Tv),h.scanUntil(f)):w==="{"?(b=h.scanUntil(p),h.scan(qS),h.scanUntil(f),w="&"):b=h.scanUntil(f),!h.scan(f))throw new Error("Unclosed tag at "+h.pos);if(w==">"?I=[w,b,g,h.pos,u,c,t]:I=[w,b,g,h.pos],c++,s.push(I),w==="#"||w==="^")n.push(I);else if(w==="/"){if(P=n.pop(),!P)throw new Error('Unopened section "'+b+'" at '+g);if(P[1]!==b)throw new Error('Unclosed section "'+P[1]+'" at '+g)}else w==="name"||w==="{"||w==="&"?o=!0:w==="="&&m(b)}if(l(),P=n.pop(),P)throw new Error('Unclosed section "'+P[1]+'" at '+h.pos);return WS(KS(s))}function KS(r){for(var e=[],t,n,s=0,a=r.length;s<a;++s)t=r[s],t&&(t[0]==="text"&&n&&n[0]==="text"?(n[1]+=t[1],n[3]=t[3]):(e.push(t),n=t));return e}function WS(r){for(var e=[],t=e,n=[],s,a,i=0,o=r.length;i<o;++i)switch(s=r[i],s[0]){case"#":case"^":t.push(s),n.push(s),t=s[4]=[];break;case"/":a=n.pop(),a[5]=s[2],t=n.length>0?n[n.length-1][4]:e;break;default:t.push(s)}return e}function vo(r){this.string=r,this.tail=r,this.pos=0}function ka(r,e){this.view=r,this.cache={".":this.view},this.parent=e}function Qe(){this.templateCache={_cache:{},set:function(e,t){this._cache[e]=t},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}var NS,Ra,zS,DS,US,ZS,VS,Tv,qS,GS,Mt,wo,Xc,Pv=_(()=>{"use strict";NS=Object.prototype.toString,Ra=Array.isArray||function(e){return NS.call(e)==="[object Array]"};zS=RegExp.prototype.test;DS=/\S/;US={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};ZS=/\s*/,VS=/\s+/,Tv=/\s*=/,qS=/\s*\}/,GS=/#|\^|\/|>|\{|&|=|!/;vo.prototype.eos=function(){return this.tail===""};vo.prototype.scan=function(e){var t=this.tail.match(e);if(!t||t.index!==0)return"";var n=t[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n};vo.prototype.scanUntil=function(e){var t=this.tail.search(e),n;switch(t){case-1:n=this.tail,this.tail="";break;case 0:n="";break;default:n=this.tail.substring(0,t),this.tail=this.tail.substring(t)}return this.pos+=n.length,n};ka.prototype.push=function(e){return new ka(e,this)};ka.prototype.lookup=function(e){var t=this.cache,n;if(t.hasOwnProperty(e))n=t[e];else{for(var s=this,a,i,o,u=!1;s;){if(e.indexOf(".")>0)for(a=s.view,i=e.split("."),o=0;a!=null&&o<i.length;)o===i.length-1&&(u=Iv(a,i[o])||MS(a,i[o])),a=a[i[o++]];else a=s.view[e],u=Iv(s.view,e);if(u){n=a;break}s=s.parent}t[e]=n}return Hf(n)&&(n=n.call(this.view)),n};Qe.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};Qe.prototype.parse=function(e,t){var n=this.templateCache,s=e+":"+(t||Mt.tags).join(":"),a=typeof n<"u",i=a?n.get(s):void 0;return i==null&&(i=HS(e,t),a&&n.set(s,i)),i};Qe.prototype.render=function(e,t,n,s){var a=this.getConfigTags(s),i=this.parse(e,a),o=t instanceof ka?t:new ka(t,void 0);return this.renderTokens(i,o,n,e,s)};Qe.prototype.renderTokens=function(e,t,n,s,a){for(var i="",o,u,c,l=0,d=e.length;l<d;++l)c=void 0,o=e[l],u=o[0],u==="#"?c=this.renderSection(o,t,n,s,a):u==="^"?c=this.renderInverted(o,t,n,s,a):u===">"?c=this.renderPartial(o,t,n,a):u==="&"?c=this.unescapedValue(o,t):u==="name"?c=this.escapedValue(o,t,a):u==="text"&&(c=this.rawValue(o)),c!==void 0&&(i+=c);return i};Qe.prototype.renderSection=function(e,t,n,s,a){var i=this,o="",u=t.lookup(e[1]);function c(f){return i.render(f,t,n,a)}if(u){if(Ra(u))for(var l=0,d=u.length;l<d;++l)o+=this.renderTokens(e[4],t.push(u[l]),n,s,a);else if(typeof u=="object"||typeof u=="string"||typeof u=="number")o+=this.renderTokens(e[4],t.push(u),n,s,a);else if(Hf(u)){if(typeof s!="string")throw new Error("Cannot use higher-order sections without the original template");u=u.call(t.view,s.slice(e[3],e[5]),c),u!=null&&(o+=u)}else o+=this.renderTokens(e[4],t,n,s,a);return o}};Qe.prototype.renderInverted=function(e,t,n,s,a){var i=t.lookup(e[1]);if(!i||Ra(i)&&i.length===0)return this.renderTokens(e[4],t,n,s,a)};Qe.prototype.indentPartial=function(e,t,n){for(var s=t.replace(/[^ \t]/g,""),a=e.split(`
80
+ `),i=0;i<a.length;i++)a[i].length&&(i>0||!n)&&(a[i]=s+a[i]);return a.join(`
81
+ `)};Qe.prototype.renderPartial=function(e,t,n,s){if(n){var a=this.getConfigTags(s),i=Hf(n)?n(e[1]):n[e[1]];if(i!=null){var o=e[6],u=e[5],c=e[4],l=i;u==0&&c&&(l=this.indentPartial(i,c,o));var d=this.parse(l,a);return this.renderTokens(d,t,n,l,s)}}};Qe.prototype.unescapedValue=function(e,t){var n=t.lookup(e[1]);if(n!=null)return n};Qe.prototype.escapedValue=function(e,t,n){var s=this.getConfigEscape(n)||Mt.escape,a=t.lookup(e[1]);if(a!=null)return typeof a=="number"&&s===Mt.escape?String(a):s(a)};Qe.prototype.rawValue=function(e){return e[1]};Qe.prototype.getConfigTags=function(e){return Ra(e)?e:e&&typeof e=="object"?e.tags:void 0};Qe.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!Ra(e))return e.escape};Mt={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(r){wo.templateCache=r},get templateCache(){return wo.templateCache}},wo=new Qe;Mt.clearCache=function(){return wo.clearCache()};Mt.parse=function(e,t){return wo.parse(e,t)};Mt.render=function(e,t,n,s){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+jS(e)+'" was given as the first argument for mustache#render(template, view, partials)');return wo.render(e,t,n,s)};Mt.escape=BS;Mt.Scanner=vo;Mt.Context=ka;Mt.Writer=Qe;Xc=Mt});function Sv(){Xc.escape=r=>r}var xo,kv,Yc,JS,XS,Kf,YS,pt,Eo,bs,ws=_(()=>{"use strict";Pv();Ki();xo=r=>{let e=r.split(""),t=[],n=(a,i)=>{for(let o=i;o<e.length;o+=1)if(a.includes(e[o]))return o;return-1},s=0;for(;s<e.length;)if(e[s]==="{"&&s+1<e.length&&e[s+1]==="{")t.push({type:"literal",text:"{"}),s+=2;else if(e[s]==="}"&&s+1<e.length&&e[s+1]==="}")t.push({type:"literal",text:"}"}),s+=2;else if(e[s]==="{"){let a=n("}",s);if(a<0)throw new Error("Unclosed '{' in template.");t.push({type:"variable",name:e.slice(s+1,a).join("")}),s=a+1}else{if(e[s]==="}")throw new Error("Single '}' in template.");{let a=n("{}",s),i=(a<0?e.slice(s):e.slice(s,a)).join("");t.push({type:"literal",text:i}),s=a<0?e.length:a}}return t},kv=(r,e=[])=>{let t=[];for(let n of r)if(n[0]==="name"){let s=n[1].includes(".")?n[1].split(".")[0]:n[1];t.push({type:"variable",name:s})}else if(["#","&","^",">"].includes(n[0])){if(t.push({type:"variable",name:n[1]}),n[0]==="#"&&n.length>4&&Array.isArray(n[4])){let s=[...e,n[1]],a=kv(n[4],s);t.push(...a)}}else t.push({type:"literal",text:n[1]});return t},Yc=r=>{Sv();let e=Xc.parse(r);return kv(e)},JS=(r,e)=>xo(r).reduce((t,n)=>{if(n.type==="variable"){if(n.name in e){let s=typeof e[n.name]=="string"?e[n.name]:JSON.stringify(e[n.name]);return t+s}throw new Error(`(f-string) Missing value for input ${n.name}`)}return t+n.text},""),XS=(r,e)=>(Sv(),Xc.render(r,e)),Kf={"f-string":JS,mustache:XS},YS={"f-string":xo,mustache:Yc},pt=(r,e,t)=>{try{return Kf[e](r,t)}catch(n){throw un(n,"INVALID_PROMPT_INPUT")}},Eo=(r,e)=>YS[e](r),bs=(r,e,t)=>{if(!(e in Kf)){let n=Object.keys(Kf);throw new Error(`Invalid template format. Got \`${e}\`;
82
+ should be one of ${n}`)}try{let n=t.reduce((s,a)=>(s[a]="foo",s),{});Array.isArray(r)?r.forEach(s=>{if(s.type==="text")pt(s.text,e,n);else if(s.type==="image_url")if(typeof s.image_url=="string")pt(s.image_url,e,n);else{let a=s.image_url.url;pt(a,e,n)}else throw new Error(`Invalid message template received. ${JSON.stringify(s,null,2)}`)}):pt(r,e,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}}});var Wf={};du(Wf,{PromptTemplate:()=>zt});var zt,Ca=_(()=>{"use strict";bo();ws();zt=class r extends Gr{static lc_name(){return"PromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"additionalContentFields",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let t=this.inputVariables;this.partialVariables&&(t=t.concat(Object.keys(this.partialVariables))),bs(this.template,this.templateFormat,t)}}_getPromptType(){return"prompt"}async format(e){let t=await this.mergePartialAndUserVariables(e);return pt(this.template,this.templateFormat,t)}static fromExamples(e,t,n,s=`
83
+
84
+ `,a=""){let i=[a,...e,t].join(s);return new r({inputVariables:n,template:i})}static fromTemplate(e,t){let{templateFormat:n="f-string",...s}=t??{},a=new Set;return Eo(e,n).forEach(i=>{i.type==="variable"&&a.add(i.name)}),new r({inputVariables:[...a],templateFormat:n,template:e,...s})}async partial(e){let t=this.inputVariables.filter(a=>!(a in e)),n={...this.partialVariables??{},...e},s={...this,inputVariables:t,partialVariables:n};return new r(s)}serialize(){if(this.outputParser!==void 0)throw new Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(e){if(!e.template)throw new Error("Prompt template must have a template");return new r({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}}});var Rv=_(()=>{"use strict";dt();ls();Ct();fc();mc();Ji();hc();gc();pa();fn()});var $a=_(()=>{"use strict";ls();Ct();fc();mc();Ji();gc();fn();Rv();hc();Rp();pa()});var Na,Jf=_(()=>{"use strict";yo();Sa();ws();Na=class r extends Hr{static lc_name(){return"ImagePromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","image"]}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"additionalContentFields",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.template=e.template,this.templateFormat=e.templateFormat??this.templateFormat,this.validateTemplate=e.validateTemplate??this.validateTemplate,this.additionalContentFields=e.additionalContentFields,this.validateTemplate){let t=this.inputVariables;this.partialVariables&&(t=t.concat(Object.keys(this.partialVariables))),bs([{type:"image_url",image_url:this.template}],this.templateFormat,t)}}_getPromptType(){return"prompt"}async partial(e){let t=this.inputVariables.filter(a=>!(a in e)),n={...this.partialVariables??{},...e},s={...this,inputVariables:t,partialVariables:n};return new r(s)}async format(e){let t={};for(let[i,o]of Object.entries(this.template))typeof o=="string"?t[i]=pt(o,this.templateFormat,e):t[i]=o;let n=e.url||t.url,s=e.detail||t.detail;if(!n)throw new Error("Must provide either an image URL.");if(typeof n!="string")throw new Error("url must be a string.");let a={url:n};return s&&(a.detail=s),a}async formatPromptValue(e){let t=await this.format(e);return new Jc(t)}}});function Xf(r,e){let t=[];for(let n of Object.values(r))if(typeof n=="string")Eo(n,e).forEach(s=>{s.type==="variable"&&t.push(s.name)});else if(Array.isArray(n))for(let s of n)typeof s=="string"?Eo(s,e).forEach(a=>{a.type==="variable"&&t.push(a.name)}):typeof s=="object"&&t.push(...Xf(s,e));else typeof n=="object"&&n!==null&&t.push(...Xf(n,e));return Array.from(new Set(t))}function Yf(r,e,t){let n={};for(let[s,a]of Object.entries(r))if(typeof a=="string")n[s]=pt(a,t,e);else if(Array.isArray(a)){let i=[];for(let o of a)typeof o=="string"?i.push(pt(o,t,e)):typeof o=="object"&&i.push(Yf(o,e,t));n[s]=i}else typeof a=="object"&&a!==null?n[s]=Yf(a,e,t):n[s]=a;return n}var Ao,Qf=_(()=>{"use strict";dt();ws();Ao=class extends pe{static lc_name(){return"DictPromptTemplate"}constructor(e){let t=e.templateFormat??"f-string",n=Xf(e.template,t);super({inputVariables:n,...e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","dict"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.template=e.template,this.templateFormat=t,this.inputVariables=n}async format(e){return Yf(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}}});function QS(r){return r===null||typeof r!="object"||Array.isArray(r)?!1:Object.keys(r).length===1&&"text"in r&&typeof r.text=="string"}function ek(r){return r===null||typeof r!="object"||Array.isArray(r)?!1:"image_url"in r&&(typeof r.image_url=="string"||typeof r.image_url=="object"&&r.image_url!==null&&"url"in r.image_url&&typeof r.image_url.url=="string")}function tk(r){return typeof r.formatMessages=="function"}function rk(r,e){if(tk(r)||cr(r))return r;if(Array.isArray(r)&&r[0]==="placeholder"){let s=r[1];if(e?.templateFormat==="mustache"&&typeof s=="string"&&s.slice(0,2)==="{{"&&s.slice(-2)==="}}"){let a=s.slice(2,-2);return new Qc({variableName:a,optional:!0})}else if(typeof s=="string"&&s[0]==="{"&&s[s.length-1]==="}"){let a=s.slice(1,-1);return new Qc({variableName:a,optional:!0})}throw new Error(`Invalid placeholder template for format ${e?.templateFormat??'"f-string"'}: "${r[1]}". Expected a variable name surrounded by ${e?.templateFormat==="mustache"?"double":"single"} curly braces.`)}let t=Vt(r),n;if(typeof t.content=="string"?n=t.content:n=t.content.map(s=>"text"in s?{...s,text:s.text}:"image_url"in s?{...s,image_url:s.image_url}:s),t._getType()==="human")return el.fromTemplate(n,e);if(t._getType()==="ai")return rm.fromTemplate(n,e);if(t._getType()==="system")return nm.fromTemplate(n,e);if(Zt.isInstance(t))return tm.fromTemplate(t.content,t.role,e);throw new Error(`Could not coerce message prompt template from input. Received message type: "${t._getType()}".`)}function nk(r){return r.constructor.lc_name()==="MessagesPlaceholder"}var Oo,Qc,em,Io,tm,To,el,rm,nm,ja,Po=_(()=>{"use strict";$a();yo();dt();bo();Sa();Ca();Jf();ws();Ki();Qf();Oo=class extends pe{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","chat"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}async invoke(e,t){return this._callWithConfig(n=>this.formatMessages(n),e,{...t,runType:"prompt"})}},Qc=class extends Oo{static lc_name(){return"MessagesPlaceholder"}constructor(e){typeof e=="string"&&(e={variableName:e}),super(e),Object.defineProperty(this,"variableName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"optional",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.variableName=e.variableName,this.optional=e.optional??!1}get inputVariables(){return[this.variableName]}async formatMessages(e){let t=e[this.variableName];if(this.optional&&!t)return[];if(!t){let s=new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw s.name="InputFormatError",s}let n;try{Array.isArray(t)?n=t.map(Vt):n=[Vt(t)]}catch(s){let a=typeof t=="string"?t:JSON.stringify(t,null,2),i=new Error([`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,`Received value: ${a}`,`Additional message: ${s.message}`].join(`
85
+
86
+ `));throw i.name="InputFormatError",i.lc_error_code=s.lc_error_code,i}return n}},em=class extends Oo{constructor(e){"prompt"in e||(e={prompt:e}),super(e),Object.defineProperty(this,"prompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},Io=class extends Hr{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){let t=await this.formatMessages(e);return new Pa(t)}},tm=class extends em{static lc_name(){return"ChatMessagePromptTemplate"}constructor(e,t){"prompt"in e||(e={prompt:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}async format(e){return new Zt(await this.prompt.format(e),this.role)}static fromTemplate(e,t,n){return new this(zt.fromTemplate(e,{templateFormat:n?.templateFormat}),t)}};To=class extends Oo{static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}constructor(e,t){if("prompt"in e||(e={prompt:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","chat"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"additionalOptions",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"prompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"messageClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chatMessageClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.prompt=e.prompt,Array.isArray(this.prompt)){let n=[];this.prompt.forEach(s=>{"inputVariables"in s&&(n=n.concat(s.inputVariables))}),this.inputVariables=n}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=t??this.additionalOptions}createMessage(e){let t=this.constructor;if(t._messageClass()){let n=t._messageClass();return new n({content:e})}else if(t.chatMessageClass){let n=t.chatMessageClass();return new n({content:e,role:this.getRoleFromMessageClass(n.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(e){switch(e){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(e,t){if(typeof e=="string")return new this(zt.fromTemplate(e,t));let n=[];for(let s of e)if(typeof s=="string")n.push(zt.fromTemplate(s,t));else if(s!==null)if(QS(s)){let a="";typeof s.text=="string"&&(a=s.text??"");let i={...t,additionalContentFields:s};n.push(zt.fromTemplate(a,i))}else if(ek(s)){let a=s.image_url??"",i,o=[];if(typeof a=="string"){let u;t?.templateFormat==="mustache"?u=Yc(a):u=xo(a);let c=u.flatMap(l=>l.type==="variable"?[l.name]:[]);if((c?.length??0)>0){if(c.length>1)throw new Error(`Only one format variable allowed per image template.
87
+ Got: ${c}
88
+ From: ${a}`);o=[c[0]]}else o=[];a={url:a},i=new Na({template:a,inputVariables:o,templateFormat:t?.templateFormat,additionalContentFields:s})}else if(typeof a=="object"){if("url"in a){let u;t?.templateFormat==="mustache"?u=Yc(a.url):u=xo(a.url),o=u.flatMap(c=>c.type==="variable"?[c.name]:[])}else o=[];i=new Na({template:a,inputVariables:o,templateFormat:t?.templateFormat,additionalContentFields:s})}else throw new Error("Invalid image template");n.push(i)}else typeof s=="object"&&n.push(new Ao({template:s,templateFormat:t?.templateFormat}));return new this({prompt:n,additionalOptions:t})}async format(e){if(this.prompt instanceof Gr){let t=await this.prompt.format(e);return this.createMessage(t)}else{let t=[];for(let n of this.prompt){let s={};if(!("inputVariables"in n))throw new Error(`Prompt ${n} does not have inputVariables defined.`);for(let a of n.inputVariables)s||(s={[a]:e[a]}),s={...s,[a]:e[a]};if(n instanceof Gr){let a=await n.format(s),i;"additionalContentFields"in n&&(i=n.additionalContentFields),a!==""&&t.push({...i,type:"text",text:a})}else if(n instanceof Na){let a=await n.format(s),i;"additionalContentFields"in n&&(i=n.additionalContentFields),t.push({...i,type:"image_url",image_url:a})}else if(n instanceof Ao){let a=await n.format(s),i;"additionalContentFields"in n&&(i=n.additionalContentFields),t.push({...i,...a})}}return this.createMessage(t)}}async formatMessages(e){return[await this.format(e)]}},el=class extends To{static _messageClass(){return ut}static lc_name(){return"HumanMessagePromptTemplate"}},rm=class extends To{static _messageClass(){return Je}static lc_name(){return"AIMessagePromptTemplate"}},nm=class extends To{static _messageClass(){return dn}static lc_name(){return"SystemMessagePromptTemplate"}};ja=class r extends Io{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}constructor(e){if(super(e),Object.defineProperty(this,"promptMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){let t=new Set;for(let o of this.promptMessages)if(!(o instanceof Ie))for(let u of o.inputVariables)t.add(u);let n=this.inputVariables,s=new Set(this.partialVariables?n.concat(Object.keys(this.partialVariables)):n),a=new Set([...s].filter(o=>!t.has(o)));if(a.size>0)throw new Error(`Input variables \`${[...a]}\` are not used in any of the prompt messages.`);let i=new Set([...t].filter(o=>!s.has(o)));if(i.size>0)throw new Error(`Input variables \`${[...i]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async _parseImagePrompts(e,t){if(typeof e.content=="string")return e;let n=await Promise.all(e.content.map(async s=>{if(s.type!=="image_url")return s;let a="";typeof s.image_url=="string"?a=s.image_url:a=s.image_url.url;let o=await zt.fromTemplate(a,{templateFormat:this.templateFormat}).format(t);return typeof s.image_url!="string"&&"url"in s.image_url?s.image_url.url=o:s.image_url=o,s}));return e.content=n,e}async formatMessages(e){let t=await this.mergePartialAndUserVariables(e),n=[];for(let s of this.promptMessages)if(s instanceof Ie)n.push(await this._parseImagePrompts(s,t));else{let a;this.templateFormat==="mustache"?a={...t}:a=s.inputVariables.reduce((o,u)=>{if(!(u in t)&&!(nk(s)&&s.optional))throw un(new Error(`Missing value for input variable \`${u.toString()}\``),"INVALID_PROMPT_INPUT");return o[u]=t[u],o},{});let i=await s.formatMessages(a);n=n.concat(i)}return n}async partial(e){let t=this.inputVariables.filter(a=>!(a in e)),n={...this.partialVariables??{},...e},s={...this,inputVariables:t,partialVariables:n};return new r(s)}static fromTemplate(e,t){let n=zt.fromTemplate(e,t),s=new el({prompt:n});return this.fromMessages([s])}static fromMessages(e,t){let n=e.reduce((i,o)=>i.concat(o instanceof r?o.promptMessages:[rk(o,t)]),[]),s=e.reduce((i,o)=>o instanceof r?Object.assign(i,o.partialVariables):i,Object.create(null)),a=new Set;for(let i of n)if(!(i instanceof Ie))for(let o of i.inputVariables)o in s||a.add(o);return new this({...t,inputVariables:[...a],promptMessages:n,partialVariables:s,templateFormat:t?.templateFormat})}static fromPromptMessages(e){return this.fromMessages(e)}}});var Cv={};du(Cv,{FewShotChatMessagePromptTemplate:()=>am,FewShotPromptTemplate:()=>sm});var sm,am,im=_(()=>{"use strict";bo();ws();Ca();Po();sm=class r extends Gr{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleSelector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"examplePrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"suffix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"exampleSeparator",{enumerable:!0,configurable:!0,writable:!0,value:`
89
+
90
+ `}),Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.assign(this,e),this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let t=this.inputVariables;this.partialVariables&&(t=t.concat(Object.keys(this.partialVariables))),bs(this.prefix+this.suffix,this.templateFormat,t)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(e){let t=this.inputVariables.filter(a=>!(a in e)),n={...this.partialVariables??{},...e},s={...this,inputVariables:t,partialVariables:n};return new r(s)}async format(e){let t=await this.mergePartialAndUserVariables(e),n=await this.getExamples(t),s=await Promise.all(n.map(i=>this.examplePrompt.format(i))),a=[this.prefix,...s,this.suffix].join(this.exampleSeparator);return pt(a,this.templateFormat,t)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(e){let{example_prompt:t}=e;if(!t)throw new Error("Missing example prompt");let n=await zt.deserialize(t),s;if(Array.isArray(e.examples))s=e.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new r({inputVariables:e.input_variables,examplePrompt:n,examples:s,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}},am=class r extends Io{_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleSelector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"examplePrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"suffix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"exampleSeparator",{enumerable:!0,configurable:!0,writable:!0,value:`
91
+
92
+ `}),Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.examples=e.examples,this.examplePrompt=e.examplePrompt,this.exampleSeparator=e.exampleSeparator??`
93
+
94
+ `,this.exampleSelector=e.exampleSelector,this.prefix=e.prefix??"",this.suffix=e.suffix??"",this.templateFormat=e.templateFormat??"f-string",this.validateTemplate=e.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let t=this.inputVariables;this.partialVariables&&(t=t.concat(Object.keys(this.partialVariables))),bs(this.prefix+this.suffix,this.templateFormat,t)}}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(e){let t=await this.mergePartialAndUserVariables(e),n=await this.getExamples(t);n=n.map(a=>{let i={};return this.examplePrompt.inputVariables.forEach(o=>{i[o]=a[o]}),i});let s=[];for(let a of n){let i=await this.examplePrompt.formatMessages(a);s.push(...i)}return s}async format(e){let t=await this.mergePartialAndUserVariables(e),n=await this.getExamples(t),a=(await Promise.all(n.map(o=>this.examplePrompt.formatMessages(o)))).flat().map(o=>o.content),i=[this.prefix,...a,this.suffix].join(this.exampleSeparator);return pt(i,this.templateFormat,t)}async partial(e){let t=this.inputVariables.filter(a=>!(a in e)),n={...this.partialVariables??{},...e},s={...this,inputVariables:t,partialVariables:n};return new r(s)}}});var Hr,Sa=_(()=>{"use strict";dt();Hr=class extends pe{get lc_attributes(){return{partialVariables:void 0}}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts",this._getPromptType()]}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputParser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"partialVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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});let{inputVariables:t}=e;if(t.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}async mergePartialAndUserVariables(e){let t=this.partialVariables??{},n={};for(let[a,i]of Object.entries(t))typeof i=="string"?n[a]=i:n[a]=await i();return{...n,...e}}async invoke(e,t){let n={...this.metadata,...t?.metadata},s=[...this.tags??[],...t?.tags??[]];return this._callWithConfig(a=>this.formatPromptValue(a),e,{...t,tags:s,metadata:n,runType:"prompt"})}serialize(){throw new Error("Use .toJSON() instead")}static async deserialize(e){switch(e._type){case"prompt":{let{PromptTemplate:t}=await Promise.resolve().then(()=>(Ca(),Wf));return t.deserialize(e)}case void 0:{let{PromptTemplate:t}=await Promise.resolve().then(()=>(Ca(),Wf));return t.deserialize({...e,_type:"prompt"})}case"few_shot":{let{FewShotPromptTemplate:t}=await Promise.resolve().then(()=>(im(),Cv));return t.deserialize(e)}default:throw new Error(`Invalid prompt type in config: ${e._type}`)}}}});var Lx=D(Rl=>{"use strict";Rl.byteLength=AR;Rl.toByteArray=IR;Rl.fromByteArray=SR;var Ir=[],Lt=[],ER=typeof Uint8Array<"u"?Uint8Array:Array,Hm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Zs=0,Mx=Hm.length;Zs<Mx;++Zs)Ir[Zs]=Hm[Zs],Lt[Hm.charCodeAt(Zs)]=Zs;var Zs,Mx;Lt[45]=62;Lt[95]=63;function zx(r){var e=r.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=r.indexOf("=");t===-1&&(t=e);var n=t===e?0:4-t%4;return[t,n]}function AR(r){var e=zx(r),t=e[0],n=e[1];return(t+n)*3/4-n}function OR(r,e,t){return(e+t)*3/4-t}function IR(r){var e,t=zx(r),n=t[0],s=t[1],a=new ER(OR(r,n,s)),i=0,o=s>0?n-4:n,u;for(u=0;u<o;u+=4)e=Lt[r.charCodeAt(u)]<<18|Lt[r.charCodeAt(u+1)]<<12|Lt[r.charCodeAt(u+2)]<<6|Lt[r.charCodeAt(u+3)],a[i++]=e>>16&255,a[i++]=e>>8&255,a[i++]=e&255;return s===2&&(e=Lt[r.charCodeAt(u)]<<2|Lt[r.charCodeAt(u+1)]>>4,a[i++]=e&255),s===1&&(e=Lt[r.charCodeAt(u)]<<10|Lt[r.charCodeAt(u+1)]<<4|Lt[r.charCodeAt(u+2)]>>2,a[i++]=e>>8&255,a[i++]=e&255),a}function TR(r){return Ir[r>>18&63]+Ir[r>>12&63]+Ir[r>>6&63]+Ir[r&63]}function PR(r,e,t){for(var n,s=[],a=e;a<t;a+=3)n=(r[a]<<16&16711680)+(r[a+1]<<8&65280)+(r[a+2]&255),s.push(TR(n));return s.join("")}function SR(r){for(var e,t=r.length,n=t%3,s=[],a=16383,i=0,o=t-n;i<o;i+=a)s.push(PR(r,i,i+a>o?o:i+a));return n===1?(e=r[t-1],s.push(Ir[e>>2]+Ir[e<<4&63]+"==")):n===2&&(e=(r[t-2]<<8)+r[t-1],s.push(Ir[e>>10]+Ir[e>>4&63]+Ir[e<<2&63]+"=")),s.join("")}});Sa();Po();im();Sa();Po();Ca();bo();ws();Jf();dt();Po();Qf();dt();zr();Fr();dt();zr();var hr=class extends pe{static lc_name(){return"RunnablePassthrough"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e&&(this.func=e.func)}async invoke(e,t){let n=ue(t);return this.func&&await this.func(e,n),this._callWithConfig(s=>Promise.resolve(s),e,n)}async*transform(e,t){let n=ue(t),s,a=!0;for await(let i of this._transformStreamWithConfig(e,o=>o,n))if(yield i,a)if(s===void 0)s=i;else try{s=Dr(s,i)}catch{s=void 0,a=!1}this.func&&s!==void 0&&await this.func(s,n)}static assign(e){return new Ia(new bn({steps:e}))}};dt();zr();dt();zr();Fr();$a();dt();function U(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t}function y(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}var om=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return om=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};function So(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var ko=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};var j=class extends Error{},ke=class r extends j{constructor(e,t,n,s){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;let a=t;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new wn({message:n,cause:ko(t)});let a=t?.error;return e===400?new Ma(e,a,n,s):e===401?new za(e,a,n,s):e===403?new La(e,a,n,s):e===404?new Da(e,a,n,s):e===409?new Fa(e,a,n,s):e===422?new Ua(e,a,n,s):e===429?new Ba(e,a,n,s):e>=500?new Za(e,a,n,s):new r(e,a,n,s)}},be=class extends ke{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},wn=class extends ke{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},gr=class extends wn{constructor({message:e}={}){super({message:e??"Request timed out."})}},Ma=class extends ke{},za=class extends ke{},La=class extends ke{},Da=class extends ke{},Fa=class extends ke{},Ua=class extends ke{},Ba=class extends ke{},Za=class extends ke{},Va=class extends j{constructor(){super("Could not parse response content as the length limit was reached")}},qa=class extends j{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},_r=class extends Error{constructor(e){super(e)}};var ak=/^[a-z][a-z0-9+.-]*:/i,$v=r=>ak.test(r),qe=r=>(qe=Array.isArray,qe(r)),um=qe;function Nv(r){return typeof r!="object"?{}:r??{}}function jv(r){if(!r)return!0;for(let e in r)return!1;return!0}function Mv(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function Ro(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}var zv=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new j(`${r} must be an integer`);if(e<0)throw new j(`${r} must be a positive integer`);return e};var Lv=r=>{try{return JSON.parse(r)}catch{return}};var yr=r=>new Promise(e=>setTimeout(e,r));var vn="5.12.2";var Bv=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function ik(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var ok=()=>{let r=ik();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":vn,"X-Stainless-OS":Fv(Deno.build.os),"X-Stainless-Arch":Dv(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":vn,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":vn,"X-Stainless-OS":Fv(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Dv(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=uk();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":vn,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":vn,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function uk(){if(typeof navigator>"u"||!navigator)return null;let r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let s=n[1]||0,a=n[2]||0,i=n[3]||0;return{browser:e,version:`${s}.${a}.${i}`}}}return null}var Dv=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Fv=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),Uv,Zv=()=>Uv??(Uv=ok());function Vv(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function cm(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function tl(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return cm({start(){},async pull(t){let{done:n,value:s}=await e.next();n?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function lm(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function qv(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}var Gv=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var rl="RFC3986",dm=r=>String(r),nl={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:dm},pm="RFC1738";var sl=(r,e)=>(sl=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),sl(r,e)),br=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var fm=1024,Hv=(r,e,t,n,s)=>{if(r.length===0)return r;let a=r;if(typeof r=="symbol"?a=Symbol.prototype.toString.call(r):typeof r!="string"&&(a=String(r)),t==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let i="";for(let o=0;o<a.length;o+=fm){let u=a.length>=fm?a.slice(o,o+fm):a,c=[];for(let l=0;l<u.length;++l){let d=u.charCodeAt(l);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||s===pm&&(d===40||d===41)){c[c.length]=u.charAt(l);continue}if(d<128){c[c.length]=br[d];continue}if(d<2048){c[c.length]=br[192|d>>6]+br[128|d&63];continue}if(d<55296||d>=57344){c[c.length]=br[224|d>>12]+br[128|d>>6&63]+br[128|d&63];continue}l+=1,d=65536+((d&1023)<<10|u.charCodeAt(l)&1023),c[c.length]=br[240|d>>18]+br[128|d>>12&63]+br[128|d>>6&63]+br[128|d&63]}i+=c.join("")}return i};function Kv(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function mm(r,e){if(qe(r)){let t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}var Jv={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},Xv=function(r,e){Array.prototype.push.apply(r,qe(e)?e:[e])},Wv,Re={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Hv,encodeValuesOnly:!1,format:rl,formatter:dm,indices:!1,serializeDate(r){return(Wv??(Wv=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function dk(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var hm={};function Yv(r,e,t,n,s,a,i,o,u,c,l,d,f,p,m,h,g,w){let b=r,x=w,I=0,P=!1;for(;(x=x.get(hm))!==void 0&&!P;){let de=x.get(r);if(I+=1,typeof de<"u"){if(de===I)throw new RangeError("Cyclic object value");P=!0}typeof x.get(hm)>"u"&&(I=0)}if(typeof c=="function"?b=c(e,b):b instanceof Date?b=f?.(b):t==="comma"&&qe(b)&&(b=mm(b,function(de){return de instanceof Date?f?.(de):de})),b===null){if(a)return u&&!h?u(e,Re.encoder,g,"key",p):e;b=""}if(dk(b)||Kv(b)){if(u){let de=h?e:u(e,Re.encoder,g,"key",p);return[m?.(de)+"="+m?.(u(b,Re.encoder,g,"value",p))]}return[m?.(e)+"="+m?.(String(b))]}let K=[];if(typeof b>"u")return K;let V;if(t==="comma"&&qe(b))h&&u&&(b=mm(b,u)),V=[{value:b.length>0?b.join(",")||null:void 0}];else if(qe(c))V=c;else{let de=Object.keys(b);V=l?de.sort(l):de}let Z=o?String(e).replace(/\./g,"%2E"):String(e),oe=n&&qe(b)&&b.length===1?Z+"[]":Z;if(s&&qe(b)&&b.length===0)return oe+"[]";for(let de=0;de<V.length;++de){let fe=V[de],nr=typeof fe=="object"&&typeof fe.value<"u"?fe.value:b[fe];if(i&&nr===null)continue;let Ws=d&&o?fe.replace(/\./g,"%2E"):fe,Ei=qe(b)?typeof t=="function"?t(oe,Ws):oe:oe+(d?"."+Ws:"["+Ws+"]");w.set(r,I);let Js=new WeakMap;Js.set(hm,w),Xv(K,Yv(nr,Ei,t,n,s,a,i,o,t==="comma"&&h&&qe(b)?null:u,c,l,d,f,p,m,h,g,Js))}return K}function pk(r=Re){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||Re.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=rl;if(typeof r.format<"u"){if(!sl(nl,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=nl[t],s=Re.filter;(typeof r.filter=="function"||qe(r.filter))&&(s=r.filter);let a;if(r.arrayFormat&&r.arrayFormat in Jv?a=r.arrayFormat:"indices"in r?a=r.indices?"indices":"repeat":a=Re.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:Re.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:Re.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:Re.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:Re.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?Re.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:Re.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:Re.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:Re.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:Re.encodeValuesOnly,filter:s,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:Re.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:Re.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:Re.strictNullHandling}}function gm(r,e={}){let t=r,n=pk(e),s,a;typeof n.filter=="function"?(a=n.filter,t=a("",t)):qe(n.filter)&&(a=n.filter,s=a);let i=[];if(typeof t!="object"||t===null)return"";let o=Jv[n.arrayFormat],u=o==="comma"&&n.commaRoundTrip;s||(s=Object.keys(t)),n.sort&&s.sort(n.sort);let c=new WeakMap;for(let f=0;f<s.length;++f){let p=s[f];n.skipNulls&&t[p]===null||Xv(i,Yv(t[p],p,o,u,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,c))}let l=i.join(n.delimiter),d=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),l.length>0?d+l:""}function tx(r){let e=0;for(let s of r)e+=s.length;let t=new Uint8Array(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}var Qv;function Ga(r){let e;return(Qv??(e=new globalThis.TextEncoder,Qv=e.encode.bind(e)))(r)}var ex;function _m(r){let e;return(ex??(e=new globalThis.TextDecoder,ex=e.decode.bind(e)))(r)}var bt,wt,vs=class{constructor(){bt.set(this,void 0),wt.set(this,void 0),U(this,bt,new Uint8Array,"f"),U(this,wt,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Ga(e):e;U(this,bt,tx([y(this,bt,"f"),t]),"f");let n=[],s;for(;(s=mk(y(this,bt,"f"),y(this,wt,"f")))!=null;){if(s.carriage&&y(this,wt,"f")==null){U(this,wt,s.index,"f");continue}if(y(this,wt,"f")!=null&&(s.index!==y(this,wt,"f")+1||s.carriage)){n.push(_m(y(this,bt,"f").subarray(0,y(this,wt,"f")-1))),U(this,bt,y(this,bt,"f").subarray(y(this,wt,"f")),"f"),U(this,wt,null,"f");continue}let a=y(this,wt,"f")!==null?s.preceding-1:s.preceding,i=_m(y(this,bt,"f").subarray(0,a));n.push(i),U(this,bt,y(this,bt,"f").subarray(s.index),"f"),U(this,wt,null,"f")}return n}flush(){return y(this,bt,"f").length?this.decode(`
95
+ `):[]}};bt=new WeakMap,wt=new WeakMap;vs.NEWLINE_CHARS=new Set([`
96
+ `,"\r"]);vs.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function mk(r,e){for(let s=e??0;s<r.length;s++){if(r[s]===10)return{preceding:s,index:s+1,carriage:!1};if(r[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function rx(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}var il={off:0,error:200,warn:300,info:400,debug:500},ym=(r,e,t)=>{if(r){if(Mv(il,r))return r;Ae(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(il))}`)}};function Co(){}function al(r,e,t){return!e||il[r]>il[t]?Co:e[r].bind(e)}var hk={error:Co,warn:Co,info:Co,debug:Co},nx=new WeakMap;function Ae(r){let e=r.logger,t=r.logLevel??"off";if(!e)return hk;let n=nx.get(e);if(n&&n[0]===t)return n[1];let s={error:al("error",e,t),warn:al("warn",e,t),info:al("info",e,t),debug:al("debug",e,t)};return nx.set(e,[t,s]),s}var Kr=r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r);var $o,wr=class r{constructor(e,t,n){this.iterator=e,$o.set(this,void 0),this.controller=t,U(this,$o,n,"f")}static fromSSEResponse(e,t,n){let s=!1,a=n?Ae(n):console;async function*i(){if(s)throw new j("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(let u of gk(e,t))if(!o){if(u.data.startsWith("[DONE]")){o=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let c;try{c=JSON.parse(u.data)}catch(l){throw a.error("Could not parse message into JSON:",u.data),a.error("From chunk:",u.raw),l}if(c&&c.error)throw new ke(void 0,c.error,void 0,e.headers);yield c}else{let c;try{c=JSON.parse(u.data)}catch(l){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),l}if(u.event=="error")throw new ke(void 0,c.error,c.message,void 0);yield{event:u.event,data:c}}}o=!0}catch(u){if(So(u))return;throw u}finally{o||t.abort()}}return new r(i,t,n)}static fromReadableStream(e,t,n){let s=!1;async function*a(){let o=new vs,u=lm(e);for await(let c of u)for(let l of o.decode(c))yield l;for(let c of o.flush())yield c}async function*i(){if(s)throw new j("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(let u of a())o||u&&(yield JSON.parse(u));o=!0}catch(u){if(So(u))return;throw u}finally{o||t.abort()}}return new r(i,t,n)}[($o=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),s=a=>({next:()=>{if(a.length===0){let i=n.next();e.push(i),t.push(i)}return a.shift()}});return[new r(()=>s(e),this.controller,y(this,$o,"f")),new r(()=>s(t),this.controller,y(this,$o,"f"))]}toReadableStream(){let e=this,t;return cm({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:s,done:a}=await t.next();if(a)return n.close();let i=Ga(JSON.stringify(s)+`
97
+ `);n.enqueue(i)}catch(s){n.error(s)}},async cancel(){await t.return?.()}})}};async function*gk(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new j("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new j("Attempted to iterate over a response with no body");let t=new bm,n=new vs,s=lm(r.body);for await(let a of _k(s))for(let i of n.decode(a)){let o=t.decode(i);o&&(yield o)}for(let a of n.flush()){let i=t.decode(a);i&&(yield i)}}async function*_k(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Ga(t):t,s=new Uint8Array(e.length+n.length);s.set(e),s.set(n,e.length),e=s;let a;for(;(a=rx(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}var bm=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let a={event:this.event,data:this.data.join(`
98
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,s]=yk(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}};function yk(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}async function ol(r,e){let{response:t,requestLogID:n,retryOfRequestLogID:s,startTime:a}=e,i=await(async()=>{if(e.options.stream)return Ae(r).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,r):wr.fromSSEResponse(t,e.controller,r);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let u=t.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){let d=await t.json();return wm(d,t)}return await t.text()})();return Ae(r).debug(`[${n}] response parsed`,Kr({retryOfRequestLogID:s,url:t.url,status:t.status,body:i,durationMs:Date.now()-a})),i}function wm(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var No,xs=class r extends Promise{constructor(e,t,n=ol){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=n,No.set(this,void 0),U(this,No,e,"f")}_thenUnwrap(e){return new r(y(this,No,"f"),this.responsePromise,async(t,n)=>wm(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(y(this,No,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};No=new WeakMap;var ul,cl=class{constructor(e,t,n,s){ul.set(this,void 0),U(this,ul,e,"f"),this.options=s,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new j("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await y(this,ul,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ul=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},jo=class extends xs{constructor(e,t,n){super(e,t,async(s,a)=>new n(s,a.response,await ol(s,a),a.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},vr=class extends cl{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},ne=class extends cl{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...Nv(this.options.query),after:t}}:null}};var xm=()=>{if(typeof File>"u"){let{process:r}=globalThis,e=typeof r?.versions?.node=="string"&&parseInt(r.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Ha(r,e,t){return xm(),new File(r,e??"unknown_file",t)}function Mo(r){return(typeof r=="object"&&r!==null&&("name"in r&&r.name&&String(r.name)||"url"in r&&r.url&&String(r.url)||"filename"in r&&r.filename&&String(r.filename)||"path"in r&&r.path&&String(r.path))||"").split(/[\\/]/).pop()||void 0}var Em=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function";var vt=async(r,e)=>({...r,body:await vk(r.body,e)}),sx=new WeakMap;function wk(r){let e=typeof r=="function"?r:r.fetch,t=sx.get(e);if(t)return t;let n=(async()=>{try{let s="Response"in e?e.Response:(await e("data:,")).constructor,a=new FormData;return a.toString()!==await new s(a).text()}catch{return!0}})();return sx.set(e,n),n}var vk=async(r,e)=>{if(!await wk(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let t=new FormData;return await Promise.all(Object.entries(r||{}).map(([n,s])=>vm(t,n,s))),t},xk=r=>r instanceof Blob&&"name"in r;var vm=async(r,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")r.append(e,String(t));else if(t instanceof Response)r.append(e,Ha([await t.blob()],Mo(t)));else if(Em(t))r.append(e,Ha([await new Response(tl(t)).blob()],Mo(t)));else if(xk(t))r.append(e,t,Mo(t));else if(Array.isArray(t))await Promise.all(t.map(n=>vm(r,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,s])=>vm(r,`${e}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var ax=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function",Ek=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&ax(r),Ak=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function";async function zo(r,e,t){if(xm(),r=await r,Ek(r))return r instanceof File?r:Ha([await r.arrayBuffer()],r.name);if(Ak(r)){let s=await r.blob();return e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()),Ha(await Am(s),e,t)}let n=await Am(r);if(e||(e=Mo(r)),!t?.type){let s=n.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof s=="string"&&(t={...t,type:s})}return Ha(n,e,t)}async function Am(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(ax(r))e.push(r instanceof Blob?r:await r.arrayBuffer());else if(Em(r))for await(let t of r)e.push(...await Am(t));else{let t=r?.constructor?.name;throw new Error(`Unexpected data type: ${typeof r}${t?`; constructor: ${t}`:""}${Ok(r)}`)}return e}function Ok(r){return typeof r!="object"||r===null?"":`; props: [${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}var O=class{constructor(e){this._client=e}};function ox(r){return r.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var ix=Object.freeze(Object.create(null)),Tk=(r=ox)=>function(t,...n){if(t.length===1)return t[0];let s=!1,a=[],i=t.reduce((l,d,f)=>{/[?#]/.test(d)&&(s=!0);let p=n[f],m=(s?encodeURIComponent:r)(""+p);return f!==n.length&&(p==null||typeof p=="object"&&p.toString===Object.getPrototypeOf(Object.getPrototypeOf(p.hasOwnProperty??ix)??ix)?.toString)&&(m=p+"",a.push({start:l.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(p).slice(8,-1)} is not a valid path parameter`})),l+d+(f===n.length?"":m)},""),o=i.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=u.exec(o))!==null;)a.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(a.sort((l,d)=>l.start-d.start),a.length>0){let l=0,d=a.reduce((f,p)=>{let m=" ".repeat(p.start-l),h="^".repeat(p.length);return l=p.start+p.length,f+m+h},"");throw new j(`Path parameters result in path with invalid segments:
99
+ ${a.map(f=>f.error).join(`
100
+ `)}
101
+ ${i}
102
+ ${d}`)}return i},E=Tk(ox);var Es=class extends O{list(e,t={},n){return this._client.getAPIList(E`/chat/completions/${e}/messages`,ne,{query:t,...n})}};function Lo(r){return r!==void 0&&"function"in r&&r.function!==void 0}function ux(r,e){let t={...r};return Object.defineProperties(t,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),t}function Do(r){return r?.$brand==="auto-parseable-response-format"}function As(r){return r?.$brand==="auto-parseable-tool"}function cx(r,e){return!e||!Om(e)?{...r,choices:r.choices.map(t=>(dx(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Fo(r,e)}function Fo(r,e){let t=r.choices.map(n=>{if(n.finish_reason==="length")throw new Va;if(n.finish_reason==="content_filter")throw new qa;return dx(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(s=>Rk(e,s))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?kk(e,n.message.content):null}}});return{...r,choices:t}}function kk(r,e){return r.response_format?.type!=="json_schema"?null:r.response_format?.type==="json_schema"?"$parseRaw"in r.response_format?r.response_format.$parseRaw(e):JSON.parse(e):null}function Rk(r,e){let t=r.tools?.find(n=>Lo(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:As(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function lx(r,e){if(!r||!("tools"in r)||!r.tools)return!1;let t=r.tools?.find(n=>Lo(n)&&n.function?.name===e.function.name);return Lo(t)&&(As(t)||t?.function.strict||!1)}function Om(r){return Do(r.response_format)?!0:r.tools?.some(e=>As(e)||e.type==="function"&&e.function.strict===!0)??!1}function dx(r){for(let e of r||[])if(e.type!=="function")throw new j(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function px(r){for(let e of r??[]){if(e.type!=="function")throw new j(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new j(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Ka=r=>r?.role==="assistant",Im=r=>r?.role==="tool";var Tm,ll,dl,Uo,Bo,pl,Zo,Wr,Vo,fl,ml,Wa,fx,xn=class{constructor(){Tm.add(this),this.controller=new AbortController,ll.set(this,void 0),dl.set(this,()=>{}),Uo.set(this,()=>{}),Bo.set(this,void 0),pl.set(this,()=>{}),Zo.set(this,()=>{}),Wr.set(this,{}),Vo.set(this,!1),fl.set(this,!1),ml.set(this,!1),Wa.set(this,!1),U(this,ll,new Promise((e,t)=>{U(this,dl,e,"f"),U(this,Uo,t,"f")}),"f"),U(this,Bo,new Promise((e,t)=>{U(this,pl,e,"f"),U(this,Zo,t,"f")}),"f"),y(this,ll,"f").catch(()=>{}),y(this,Bo,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},y(this,Tm,"m",fx).bind(this))},0)}_connected(){this.ended||(y(this,dl,"f").call(this),this._emit("connect"))}get ended(){return y(this,Vo,"f")}get errored(){return y(this,fl,"f")}get aborted(){return y(this,ml,"f")}abort(){this.controller.abort()}on(e,t){return(y(this,Wr,"f")[e]||(y(this,Wr,"f")[e]=[])).push({listener:t}),this}off(e,t){let n=y(this,Wr,"f")[e];if(!n)return this;let s=n.findIndex(a=>a.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(y(this,Wr,"f")[e]||(y(this,Wr,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{U(this,Wa,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){U(this,Wa,!0,"f"),await y(this,Bo,"f")}_emit(e,...t){if(y(this,Vo,"f"))return;e==="end"&&(U(this,Vo,!0,"f"),y(this,pl,"f").call(this));let n=y(this,Wr,"f")[e];if(n&&(y(this,Wr,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!y(this,Wa,"f")&&!n?.length&&Promise.reject(s),y(this,Uo,"f").call(this,s),y(this,Zo,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!y(this,Wa,"f")&&!n?.length&&Promise.reject(s),y(this,Uo,"f").call(this,s),y(this,Zo,"f").call(this,s),this._emit("end")}}_emitFinal(){}};ll=new WeakMap,dl=new WeakMap,Uo=new WeakMap,Bo=new WeakMap,pl=new WeakMap,Zo=new WeakMap,Wr=new WeakMap,Vo=new WeakMap,fl=new WeakMap,ml=new WeakMap,Wa=new WeakMap,Tm=new WeakSet,fx=function(e){if(U(this,fl,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new be),e instanceof be)return U(this,ml,!0,"f"),this._emit("abort",e);if(e instanceof j)return this._emit("error",e);if(e instanceof Error){let t=new j(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new j(String(e)))};function mx(r){return typeof r.parse=="function"}var et,Pm,hl,Sm,km,Rm,hx,gx,Ck=10,Ja=class extends xn{constructor(){super(...arguments),et.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),Im(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Ka(e)&&e.tool_calls)for(let n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new j("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),y(this,et,"m",Pm).call(this)}async finalMessage(){return await this.done(),y(this,et,"m",hl).call(this)}async finalFunctionToolCall(){return await this.done(),y(this,et,"m",Sm).call(this)}async finalFunctionToolCallResult(){return await this.done(),y(this,et,"m",km).call(this)}async totalUsage(){return await this.done(),y(this,et,"m",Rm).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=y(this,et,"m",hl).call(this);t&&this._emit("finalMessage",t);let n=y(this,et,"m",Pm).call(this);n&&this._emit("finalContent",n);let s=y(this,et,"m",Sm).call(this);s&&this._emit("finalFunctionToolCall",s);let a=y(this,et,"m",km).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",y(this,et,"m",Rm).call(this))}async _createChatCompletion(e,t,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),y(this,et,"m",hx).call(this,t);let a=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Fo(a,t))}async _runChatCompletion(e,t,n){for(let s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n){let s="tool",{tool_choice:a="auto",stream:i,...o}=t,u=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:c=Ck}=n||{},l=t.tools.map(p=>{if(As(p)){if(!p.$callback)throw new j("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:p.$callback,name:p.function.name,description:p.function.description||"",parameters:p.function.parameters,parse:p.$parseRaw,strict:!0}}}return p}),d={};for(let p of l)p.type==="function"&&(d[p.function.name||p.function.function.name]=p.function);let f="tools"in t?l.map(p=>p.type==="function"?{type:"function",function:{name:p.function.name||p.function.function.name,parameters:p.function.parameters,description:p.function.description,strict:p.function.strict}}:p):void 0;for(let p of t.messages)this._addMessage(p,!1);for(let p=0;p<c;++p){let h=(await this._createChatCompletion(e,{...o,tool_choice:a,tools:f,messages:[...this.messages]},n)).choices[0]?.message;if(!h)throw new j("missing message in ChatCompletion response");if(!h.tool_calls?.length)return;for(let g of h.tool_calls){if(g.type!=="function")continue;let w=g.id,{name:b,arguments:x}=g.function,I=d[b];if(I){if(u&&u!==b){let Z=`Invalid tool_call: ${JSON.stringify(b)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:s,tool_call_id:w,content:Z});continue}}else{let Z=`Invalid tool_call: ${JSON.stringify(b)}. Available options are: ${Object.keys(d).map(oe=>JSON.stringify(oe)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:w,content:Z});continue}let P;try{P=mx(I)?await I.parse(x):x}catch(Z){let oe=Z instanceof Error?Z.message:String(Z);this._addMessage({role:s,tool_call_id:w,content:oe});continue}let K=await I.function(P,this),V=y(this,et,"m",gx).call(this,K);if(this._addMessage({role:s,tool_call_id:w,content:V}),u)return}}}};et=new WeakSet,Pm=function(){return y(this,et,"m",hl).call(this).content??null},hl=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(Ka(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new j("stream ended without producing a ChatCompletionMessage with role=assistant")},Sm=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Ka(t)&&t?.tool_calls?.length)return t.tool_calls.filter(n=>n.type==="function").at(-1)?.function}},km=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Im(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(n=>n.role==="assistant"&&n.tool_calls?.some(s=>s.type==="function"&&s.id===t.tool_call_id)))return t.content}},Rm=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},hx=function(e){if(e.n!=null&&e.n>1)throw new j("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},gx=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var qo=class r extends Ja{static runTools(e,t,n){let s=new r,a={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,a)),s}_addMessage(e,t=!0){super._addMessage(e,t),Ka(e)&&e.content&&this._emit("content",e.content)}};var $e={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},Cm=class extends Error{},$m=class extends Error{};function $k(r,e=$e.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return Nk(r.trim(),e)}var Nk=(r,e)=>{let t=r.length,n=0,s=f=>{throw new Cm(`${f} at position ${n}`)},a=f=>{throw new $m(`${f} at position ${n}`)},i=()=>(d(),n>=t&&s("Unexpected end of input"),r[n]==='"'?o():r[n]==="{"?u():r[n]==="["?c():r.substring(n,n+4)==="null"||$e.NULL&e&&t-n<4&&"null".startsWith(r.substring(n))?(n+=4,null):r.substring(n,n+4)==="true"||$e.BOOL&e&&t-n<4&&"true".startsWith(r.substring(n))?(n+=4,!0):r.substring(n,n+5)==="false"||$e.BOOL&e&&t-n<5&&"false".startsWith(r.substring(n))?(n+=5,!1):r.substring(n,n+8)==="Infinity"||$e.INFINITY&e&&t-n<8&&"Infinity".startsWith(r.substring(n))?(n+=8,1/0):r.substring(n,n+9)==="-Infinity"||$e.MINUS_INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(r.substring(n))?(n+=9,-1/0):r.substring(n,n+3)==="NaN"||$e.NAN&e&&t-n<3&&"NaN".startsWith(r.substring(n))?(n+=3,NaN):l()),o=()=>{let f=n,p=!1;for(n++;n<t&&(r[n]!=='"'||p&&r[n-1]==="\\");)p=r[n]==="\\"?!p:!1,n++;if(r.charAt(n)=='"')try{return JSON.parse(r.substring(f,++n-Number(p)))}catch(m){a(String(m))}else if($e.STR&e)try{return JSON.parse(r.substring(f,n-Number(p))+'"')}catch{return JSON.parse(r.substring(f,r.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},u=()=>{n++,d();let f={};try{for(;r[n]!=="}";){if(d(),n>=t&&$e.OBJ&e)return f;let p=o();d(),n++;try{let m=i();Object.defineProperty(f,p,{value:m,writable:!0,enumerable:!0,configurable:!0})}catch(m){if($e.OBJ&e)return f;throw m}d(),r[n]===","&&n++}}catch{if($e.OBJ&e)return f;s("Expected '}' at end of object")}return n++,f},c=()=>{n++;let f=[];try{for(;r[n]!=="]";)f.push(i()),d(),r[n]===","&&n++}catch{if($e.ARR&e)return f;s("Expected ']' at end of array")}return n++,f},l=()=>{if(n===0){r==="-"&&$e.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r)}catch(p){if($e.NUM&e)try{return r[r.length-1]==="."?JSON.parse(r.substring(0,r.lastIndexOf("."))):JSON.parse(r.substring(0,r.lastIndexOf("e")))}catch{}a(String(p))}}let f=n;for(r[n]==="-"&&n++;r[n]&&!",]}".includes(r[n]);)n++;n==t&&!($e.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(r.substring(f,n))}catch{r.substring(f,n)==="-"&&$e.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r.substring(f,r.lastIndexOf("e")))}catch(m){a(String(m))}}},d=()=>{for(;n<t&&`
103
+ \r `.includes(r[n]);)n++};return i()},Nm=r=>$k(r,$e.ALL^$e.NUM);var Ce,Jr,Xa,En,jm,gl,Mm,zm,Lm,_l,Dm,_x,Os=class r extends Ja{constructor(e){super(),Ce.add(this),Jr.set(this,void 0),Xa.set(this,void 0),En.set(this,void 0),U(this,Jr,e,"f"),U(this,Xa,[],"f")}get currentChatCompletionSnapshot(){return y(this,En,"f")}static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){let s=new r(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,n){super._createChatCompletion;let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),y(this,Ce,"m",jm).call(this);let a=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let i of a)y(this,Ce,"m",Mm).call(this,i);if(a.controller.signal?.aborted)throw new be;return this._addChatCompletion(y(this,Ce,"m",_l).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),y(this,Ce,"m",jm).call(this),this._connected();let s=wr.fromReadableStream(e,this.controller),a;for await(let i of s)a&&a!==i.id&&this._addChatCompletion(y(this,Ce,"m",_l).call(this)),y(this,Ce,"m",Mm).call(this,i),a=i.id;if(s.controller.signal?.aborted)throw new be;return this._addChatCompletion(y(this,Ce,"m",_l).call(this))}[(Jr=new WeakMap,Xa=new WeakMap,En=new WeakMap,Ce=new WeakSet,jm=function(){this.ended||U(this,En,void 0,"f")},gl=function(t){let n=y(this,Xa,"f")[t.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},y(this,Xa,"f")[t.index]=n,n)},Mm=function(t){if(this.ended)return;let n=y(this,Ce,"m",_x).call(this,t);this._emit("chunk",t,n);for(let s of t.choices){let a=n.choices[s.index];s.delta.content!=null&&a.message?.role==="assistant"&&a.message?.content&&(this._emit("content",s.delta.content,a.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:a.message.content,parsed:a.message.parsed})),s.delta.refusal!=null&&a.message?.role==="assistant"&&a.message?.refusal&&this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:a.message.refusal}),s.logprobs?.content!=null&&a.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:a.logprobs?.content??[]}),s.logprobs?.refusal!=null&&a.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:a.logprobs?.refusal??[]});let i=y(this,Ce,"m",gl).call(this,a);a.finish_reason&&(y(this,Ce,"m",Lm).call(this,a),i.current_tool_call_index!=null&&y(this,Ce,"m",zm).call(this,a,i.current_tool_call_index));for(let o of s.delta.tool_calls??[])i.current_tool_call_index!==o.index&&(y(this,Ce,"m",Lm).call(this,a),i.current_tool_call_index!=null&&y(this,Ce,"m",zm).call(this,a,i.current_tool_call_index)),i.current_tool_call_index=o.index;for(let o of s.delta.tool_calls??[]){let u=a.message.tool_calls?.[o.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:o.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:o.function?.arguments??""}):(u?.type,void 0))}}},zm=function(t,n){if(y(this,Ce,"m",gl).call(this,t).done_tool_calls.has(n))return;let a=t.message.tool_calls?.[n];if(!a)throw new Error("no tool call snapshot");if(!a.type)throw new Error("tool call snapshot missing `type`");if(a.type==="function"){let i=y(this,Jr,"f")?.tools?.find(o=>Lo(o)&&o.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:n,arguments:a.function.arguments,parsed_arguments:As(i)?i.$parseRaw(a.function.arguments):i?.function.strict?JSON.parse(a.function.arguments):null})}else a.type},Lm=function(t){let n=y(this,Ce,"m",gl).call(this,t);if(t.message.content&&!n.content_done){n.content_done=!0;let s=y(this,Ce,"m",Dm).call(this);this._emit("content.done",{content:t.message.content,parsed:s?s.$parseRaw(t.message.content):null})}t.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},_l=function(){if(this.ended)throw new j("stream has ended, this shouldn't happen");let t=y(this,En,"f");if(!t)throw new j("request ended without sending any chunks");return U(this,En,void 0,"f"),U(this,Xa,[],"f"),jk(t,y(this,Jr,"f"))},Dm=function(){let t=y(this,Jr,"f")?.response_format;return Do(t)?t:null},_x=function(t){var n,s,a,i;let o=y(this,En,"f"),{choices:u,...c}=t;o?Object.assign(o,c):o=U(this,En,{...c,choices:[]},"f");for(let{delta:l,finish_reason:d,index:f,logprobs:p=null,...m}of t.choices){let h=o.choices[f];if(h||(h=o.choices[f]={finish_reason:d,index:f,message:{},logprobs:p,...m}),p)if(!h.logprobs)h.logprobs=Object.assign({},p);else{let{content:K,refusal:V,...Z}=p;Object.assign(h.logprobs,Z),K&&((n=h.logprobs).content??(n.content=[]),h.logprobs.content.push(...K)),V&&((s=h.logprobs).refusal??(s.refusal=[]),h.logprobs.refusal.push(...V))}if(d&&(h.finish_reason=d,y(this,Jr,"f")&&Om(y(this,Jr,"f")))){if(d==="length")throw new Va;if(d==="content_filter")throw new qa}if(Object.assign(h,m),!l)continue;let{content:g,refusal:w,function_call:b,role:x,tool_calls:I,...P}=l;if(Object.assign(h.message,P),w&&(h.message.refusal=(h.message.refusal||"")+w),x&&(h.message.role=x),b&&(h.message.function_call?(b.name&&(h.message.function_call.name=b.name),b.arguments&&((a=h.message.function_call).arguments??(a.arguments=""),h.message.function_call.arguments+=b.arguments)):h.message.function_call=b),g&&(h.message.content=(h.message.content||"")+g,!h.message.refusal&&y(this,Ce,"m",Dm).call(this)&&(h.message.parsed=Nm(h.message.content))),I){h.message.tool_calls||(h.message.tool_calls=[]);for(let{index:K,id:V,type:Z,function:oe,...de}of I){let fe=(i=h.message.tool_calls)[K]??(i[K]={});Object.assign(fe,de),V&&(fe.id=V),Z&&(fe.type=Z),oe&&(fe.function??(fe.function={name:oe.name??"",arguments:""})),oe?.name&&(fe.function.name=oe.name),oe?.arguments&&(fe.function.arguments+=oe.arguments,lx(y(this,Jr,"f"),fe)&&(fe.function.parsed_arguments=Nm(fe.function.arguments)))}}}return o},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("chunk",s=>{let a=t.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(let a of t)a.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(let a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new wr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function jk(r,e){let{id:t,choices:n,created:s,model:a,system_fingerprint:i,...o}=r,u={...o,id:t,choices:n.map(({message:c,finish_reason:l,index:d,logprobs:f,...p})=>{if(!l)throw new j(`missing finish_reason for choice ${d}`);let{content:m=null,function_call:h,tool_calls:g,...w}=c,b=c.role;if(!b)throw new j(`missing role for choice ${d}`);if(h){let{arguments:x,name:I}=h;if(x==null)throw new j(`missing function_call.arguments for choice ${d}`);if(!I)throw new j(`missing function_call.name for choice ${d}`);return{...p,message:{content:m,function_call:{arguments:x,name:I},role:b,refusal:c.refusal??null},finish_reason:l,index:d,logprobs:f}}return g?{...p,index:d,finish_reason:l,logprobs:f,message:{...w,role:b,content:m,refusal:c.refusal??null,tool_calls:g.map((x,I)=>{let{function:P,type:K,id:V,...Z}=x,{arguments:oe,name:de,...fe}=P||{};if(V==null)throw new j(`missing choices[${d}].tool_calls[${I}].id
104
+ ${yl(r)}`);if(K==null)throw new j(`missing choices[${d}].tool_calls[${I}].type
105
+ ${yl(r)}`);if(de==null)throw new j(`missing choices[${d}].tool_calls[${I}].function.name
106
+ ${yl(r)}`);if(oe==null)throw new j(`missing choices[${d}].tool_calls[${I}].function.arguments
107
+ ${yl(r)}`);return{...Z,id:V,type:K,function:{...fe,name:de,arguments:oe}}})}}:{...p,message:{...w,content:m,role:b,refusal:c.refusal??null},finish_reason:l,index:d,logprobs:f}}),created:s,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return cx(u,e)}function yl(r){return JSON.stringify(r)}var Go=class r extends Os{static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,n){let s=new r(t),a={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,a)),s}};var Xr=class extends O{constructor(){super(...arguments),this.messages=new Es(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(E`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(E`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/chat/completions",ne,{query:e,...t})}delete(e,t){return this._client.delete(E`/chat/completions/${e}`,t)}parse(e,t){return px(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>Fo(n,e))}runTools(e,t){return e.stream?Go.runTools(this._client,e,t):qo.runTools(this._client,e,t)}stream(e,t){return Os.createChatCompletion(this._client,e,t)}};Xr.Messages=Es;var An=class extends O{constructor(){super(...arguments),this.completions=new Xr(this._client)}};An.Completions=Xr;var yx=Symbol("brand.privateNullableHeaders");function*zk(r){if(!r)return;if(yx in r){let{values:n,nulls:s}=r;yield*n.entries();for(let a of s)yield[a,null];return}let e=!1,t;r instanceof Headers?t=r.entries():um(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let n of t){let s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let a=um(n[1])?n[1]:[n[1]],i=!1;for(let o of a)o!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,o])}}var k=r=>{let e=new Headers,t=new Set;for(let n of r){let s=new Set;for(let[a,i]of zk(n)){let o=a.toLowerCase();s.has(o)||(e.delete(a),s.add(o)),i===null?(e.delete(a),t.add(o)):(e.append(a,i),t.delete(o))}}return{[yx]:!0,values:e,nulls:t}};var Ya=class extends O{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:k([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};var Qa=class extends O{create(e,t){return this._client.post("/audio/transcriptions",vt({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};var ei=class extends O{create(e,t){return this._client.post("/audio/translations",vt({body:e,...t,__metadata:{model:e.model}},this._client))}};var xr=class extends O{constructor(){super(...arguments),this.transcriptions=new Qa(this._client),this.translations=new ei(this._client),this.speech=new Ya(this._client)}};xr.Transcriptions=Qa;xr.Translations=ei;xr.Speech=Ya;var Is=class extends O{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(E`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",ne,{query:e,...t})}cancel(e,t){return this._client.post(E`/batches/${e}/cancel`,t)}};var ti=class extends O{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:k([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(E`/assistants/${e}`,{...t,headers:k([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(E`/assistants/${e}`,{body:t,...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",ne,{query:e,...t,headers:k([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(E`/assistants/${e}`,{...t,headers:k([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var ri=class extends O{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:k([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var ni=class extends O{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:k([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var On=class extends O{constructor(){super(...arguments),this.sessions=new ri(this._client),this.transcriptionSessions=new ni(this._client)}};On.Sessions=ri;On.TranscriptionSessions=ni;var si=class extends O{create(e,t,n){return this._client.post(E`/threads/${e}/messages`,{body:t,...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{thread_id:s}=t;return this._client.get(E`/threads/${s}/messages/${e}`,{...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{thread_id:s,...a}=t;return this._client.post(E`/threads/${s}/messages/${e}`,{body:a,...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(E`/threads/${e}/messages`,ne,{query:t,...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t,n){let{thread_id:s}=t;return this._client.delete(E`/threads/${s}/messages/${e}`,{...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var ai=class extends O{retrieve(e,t,n){let{thread_id:s,run_id:a,...i}=t;return this._client.get(E`/threads/${s}/runs/${a}/steps/${e}`,{query:i,...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t,n){let{thread_id:s,...a}=t;return this._client.getAPIList(E`/threads/${s}/runs/${e}/steps`,ne,{query:a,...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var bx=r=>{if(typeof Buffer<"u"){let e=Buffer.from(r,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(r),t=e.length,n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);return Array.from(new Float32Array(n.buffer))}};var In=r=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()};var De,Ps,Fm,Er,bl,Jt,Ss,ii,Ts,xl,xt,wl,vl,Wo,Ho,Ko,wx,vx,xx,Ex,Ax,Ox,Ix,Yr=class extends xn{constructor(){super(...arguments),De.add(this),Fm.set(this,[]),Er.set(this,{}),bl.set(this,{}),Jt.set(this,void 0),Ss.set(this,void 0),ii.set(this,void 0),Ts.set(this,void 0),xl.set(this,void 0),xt.set(this,void 0),wl.set(this,void 0),vl.set(this,void 0),Wo.set(this,void 0)}[(Fm=new WeakMap,Er=new WeakMap,bl=new WeakMap,Jt=new WeakMap,Ss=new WeakMap,ii=new WeakMap,Ts=new WeakMap,xl=new WeakMap,xt=new WeakMap,wl=new WeakMap,vl=new WeakMap,Wo=new WeakMap,De=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("event",s=>{let a=t.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(let a of t)a.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(let a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new Ps;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let s=wr.fromReadableStream(e,this.controller);for await(let a of s)y(this,De,"m",Ho).call(this,a);if(s.controller.signal?.aborted)throw new be;return this._addRun(y(this,De,"m",Ko).call(this))}toReadableStream(){return new wr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s){let a=new Ps;return a._run(()=>a._runToolAssistantStream(e,t,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,t,n,s){let a=s?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));let i={...n,stream:!0},o=await e.submitToolOutputs(t,i,{...s,signal:this.controller.signal});this._connected();for await(let u of o)y(this,De,"m",Ho).call(this,u);if(o.controller.signal?.aborted)throw new be;return this._addRun(y(this,De,"m",Ko).call(this))}static createThreadAssistantStream(e,t,n){let s=new Ps;return s._run(()=>s._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,n,s){let a=new Ps;return a._run(()=>a._runAssistantStream(e,t,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return y(this,wl,"f")}currentRun(){return y(this,vl,"f")}currentMessageSnapshot(){return y(this,Jt,"f")}currentRunStepSnapshot(){return y(this,Wo,"f")}async finalRunSteps(){return await this.done(),Object.values(y(this,Er,"f"))}async finalMessages(){return await this.done(),Object.values(y(this,bl,"f"))}async finalRun(){if(await this.done(),!y(this,Ss,"f"))throw Error("Final run was not received.");return y(this,Ss,"f")}async _createThreadAssistantStream(e,t,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let a={...t,stream:!0},i=await e.createAndRun(a,{...n,signal:this.controller.signal});this._connected();for await(let o of i)y(this,De,"m",Ho).call(this,o);if(i.controller.signal?.aborted)throw new be;return this._addRun(y(this,De,"m",Ko).call(this))}async _createAssistantStream(e,t,n,s){let a=s?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));let i={...n,stream:!0},o=await e.create(t,i,{...s,signal:this.controller.signal});this._connected();for await(let u of o)y(this,De,"m",Ho).call(this,u);if(o.controller.signal?.aborted)throw new be;return this._addRun(y(this,De,"m",Ko).call(this))}static accumulateDelta(e,t){for(let[n,s]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=s;continue}let a=e[n];if(a==null){e[n]=s;continue}if(n==="index"||n==="type"){e[n]=s;continue}if(typeof a=="string"&&typeof s=="string")a+=s;else if(typeof a=="number"&&typeof s=="number")a+=s;else if(Ro(a)&&Ro(s))a=this.accumulateDelta(a,s);else if(Array.isArray(a)&&Array.isArray(s)){if(a.every(i=>typeof i=="string"||typeof i=="number")){a.push(...s);continue}for(let i of s){if(!Ro(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let o=i.index;if(o==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof o!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${o}`);let u=a[o];u==null?a.push(i):a[o]=this.accumulateDelta(u,i)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${s}, accValue: ${a}`);e[n]=a}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,s){return await this._createAssistantStream(t,e,n,s)}async _runToolAssistantStream(e,t,n,s){return await this._createToolAssistantStream(t,e,n,s)}};Ps=Yr,Ho=function(e){if(!this.ended)switch(U(this,wl,e,"f"),y(this,De,"m",xx).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":y(this,De,"m",Ix).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":y(this,De,"m",vx).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":y(this,De,"m",wx).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},Ko=function(){if(this.ended)throw new j("stream has ended, this shouldn't happen");if(!y(this,Ss,"f"))throw Error("Final run has not been received");return y(this,Ss,"f")},wx=function(e){let[t,n]=y(this,De,"m",Ax).call(this,e,y(this,Jt,"f"));U(this,Jt,t,"f"),y(this,bl,"f")[t.id]=t;for(let s of n){let a=t.content[s.index];a?.type=="text"&&this._emit("textCreated",a.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let s of e.data.delta.content){if(s.type=="text"&&s.text){let a=s.text,i=t.content[s.index];if(i&&i.type=="text")this._emit("textDelta",a,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=y(this,ii,"f")){if(y(this,Ts,"f"))switch(y(this,Ts,"f").type){case"text":this._emit("textDone",y(this,Ts,"f").text,y(this,Jt,"f"));break;case"image_file":this._emit("imageFileDone",y(this,Ts,"f").image_file,y(this,Jt,"f"));break}U(this,ii,s.index,"f")}U(this,Ts,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(y(this,ii,"f")!==void 0){let s=e.data.content[y(this,ii,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,y(this,Jt,"f"));break;case"text":this._emit("textDone",s.text,y(this,Jt,"f"));break}}y(this,Jt,"f")&&this._emit("messageDone",e.data),U(this,Jt,void 0,"f")}},vx=function(e){let t=y(this,De,"m",Ex).call(this,e);switch(U(this,Wo,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let a of n.step_details.tool_calls)a.index==y(this,xl,"f")?this._emit("toolCallDelta",a,t.step_details.tool_calls[a.index]):(y(this,xt,"f")&&this._emit("toolCallDone",y(this,xt,"f")),U(this,xl,a.index,"f"),U(this,xt,t.step_details.tool_calls[a.index],"f"),y(this,xt,"f")&&this._emit("toolCallCreated",y(this,xt,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":U(this,Wo,void 0,"f"),e.data.step_details.type=="tool_calls"&&y(this,xt,"f")&&(this._emit("toolCallDone",y(this,xt,"f")),U(this,xt,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},xx=function(e){y(this,Fm,"f").push(e),this._emit("event",e)},Ex=function(e){switch(e.event){case"thread.run.step.created":return y(this,Er,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=y(this,Er,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let s=Ps.accumulateDelta(t,n.delta);y(this,Er,"f")[e.data.id]=s}return y(this,Er,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":y(this,Er,"f")[e.data.id]=e.data;break}if(y(this,Er,"f")[e.data.id])return y(this,Er,"f")[e.data.id];throw new Error("No snapshot available")},Ax=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(let a of s.delta.content)if(a.index in t.content){let i=t.content[a.index];t.content[a.index]=y(this,De,"m",Ox).call(this,a,i)}else t.content[a.index]=a,n.push(a);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Ox=function(e,t){return Ps.accumulateDelta(t,e)},Ix=function(e){switch(U(this,vl,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":U(this,Ss,e.data,"f"),y(this,xt,"f")&&(this._emit("toolCallDone",y(this,xt,"f")),U(this,xt,void 0,"f"));break;case"thread.run.cancelling":break}};var ks=class extends O{constructor(){super(...arguments),this.steps=new ai(this._client)}create(e,t,n){let{include:s,...a}=t;return this._client.post(E`/threads/${e}/runs`,{query:{include:s},body:a,...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1})}retrieve(e,t,n){let{thread_id:s}=t;return this._client.get(E`/threads/${s}/runs/${e}`,{...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{thread_id:s,...a}=t;return this._client.post(E`/threads/${s}/runs/${e}`,{body:a,...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(E`/threads/${e}/runs`,ne,{query:t,...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,t,n){let{thread_id:s}=t;return this._client.post(E`/threads/${s}/runs/${e}/cancel`,{...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let s=await this.create(e,t,n);return await this.poll(s.id,{thread_id:e},n)}createAndStream(e,t,n){return Yr.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let s=k([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:a,response:i}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...s}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let o=5e3;if(n?.pollIntervalMs)o=n.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let c=parseInt(u);isNaN(c)||(o=c)}}await yr(o);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,t,n){return Yr.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:s,...a}=t;return this._client.post(E`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:a,...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,n){let s=await this.submitToolOutputs(e,t,n);return await this.poll(s.id,t,n)}submitToolOutputsStream(e,t,n){return Yr.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};ks.Steps=ai;var Tn=class extends O{constructor(){super(...arguments),this.runs=new ks(this._client),this.messages=new si(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:k([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(E`/threads/${e}`,{...t,headers:k([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(E`/threads/${e}`,{body:t,...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t){return this._client.delete(E`/threads/${e}`,{...t,headers:k([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:k([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return Yr.createThreadAssistantStream(e,this._client.beta.threads,t)}};Tn.Runs=ks;Tn.Messages=si;var Ar=class extends O{constructor(){super(...arguments),this.realtime=new On(this._client),this.assistants=new ti(this._client),this.threads=new Tn(this._client)}};Ar.Realtime=On;Ar.Assistants=ti;Ar.Threads=Tn;var Rs=class extends O{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};var oi=class extends O{retrieve(e,t,n){let{container_id:s}=t;return this._client.get(E`/containers/${s}/files/${e}/content`,{...n,headers:k([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}};var Cs=class extends O{constructor(){super(...arguments),this.content=new oi(this._client)}create(e,t,n){return this._client.post(E`/containers/${e}/files`,vt({body:t,...n},this._client))}retrieve(e,t,n){let{container_id:s}=t;return this._client.get(E`/containers/${s}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(E`/containers/${e}/files`,ne,{query:t,...n})}delete(e,t,n){let{container_id:s}=t;return this._client.delete(E`/containers/${s}/files/${e}`,{...n,headers:k([{Accept:"*/*"},n?.headers])})}};Cs.Content=oi;var Pn=class extends O{constructor(){super(...arguments),this.files=new Cs(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(E`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",ne,{query:e,...t})}delete(e,t){return this._client.delete(E`/containers/${e}`,{...t,headers:k([{Accept:"*/*"},t?.headers])})}};Pn.Files=Cs;var $s=class extends O{create(e,t){let n=!!e.encoding_format,s=n?e.encoding_format:"base64";n&&Ae(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let a=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return n?a:(Ae(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(i=>(i&&i.data&&i.data.forEach(o=>{let u=o.embedding;o.embedding=bx(u)}),i)))}};var ui=class extends O{retrieve(e,t,n){let{eval_id:s,run_id:a}=t;return this._client.get(E`/evals/${s}/runs/${a}/output_items/${e}`,n)}list(e,t,n){let{eval_id:s,...a}=t;return this._client.getAPIList(E`/evals/${s}/runs/${e}/output_items`,ne,{query:a,...n})}};var Ns=class extends O{constructor(){super(...arguments),this.outputItems=new ui(this._client)}create(e,t,n){return this._client.post(E`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){let{eval_id:s}=t;return this._client.get(E`/evals/${s}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(E`/evals/${e}/runs`,ne,{query:t,...n})}delete(e,t,n){let{eval_id:s}=t;return this._client.delete(E`/evals/${s}/runs/${e}`,n)}cancel(e,t,n){let{eval_id:s}=t;return this._client.post(E`/evals/${s}/runs/${e}`,n)}};Ns.OutputItems=ui;var Sn=class extends O{constructor(){super(...arguments),this.runs=new Ns(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(E`/evals/${e}`,t)}update(e,t,n){return this._client.post(E`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/evals",ne,{query:e,...t})}delete(e,t){return this._client.delete(E`/evals/${e}`,t)}};Sn.Runs=Ns;var js=class extends O{create(e,t){return this._client.post("/files",vt({body:e,...t},this._client))}retrieve(e,t){return this._client.get(E`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",ne,{query:e,...t})}delete(e,t){return this._client.delete(E`/files/${e}`,t)}content(e,t){return this._client.get(E`/files/${e}/content`,{...t,headers:k([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=30*60*1e3}={}){let s=new Set(["processed","error","deleted"]),a=Date.now(),i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await yr(t),i=await this.retrieve(e),Date.now()-a>n)throw new gr({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};var ci=class extends O{};var li=class extends O{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};var Ms=class extends O{constructor(){super(...arguments),this.graders=new li(this._client)}};Ms.Graders=li;var di=class extends O{create(e,t,n){return this._client.getAPIList(E`/fine_tuning/checkpoints/${e}/permissions`,vr,{body:t,method:"post",...n})}retrieve(e,t={},n){return this._client.get(E`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}delete(e,t,n){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(E`/fine_tuning/checkpoints/${s}/permissions/${e}`,n)}};var zs=class extends O{constructor(){super(...arguments),this.permissions=new di(this._client)}};zs.Permissions=di;var pi=class extends O{list(e,t={},n){return this._client.getAPIList(E`/fine_tuning/jobs/${e}/checkpoints`,ne,{query:t,...n})}};var Ls=class extends O{constructor(){super(...arguments),this.checkpoints=new pi(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(E`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",ne,{query:e,...t})}cancel(e,t){return this._client.post(E`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(E`/fine_tuning/jobs/${e}/events`,ne,{query:t,...n})}pause(e,t){return this._client.post(E`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(E`/fine_tuning/jobs/${e}/resume`,t)}};Ls.Checkpoints=pi;var Xt=class extends O{constructor(){super(...arguments),this.methods=new ci(this._client),this.jobs=new Ls(this._client),this.checkpoints=new zs(this._client),this.alpha=new Ms(this._client)}};Xt.Methods=ci;Xt.Jobs=Ls;Xt.Checkpoints=zs;Xt.Alpha=Ms;var fi=class extends O{};var kn=class extends O{constructor(){super(...arguments),this.graderModels=new fi(this._client)}};kn.GraderModels=fi;var Ds=class extends O{createVariation(e,t){return this._client.post("/images/variations",vt({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",vt({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}};var Fs=class extends O{retrieve(e,t){return this._client.get(E`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",vr,e)}delete(e,t){return this._client.delete(E`/models/${e}`,t)}};var Us=class extends O{create(e,t){return this._client.post("/moderations",{body:e,...t})}};function Tx(r,e){return!e||!uR(e)?{...r,output_parsed:null,output:r.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(n=>({...n,parsed:null}))}:t)}:Um(r,e)}function Um(r,e){let t=r.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:dR(e,s)};if(s.type==="message"){let a=s.content.map(i=>i.type==="output_text"?{...i,parsed:oR(e,i.text)}:i);return{...s,content:a}}return s}),n=Object.assign({},r,{output:t});return Object.getOwnPropertyDescriptor(r,"output_text")||El(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let s of n.output)if(s.type==="message"){for(let a of s.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function oR(r,e){return r.text?.format?.type!=="json_schema"?null:"$parseRaw"in r.text?.format?(r.text?.format).$parseRaw(e):JSON.parse(e)}function uR(r){return!!Do(r.text?.format)}function cR(r){return r?.$brand==="auto-parseable-tool"}function lR(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function dR(r,e){let t=lR(r.tools??[],e.name);return{...e,...e,parsed_arguments:cR(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function El(r){let e=[];for(let t of r.output)if(t.type==="message")for(let n of t.content)n.type==="output_text"&&e.push(n.text);r.output_text=e.join("")}var mi,Al,Rn,Ol,Px,Sx,kx,Rx,Il=class r extends xn{constructor(e){super(),mi.add(this),Al.set(this,void 0),Rn.set(this,void 0),Ol.set(this,void 0),U(this,Al,e,"f")}static createResponse(e,t,n){let s=new r(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),y(this,mi,"m",Px).call(this);let a,i=null;"response_id"in t?(a=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):a=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let o of a)y(this,mi,"m",Sx).call(this,o,i);if(a.controller.signal?.aborted)throw new be;return y(this,mi,"m",kx).call(this)}[(Al=new WeakMap,Rn=new WeakMap,Ol=new WeakMap,mi=new WeakSet,Px=function(){this.ended||U(this,Rn,void 0,"f")},Sx=function(t,n){if(this.ended)return;let s=(i,o)=>{(n==null||o.sequence_number>n)&&this._emit(i,o)},a=y(this,mi,"m",Rx).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{let i=a.output[t.output_index];if(!i)throw new j(`missing output at index ${t.output_index}`);if(i.type==="message"){let o=i.content[t.content_index];if(!o)throw new j(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new j(`expected content to be 'output_text', got ${o.type}`);s("response.output_text.delta",{...t,snapshot:o.text})}break}case"response.function_call_arguments.delta":{let i=a.output[t.output_index];if(!i)throw new j(`missing output at index ${t.output_index}`);i.type==="function_call"&&s("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:s(t.type,t);break}},kx=function(){if(this.ended)throw new j("stream has ended, this shouldn't happen");let t=y(this,Rn,"f");if(!t)throw new j("request ended without sending any events");U(this,Rn,void 0,"f");let n=pR(t,y(this,Al,"f"));return U(this,Ol,n,"f"),n},Rx=function(t){let n=y(this,Rn,"f");if(!n){if(t.type!=="response.created")throw new j(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return n=U(this,Rn,t.response,"f"),n}switch(t.type){case"response.output_item.added":{n.output.push(t.item);break}case"response.content_part.added":{let s=n.output[t.output_index];if(!s)throw new j(`missing output at index ${t.output_index}`);s.type==="message"&&s.content.push(t.part);break}case"response.output_text.delta":{let s=n.output[t.output_index];if(!s)throw new j(`missing output at index ${t.output_index}`);if(s.type==="message"){let a=s.content[t.content_index];if(!a)throw new j(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new j(`expected content to be 'output_text', got ${a.type}`);a.text+=t.delta}break}case"response.function_call_arguments.delta":{let s=n.output[t.output_index];if(!s)throw new j(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{U(this,Rn,t.response,"f");break}}return n},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("event",s=>{let a=t.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(let a of t)a.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(let a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=y(this,Ol,"f");if(!e)throw new j("stream ended without producing a ChatCompletion");return e}};function pR(r,e){return Tx(r,e)}var hi=class extends O{list(e,t={},n){return this._client.getAPIList(E`/responses/${e}/input_items`,ne,{query:t,...n})}};var Cn=class extends O{constructor(){super(...arguments),this.inputItems=new hi(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&El(n),n))}retrieve(e,t={},n){return this._client.get(E`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&El(s),s))}delete(e,t){return this._client.delete(E`/responses/${e}`,{...t,headers:k([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(n=>Um(n,e))}stream(e,t){return Il.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(E`/responses/${e}/cancel`,t)}};Cn.InputItems=hi;var gi=class extends O{create(e,t,n){return this._client.post(E`/uploads/${e}/parts`,vt({body:t,...n},this._client))}};var $n=class extends O{constructor(){super(...arguments),this.parts=new gi(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(E`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(E`/uploads/${e}/complete`,{body:t,...n})}};$n.Parts=gi;var Cx=async r=>{let e=await Promise.allSettled(r),t=e.filter(s=>s.status==="rejected");if(t.length){for(let s of t)console.error(s.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let n=[];for(let s of e)s.status==="fulfilled"&&n.push(s.value);return n};var _i=class extends O{create(e,t,n){return this._client.post(E`/vector_stores/${e}/file_batches`,{body:t,...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{vector_store_id:s}=t;return this._client.get(E`/vector_stores/${s}/file_batches/${e}`,{...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,t,n){let{vector_store_id:s}=t;return this._client.post(E`/vector_stores/${s}/file_batches/${e}/cancel`,{...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let s=await this.create(e,t);return await this.poll(e,s.id,n)}listFiles(e,t,n){let{vector_store_id:s,...a}=t;return this._client.getAPIList(E`/vector_stores/${s}/file_batches/${e}/files`,ne,{query:a,...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async poll(e,t,n){let s=k([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:a,response:i}=await this.retrieve(t,{vector_store_id:e},{...n,headers:s}).withResponse();switch(a.status){case"in_progress":let o=5e3;if(n?.pollIntervalMs)o=n.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let c=parseInt(u);isNaN(c)||(o=c)}}await yr(o);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let a=s?.maxConcurrency??5,i=Math.min(a,t.length),o=this._client,u=t.values(),c=[...n];async function l(f){for(let p of f){let m=await o.files.create({file:p,purpose:"assistants"},s);c.push(m.id)}}let d=Array(i).fill(u).map(l);return await Cx(d),await this.createAndPoll(e,{file_ids:c})}};var yi=class extends O{create(e,t,n){return this._client.post(E`/vector_stores/${e}/files`,{body:t,...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{vector_store_id:s}=t;return this._client.get(E`/vector_stores/${s}/files/${e}`,{...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{vector_store_id:s,...a}=t;return this._client.post(E`/vector_stores/${s}/files/${e}`,{body:a,...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(E`/vector_stores/${e}/files`,ne,{query:t,...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t,n){let{vector_store_id:s}=t;return this._client.delete(E`/vector_stores/${s}/files/${e}`,{...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let s=await this.create(e,t,n);return await this.poll(e,s.id,n)}async poll(e,t,n){let s=k([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let a=await this.retrieve(t,{vector_store_id:e},{...n,headers:s}).withResponse(),i=a.data;switch(i.status){case"in_progress":let o=5e3;if(n?.pollIntervalMs)o=n.pollIntervalMs;else{let u=a.response.headers.get("openai-poll-after-ms");if(u){let c=parseInt(u);isNaN(c)||(o=c)}}await yr(o);break;case"failed":case"completed":return i}}}async upload(e,t,n){let s=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,t,n){let s=await this.upload(e,t,n);return await this.poll(e,s.id,n)}content(e,t,n){let{vector_store_id:s}=t;return this._client.getAPIList(E`/vector_stores/${s}/files/${e}/content`,vr,{...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var Qr=class extends O{constructor(){super(...arguments),this.files=new yi(this._client),this.fileBatches=new _i(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:k([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(E`/vector_stores/${e}`,{...t,headers:k([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(E`/vector_stores/${e}`,{body:t,...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",ne,{query:e,...t,headers:k([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(E`/vector_stores/${e}`,{...t,headers:k([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,n){return this._client.getAPIList(E`/vector_stores/${e}/search`,vr,{body:t,method:"post",...n,headers:k([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};Qr.Files=yi;Qr.FileBatches=_i;var bi,$x,Tl,Bs=class extends O{constructor(){super(...arguments),bi.add(this)}async unwrap(e,t,n=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,n,s),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");y(this,bi,"m",$x).call(this,n);let a=k([t]).values,i=y(this,bi,"m",Tl).call(this,a,"webhook-signature"),o=y(this,bi,"m",Tl).call(this,a,"webhook-timestamp"),u=y(this,bi,"m",Tl).call(this,a,"webhook-id"),c=parseInt(o,10);if(isNaN(c))throw new _r("Invalid webhook timestamp format");let l=Math.floor(Date.now()/1e3);if(l-c>s)throw new _r("Webhook timestamp is too old");if(c>l+s)throw new _r("Webhook timestamp is too new");let d=i.split(" ").map(h=>h.startsWith("v1,")?h.substring(3):h),f=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),p=u?`${u}.${o}.${e}`:`${o}.${e}`,m=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let h of d)try{let g=Buffer.from(h,"base64");if(await crypto.subtle.verify("HMAC",m,g,new TextEncoder().encode(p)))return}catch{continue}throw new _r("The given webhook signature does not match the expected signature")}};bi=new WeakSet,$x=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Tl=function(e,t){if(!e)throw new Error("Headers are required");let n=e.get(t);if(n==null)throw new Error(`Missing required header: ${t}`);return n};var Bm,Zm,Pl,Nx,W=class{constructor({baseURL:e=In("OPENAI_BASE_URL"),apiKey:t=In("OPENAI_API_KEY"),organization:n=In("OPENAI_ORG_ID")??null,project:s=In("OPENAI_PROJECT_ID")??null,webhookSecret:a=In("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(Bm.add(this),Pl.set(this,void 0),this.completions=new Rs(this),this.chat=new An(this),this.embeddings=new $s(this),this.files=new js(this),this.images=new Ds(this),this.audio=new xr(this),this.moderations=new Us(this),this.models=new Fs(this),this.fineTuning=new Xt(this),this.graders=new kn(this),this.vectorStores=new Qr(this),this.webhooks=new Bs(this),this.beta=new Ar(this),this.batches=new Is(this),this.uploads=new $n(this),this.responses=new Cn(this),this.evals=new Sn(this),this.containers=new Pn(this),t===void 0)throw new j("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let o={apiKey:t,organization:n,project:s,webhookSecret:a,...i,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&Bv())throw new j(`It looks like you're running in a browser-like environment.
108
+
109
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
110
+ If you understand the risks and have appropriate mitigations in place,
111
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
112
+
113
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
114
+
115
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
116
+ `);this.baseURL=o.baseURL,this.timeout=o.timeout??Zm.DEFAULT_TIMEOUT,this.logger=o.logger??console;let u="warn";this.logLevel=u,this.logLevel=ym(o.logLevel,"ClientOptions.logLevel",this)??ym(In("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??Vv(),U(this,Pl,Gv,"f"),this._options=o,this.apiKey=t,this.organization=n,this.project=s,this.webhookSecret=a}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return k([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return gm(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${vn}`}defaultIdempotencyKey(){return`stainless-node-retry-${om()}`}makeStatusError(e,t,n,s){return ke.generate(e,t,n,s)}buildURL(e,t,n){let s=!y(this,Bm,"m",Nx).call(this)&&n||this.baseURL,a=$v(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return jv(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(a.search=this.stringifyQuery(t)),a.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new xs(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let s=await e,a=s.maxRetries??this.maxRetries;t==null&&(t=a),await this.prepareOptions(s);let{req:i,url:o,timeout:u}=await this.buildRequest(s,{retryCount:a-t});await this.prepareRequest(i,{url:o,options:s});let c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=n===void 0?"":`, retryOf: ${n}`,d=Date.now();if(Ae(this).debug(`[${c}] sending request`,Kr({retryOfRequestLogID:n,method:s.method,url:o,options:s,headers:i.headers})),s.signal?.aborted)throw new be;let f=new AbortController,p=await this.fetchWithTimeout(o,i,u,f).catch(ko),m=Date.now();if(p instanceof Error){let w=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new be;let b=So(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(t)return Ae(this).info(`[${c}] connection ${b?"timed out":"failed"} - ${w}`),Ae(this).debug(`[${c}] connection ${b?"timed out":"failed"} (${w})`,Kr({retryOfRequestLogID:n,url:o,durationMs:m-d,message:p.message})),this.retryRequest(s,t,n??c);throw Ae(this).info(`[${c}] connection ${b?"timed out":"failed"} - error; no more retries left`),Ae(this).debug(`[${c}] connection ${b?"timed out":"failed"} (error; no more retries left)`,Kr({retryOfRequestLogID:n,url:o,durationMs:m-d,message:p.message})),b?new gr:new wn({cause:p})}let h=[...p.headers.entries()].filter(([w])=>w==="x-request-id").map(([w,b])=>", "+w+": "+JSON.stringify(b)).join(""),g=`[${c}${l}${h}] ${i.method} ${o} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${m-d}ms`;if(!p.ok){let w=await this.shouldRetry(p);if(t&&w){let V=`retrying, ${t} attempts remaining`;return await qv(p.body),Ae(this).info(`${g} - ${V}`),Ae(this).debug(`[${c}] response error (${V})`,Kr({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:m-d})),this.retryRequest(s,t,n??c,p.headers)}let b=w?"error; no more retries left":"error; not retryable";Ae(this).info(`${g} - ${b}`);let x=await p.text().catch(V=>ko(V).message),I=Lv(x),P=I?void 0:x;throw Ae(this).debug(`[${c}] response error (${b})`,Kr({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,message:P,durationMs:Date.now()-d})),this.makeStatusError(p.status,I,P,p.headers)}return Ae(this).info(g),Ae(this).debug(`[${c}] response start`,Kr({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:m-d})),{response:p,options:s,controller:f,requestLogID:c,retryOfRequestLogID:n,startTime:d}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new jo(this,n,e)}async fetchWithTimeout(e,t,n,s){let{signal:a,method:i,...o}=t||{};a&&a.addEventListener("abort",()=>s.abort());let u=setTimeout(()=>s.abort(),n),c=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,l={signal:s.signal,...c?{duplex:"half"}:{},method:"GET",...o};i&&(l.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,l)}finally{clearTimeout(u)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,s){let a,i=s?.get("retry-after-ms");if(i){let u=parseFloat(i);Number.isNaN(u)||(a=u)}let o=s?.get("retry-after");if(o&&!a){let u=parseFloat(o);Number.isNaN(u)?a=Date.parse(o)-Date.now():a=u*1e3}if(!(a&&0<=a&&a<60*1e3)){let u=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,u)}return await yr(a),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let a=t-e,i=Math.min(.5*Math.pow(2,a),8),o=1-Math.random()*.25;return i*o*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:s,path:a,query:i,defaultBaseURL:o}=n,u=this.buildURL(a,i,o);"timeout"in n&&zv("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n}),d=await this.buildHeaders({options:e,method:s,bodyHeaders:c,retryCount:t});return{req:{method:s,headers:d,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:u,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:s}){let a={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);let i=k([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Zv(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=k([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:tl(e)}:y(this,Pl,"f").call(this,{body:e,headers:n})}};Zm=W,Pl=new WeakMap,Bm=new WeakSet,Nx=function(){return this.baseURL!=="https://api.openai.com/v1"};W.OpenAI=Zm;W.DEFAULT_TIMEOUT=6e5;W.OpenAIError=j;W.APIError=ke;W.APIConnectionError=wn;W.APIConnectionTimeoutError=gr;W.APIUserAbortError=be;W.NotFoundError=Da;W.ConflictError=Fa;W.RateLimitError=Ba;W.BadRequestError=Ma;W.AuthenticationError=za;W.InternalServerError=Za;W.PermissionDeniedError=La;W.UnprocessableEntityError=Ua;W.InvalidWebhookSignatureError=_r;W.toFile=zo;W.Completions=Rs;W.Chat=An;W.Embeddings=$s;W.Files=js;W.Images=Ds;W.Audio=xr;W.Moderations=Us;W.Models=Fs;W.FineTuning=Xt;W.Graders=kn;W.VectorStores=Qr;W.Webhooks=Bs;W.Beta=Ar;W.Batches=Is;W.Uploads=$n;W.Responses=Cn;W.Evals=Sn;W.Containers=Pn;$a();_a();is();$a();_a();var yR=typeof window=="object"?window:{},ae="0123456789abcdef".split(""),bR=[-2147483648,8388608,32768,128],Yt=[24,16,8,0];var Ne=[];function Qt(r){r?(Ne[0]=Ne[16]=Ne[1]=Ne[2]=Ne[3]=Ne[4]=Ne[5]=Ne[6]=Ne[7]=Ne[8]=Ne[9]=Ne[10]=Ne[11]=Ne[12]=Ne[13]=Ne[14]=Ne[15]=0,this.blocks=Ne):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.h0=1732584193,this.h1=4023233417,this.h2=2562383102,this.h3=271733878,this.h4=3285377520,this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}Qt.prototype.update=function(r){if(!this.finalized){var e=typeof r!="string";e&&r.constructor===yR.ArrayBuffer&&(r=new Uint8Array(r));for(var t,n=0,s,a=r.length||0,i=this.blocks;n<a;){if(this.hashed&&(this.hashed=!1,i[0]=this.block,i[16]=i[1]=i[2]=i[3]=i[4]=i[5]=i[6]=i[7]=i[8]=i[9]=i[10]=i[11]=i[12]=i[13]=i[14]=i[15]=0),e)for(s=this.start;n<a&&s<64;++n)i[s>>2]|=r[n]<<Yt[s++&3];else for(s=this.start;n<a&&s<64;++n)t=r.charCodeAt(n),t<128?i[s>>2]|=t<<Yt[s++&3]:t<2048?(i[s>>2]|=(192|t>>6)<<Yt[s++&3],i[s>>2]|=(128|t&63)<<Yt[s++&3]):t<55296||t>=57344?(i[s>>2]|=(224|t>>12)<<Yt[s++&3],i[s>>2]|=(128|t>>6&63)<<Yt[s++&3],i[s>>2]|=(128|t&63)<<Yt[s++&3]):(t=65536+((t&1023)<<10|r.charCodeAt(++n)&1023),i[s>>2]|=(240|t>>18)<<Yt[s++&3],i[s>>2]|=(128|t>>12&63)<<Yt[s++&3],i[s>>2]|=(128|t>>6&63)<<Yt[s++&3],i[s>>2]|=(128|t&63)<<Yt[s++&3]);this.lastByteIndex=s,this.bytes+=s-this.start,s>=64?(this.block=i[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}};Qt.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var r=this.blocks,e=this.lastByteIndex;r[16]=this.block,r[e>>2]|=bR[e&3],this.block=r[16],e>=56&&(this.hashed||this.hash(),r[0]=this.block,r[16]=r[1]=r[2]=r[3]=r[4]=r[5]=r[6]=r[7]=r[8]=r[9]=r[10]=r[11]=r[12]=r[13]=r[14]=r[15]=0),r[14]=this.hBytes<<3|this.bytes>>>29,r[15]=this.bytes<<3,this.hash()}};Qt.prototype.hash=function(){var r=this.h0,e=this.h1,t=this.h2,n=this.h3,s=this.h4,a,i,o,u=this.blocks;for(i=16;i<80;++i)o=u[i-3]^u[i-8]^u[i-14]^u[i-16],u[i]=o<<1|o>>>31;for(i=0;i<20;i+=5)a=e&t|~e&n,o=r<<5|r>>>27,s=o+a+s+1518500249+u[i]<<0,e=e<<30|e>>>2,a=r&e|~r&t,o=s<<5|s>>>27,n=o+a+n+1518500249+u[i+1]<<0,r=r<<30|r>>>2,a=s&r|~s&e,o=n<<5|n>>>27,t=o+a+t+1518500249+u[i+2]<<0,s=s<<30|s>>>2,a=n&s|~n&r,o=t<<5|t>>>27,e=o+a+e+1518500249+u[i+3]<<0,n=n<<30|n>>>2,a=t&n|~t&s,o=e<<5|e>>>27,r=o+a+r+1518500249+u[i+4]<<0,t=t<<30|t>>>2;for(;i<40;i+=5)a=e^t^n,o=r<<5|r>>>27,s=o+a+s+1859775393+u[i]<<0,e=e<<30|e>>>2,a=r^e^t,o=s<<5|s>>>27,n=o+a+n+1859775393+u[i+1]<<0,r=r<<30|r>>>2,a=s^r^e,o=n<<5|n>>>27,t=o+a+t+1859775393+u[i+2]<<0,s=s<<30|s>>>2,a=n^s^r,o=t<<5|t>>>27,e=o+a+e+1859775393+u[i+3]<<0,n=n<<30|n>>>2,a=t^n^s,o=e<<5|e>>>27,r=o+a+r+1859775393+u[i+4]<<0,t=t<<30|t>>>2;for(;i<60;i+=5)a=e&t|e&n|t&n,o=r<<5|r>>>27,s=o+a+s-1894007588+u[i]<<0,e=e<<30|e>>>2,a=r&e|r&t|e&t,o=s<<5|s>>>27,n=o+a+n-1894007588+u[i+1]<<0,r=r<<30|r>>>2,a=s&r|s&e|r&e,o=n<<5|n>>>27,t=o+a+t-1894007588+u[i+2]<<0,s=s<<30|s>>>2,a=n&s|n&r|s&r,o=t<<5|t>>>27,e=o+a+e-1894007588+u[i+3]<<0,n=n<<30|n>>>2,a=t&n|t&s|n&s,o=e<<5|e>>>27,r=o+a+r-1894007588+u[i+4]<<0,t=t<<30|t>>>2;for(;i<80;i+=5)a=e^t^n,o=r<<5|r>>>27,s=o+a+s-899497514+u[i]<<0,e=e<<30|e>>>2,a=r^e^t,o=s<<5|s>>>27,n=o+a+n-899497514+u[i+1]<<0,r=r<<30|r>>>2,a=s^r^e,o=n<<5|n>>>27,t=o+a+t-899497514+u[i+2]<<0,s=s<<30|s>>>2,a=n^s^r,o=t<<5|t>>>27,e=o+a+e-899497514+u[i+3]<<0,n=n<<30|n>>>2,a=t^n^s,o=e<<5|e>>>27,r=o+a+r-899497514+u[i+4]<<0,t=t<<30|t>>>2;this.h0=this.h0+r<<0,this.h1=this.h1+e<<0,this.h2=this.h2+t<<0,this.h3=this.h3+n<<0,this.h4=this.h4+s<<0};Qt.prototype.hex=function(){this.finalize();var r=this.h0,e=this.h1,t=this.h2,n=this.h3,s=this.h4;return ae[r>>28&15]+ae[r>>24&15]+ae[r>>20&15]+ae[r>>16&15]+ae[r>>12&15]+ae[r>>8&15]+ae[r>>4&15]+ae[r&15]+ae[e>>28&15]+ae[e>>24&15]+ae[e>>20&15]+ae[e>>16&15]+ae[e>>12&15]+ae[e>>8&15]+ae[e>>4&15]+ae[e&15]+ae[t>>28&15]+ae[t>>24&15]+ae[t>>20&15]+ae[t>>16&15]+ae[t>>12&15]+ae[t>>8&15]+ae[t>>4&15]+ae[t&15]+ae[n>>28&15]+ae[n>>24&15]+ae[n>>20&15]+ae[n>>16&15]+ae[n>>12&15]+ae[n>>8&15]+ae[n>>4&15]+ae[n&15]+ae[s>>28&15]+ae[s>>24&15]+ae[s>>20&15]+ae[s>>16&15]+ae[s>>12&15]+ae[s>>8&15]+ae[s>>4&15]+ae[s&15]};Qt.prototype.toString=Qt.prototype.hex;Qt.prototype.digest=function(){this.finalize();var r=this.h0,e=this.h1,t=this.h2,n=this.h3,s=this.h4;return[r>>24&255,r>>16&255,r>>8&255,r&255,e>>24&255,e>>16&255,e>>8&255,e&255,t>>24&255,t>>16&255,t>>8&255,t&255,n>>24&255,n>>16&255,n>>8&255,n&255,s>>24&255,s>>16&255,s>>8&255,s&255]};Qt.prototype.array=Qt.prototype.digest;Qt.prototype.arrayBuffer=function(){this.finalize();var r=new ArrayBuffer(20),e=new DataView(r);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),r};var jx=!1,qm=r=>(jx||(console.warn(["The default method for hashing keys is insecure and will be replaced in a future version,","but hasn't been replaced yet as to not break existing caches. It's recommended that you use","a more secure hashing algorithm to avoid cache poisoning.","","See this page for more information:","|","\u2514> https://js.langchain.com/docs/troubleshooting/warnings/insecure-cache-algorithm"].join(`
117
+ `)),jx=!0),new Qt(!0).update(r).hex());var z="0123456789abcdef".split(""),wR=[-2147483648,8388608,32768,128],er=[24,16,8,0],Sl=[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];var je=[];function Or(r,e){e?(je[0]=je[16]=je[1]=je[2]=je[3]=je[4]=je[5]=je[6]=je[7]=je[8]=je[9]=je[10]=je[11]=je[12]=je[13]=je[14]=je[15]=0,this.blocks=je):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],r?(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=r}Or.prototype.update=function(r){if(!this.finalized){var e,t=typeof r;if(t!=="string"){if(t==="object"){if(r===null)throw new Error(ERROR);if(ARRAY_BUFFER&&r.constructor===ArrayBuffer)r=new Uint8Array(r);else if(!Array.isArray(r)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(r)))throw new Error(ERROR)}else throw new Error(ERROR);e=!0}for(var n,s=0,a,i=r.length,o=this.blocks;s<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(a=this.start;s<i&&a<64;++s)o[a>>>2]|=r[s]<<er[a++&3];else for(a=this.start;s<i&&a<64;++s)n=r.charCodeAt(s),n<128?o[a>>>2]|=n<<er[a++&3]:n<2048?(o[a>>>2]|=(192|n>>>6)<<er[a++&3],o[a>>>2]|=(128|n&63)<<er[a++&3]):n<55296||n>=57344?(o[a>>>2]|=(224|n>>>12)<<er[a++&3],o[a>>>2]|=(128|n>>>6&63)<<er[a++&3],o[a>>>2]|=(128|n&63)<<er[a++&3]):(n=65536+((n&1023)<<10|r.charCodeAt(++s)&1023),o[a>>>2]|=(240|n>>>18)<<er[a++&3],o[a>>>2]|=(128|n>>>12&63)<<er[a++&3],o[a>>>2]|=(128|n>>>6&63)<<er[a++&3],o[a>>>2]|=(128|n&63)<<er[a++&3]);this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=o[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};Or.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var r=this.blocks,e=this.lastByteIndex;r[16]=this.block,r[e>>>2]|=wR[e&3],this.block=r[16],e>=56&&(this.hashed||this.hash(),r[0]=this.block,r[16]=r[1]=r[2]=r[3]=r[4]=r[5]=r[6]=r[7]=r[8]=r[9]=r[10]=r[11]=r[12]=r[13]=r[14]=r[15]=0),r[14]=this.hBytes<<3|this.bytes>>>29,r[15]=this.bytes<<3,this.hash()}};Or.prototype.hash=function(){var r=this.h0,e=this.h1,t=this.h2,n=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,u=this.blocks,c,l,d,f,p,m,h,g,w,b,x;for(c=16;c<64;++c)p=u[c-15],l=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=u[c-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,u[c]=u[c-16]+l+u[c-7]+d<<0;for(x=e&t,c=0;c<64;c+=4)this.first?(this.is224?(g=300032,p=u[0]-1413257819,o=p-150054599<<0,n=p+24177077<<0):(g=704751109,p=u[0]-210244248,o=p-1521486534<<0,n=p+143694565<<0),this.first=!1):(l=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),g=r&e,f=g^r&t^x,h=s&a^~s&i,p=o+d+h+Sl[c]+u[c],m=l+f,o=n+p<<0,n=p+m<<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&r,f=w^n&e^g,h=i&o^~i&s,p=a+d+h+Sl[c+1]+u[c+1],m=l+f,i=t+p<<0,t=p+m<<0,l=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),b=t&n,f=b^t&r^w,h=a&i^~a&o,p=s+d+h+Sl[c+2]+u[c+2],m=l+f,a=e+p<<0,e=p+m<<0,l=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),x=e&t,f=x^e&n^b,h=a&i^~a&o,p=s+d+h+Sl[c+3]+u[c+3],m=l+f,s=r+p<<0,r=p+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+r<<0,this.h1=this.h1+e<<0,this.h2=this.h2+t<<0,this.h3=this.h3+n<<0,this.h4=this.h4+s<<0,this.h5=this.h5+a<<0,this.h6=this.h6+i<<0,this.h7=this.h7+o<<0};Or.prototype.hex=function(){this.finalize();var r=this.h0,e=this.h1,t=this.h2,n=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,u=z[r>>>28&15]+z[r>>>24&15]+z[r>>>20&15]+z[r>>>16&15]+z[r>>>12&15]+z[r>>>8&15]+z[r>>>4&15]+z[r&15]+z[e>>>28&15]+z[e>>>24&15]+z[e>>>20&15]+z[e>>>16&15]+z[e>>>12&15]+z[e>>>8&15]+z[e>>>4&15]+z[e&15]+z[t>>>28&15]+z[t>>>24&15]+z[t>>>20&15]+z[t>>>16&15]+z[t>>>12&15]+z[t>>>8&15]+z[t>>>4&15]+z[t&15]+z[n>>>28&15]+z[n>>>24&15]+z[n>>>20&15]+z[n>>>16&15]+z[n>>>12&15]+z[n>>>8&15]+z[n>>>4&15]+z[n&15]+z[s>>>28&15]+z[s>>>24&15]+z[s>>>20&15]+z[s>>>16&15]+z[s>>>12&15]+z[s>>>8&15]+z[s>>>4&15]+z[s&15]+z[a>>>28&15]+z[a>>>24&15]+z[a>>>20&15]+z[a>>>16&15]+z[a>>>12&15]+z[a>>>8&15]+z[a>>>4&15]+z[a&15]+z[i>>>28&15]+z[i>>>24&15]+z[i>>>20&15]+z[i>>>16&15]+z[i>>>12&15]+z[i>>>8&15]+z[i>>>4&15]+z[i&15];return this.is224||(u+=z[o>>>28&15]+z[o>>>24&15]+z[o>>>20&15]+z[o>>>16&15]+z[o>>>12&15]+z[o>>>8&15]+z[o>>>4&15]+z[o&15]),u};Or.prototype.toString=Or.prototype.hex;Or.prototype.digest=function(){this.finalize();var r=this.h0,e=this.h1,t=this.h2,n=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,u=[r>>>24&255,r>>>16&255,r>>>8&255,r&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255];return this.is224||u.push(o>>>24&255,o>>>16&255,o>>>8&255,o&255),u};Or.prototype.array=Or.prototype.digest;Or.prototype.arrayBuffer=function(){this.finalize();var r=new ArrayBuffer(this.is224?28:32),e=new DataView(r);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),r};fn();var vR=(...r)=>qm(r.join("_"));var Gm=class{constructor(){Object.defineProperty(this,"keyEncoder",{enumerable:!0,configurable:!0,writable:!0,value:vR})}makeDefaultKeyEncoder(e){this.keyEncoder=e}},xR=new Map,kl=class r extends Gm{constructor(e){super(),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cache=e??new Map}lookup(e,t){return Promise.resolve(this.cache.get(this.keyEncoder(e,t))??null)}async update(e,t,n){this.cache.set(this.keyEncoder(e,t),n)}static global(){return new r(xR)}};yo();fn();so();var Dx=Dt(Lx(),1),kR=Object.defineProperty,RR=(r,e,t)=>e in r?kR(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,CR=(r,e,t)=>(RR(r,typeof e!="symbol"?e+"":e,t),t);function $R(r,e){let t=Array.from({length:r.length},(n,s)=>({start:s,end:s+1}));for(;t.length>1;){let n=null;for(let s=0;s<t.length-1;s++){let a=r.slice(t[s].start,t[s+1].end),i=e.get(a.join(","));i!=null&&(n==null||i<n[0])&&(n=[i,s])}if(n!=null){let s=n[1];t[s]={start:t[s].start,end:t[s+1].end},t.splice(s+1,1)}else break}return t}function NR(r,e){return r.length===1?[e.get(r.join(","))]:$R(r,e).map(t=>e.get(r.slice(t.start,t.end).join(","))).filter(t=>t!=null)}function jR(r){return r.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var Km=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(r,e){this.patStr=r.pat_str;let t=r.bpe_ranks.split(`
118
+ `).filter(Boolean).reduce((n,s)=>{let[a,i,...o]=s.split(" "),u=Number.parseInt(i,10);return o.forEach((c,l)=>n[c]=u+l),n},{});for(let[n,s]of Object.entries(t)){let a=Dx.default.toByteArray(n);this.rankMap.set(a.join(","),s),this.textMap.set(s,a)}this.specialTokens={...r.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[s,a])=>(n[a]=this.textEncoder.encode(s),n),{})}encode(r,e=[],t="all"){let n=new RegExp(this.patStr,"ug"),s=Km.specialTokenRegex(Object.keys(this.specialTokens)),a=[],i=new Set(e==="all"?Object.keys(this.specialTokens):e),o=new Set(t==="all"?Object.keys(this.specialTokens).filter(c=>!i.has(c)):t);if(o.size>0){let c=Km.specialTokenRegex([...o]),l=r.match(c);if(l!=null)throw new Error(`The text contains a special token that is not allowed: ${l[0]}`)}let u=0;for(;;){let c=null,l=u;for(;s.lastIndex=l,c=s.exec(r),!(c==null||i.has(c[0]));)l=c.index+1;let d=c?.index??r.length;for(let p of r.substring(u,d).matchAll(n)){let m=this.textEncoder.encode(p[0]),h=this.rankMap.get(m.join(","));if(h!=null){a.push(h);continue}a.push(...NR(m,this.rankMap))}if(c==null)break;let f=this.specialTokens[c[0]];a.push(f),u=c.index+c[0].length}return a}decode(r){let e=[],t=0;for(let a=0;a<r.length;++a){let i=r[a],o=this.textMap.get(i)??this.inverseSpecialTokens[i];o!=null&&(e.push(o),t+=o.length)}let n=new Uint8Array(t),s=0;for(let a of e)n.set(a,s),s+=a.length;return this.textDecoder.decode(n)}},Cl=Km;CR(Cl,"specialTokenRegex",r=>new RegExp(r.map(e=>jR(e)).join("|"),"g"));function Wm(r){switch(r){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")}}so();var $l={},MR=new Br({});async function zR(r){return r in $l||($l[r]=MR.fetch(`https://tiktoken.pages.dev/js/${r}.json`).then(e=>e.json()).then(e=>new Cl(e)).catch(e=>{throw delete $l[r],e})),await $l[r]}async function Fx(r){return zR(Wm(r))}dt();var LR=r=>r.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":r.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":r.startsWith("gpt-4-32k")?"gpt-4-32k":r.startsWith("gpt-4-")?"gpt-4":r.startsWith("gpt-4o")?"gpt-4o":r;function Jm(r){return typeof r!="object"||!r?!1:!!("type"in r&&r.type==="function"&&"function"in r&&typeof r.function=="object"&&r.function&&"name"in r.function&&"parameters"in r.function)}var DR=()=>!1,Jo=class extends pe{get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.verbose=e.verbose??DR(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},Xo=class extends Jo{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}constructor({callbacks:e,callbackManager:t,...n}){let{cache:s,...a}=n;super({callbacks:e??t,...a}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_encoding",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof s=="object"?this.cache=s:s?this.cache=kl.global():this.cache=void 0,this.caller=new Br(n??{})}async getNumTokens(e){let t;typeof e=="string"?t=e:t=e.map(s=>typeof s=="string"?s:s.type==="text"&&"text"in s?s.text:"").join("");let n=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await Fx("modelName"in this?LR(this.modelName):"gpt2")}catch(s){console.warn("Failed to calculate number of tokens, falling back to approximate count",s)}if(this._encoding)try{n=this._encoding.encode(t).length}catch(s){console.warn("Failed to calculate number of tokens, falling back to approximate count",s)}return n}static _convertInputToPromptValue(e){return typeof e=="string"?new Ta(e):Array.isArray(e)?new Pa(e.map(Vt)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){let n={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([i,o])=>o!==void 0).map(([i,o])=>`${i}:${JSON.stringify(o)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}};ha();dt();Fr();Vr();Gi();ys();function Xm(r){let e=[];for(let t of r){let n=t;if(Array.isArray(t.content))for(let s=0;s<t.content.length;s++){let a=t.content[s];(Cb(a)||$b(a))&&n===t&&(n=new t.constructor({...n,content:[...t.content.slice(0,s),Nb(a),...t.content.slice(s+1)]}))}e.push(n)}return e}var Nl=class r extends Xo{constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","chat_models",this._llmType()]}),Object.defineProperty(this,"disableStreaming",{enumerable:!0,configurable:!0,writable:!0,value:!1})}_separateRunnableConfigFromCallOptionsCompat(e){let[t,n]=super._separateRunnableConfigFromCallOptions(e);return n.signal=t.signal,[t,n]}async invoke(e,t){let n=r._convertInputToPromptValue(e);return(await this.generatePrompt([n],t,t?.callbacks)).generations[0][0].message}async*_streamResponseChunks(e,t,n){throw new Error("Not implemented.")}async*_streamIterator(e,t){if(this._streamResponseChunks===r.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(e,t);else{let s=r._convertInputToPromptValue(e).toChatMessages(),[a,i]=this._separateRunnableConfigFromCallOptionsCompat(t),o={...a.metadata,...this.getLsParams(i)},u=await Le.configure(a.callbacks,this.callbacks,a.tags,this.tags,o,this.metadata,{verbose:this.verbose}),c={options:i,invocation_params:this?.invocationParams(i),batch_size:1},l=await u?.handleChatModelStart(this.toJSON(),[Xm(s)],a.runId,void 0,c,void 0,void 0,a.runName),d,f;try{for await(let p of this._streamResponseChunks(s,i,l?.[0])){if(p.message.id==null){let m=l?.at(0)?.runId;m!=null&&p.message._updateId(`run-${m}`)}p.message.response_metadata={...p.generationInfo,...p.message.response_metadata},yield p.message,d?d=d.concat(p):d=p,$p(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((l??[]).map(m=>m?.handleLLMError(p))),p}await Promise.all((l??[]).map(p=>p?.handleLLMEnd({generations:[[d]],llmOutput:f})))}}getLsParams(e){let t=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:e.stop,ls_provider:t}}async _generateUncached(e,t,n,s){let a=e.map(d=>d.map(Vt)),i;if(s!==void 0&&s.length===a.length)i=s;else{let d={...n.metadata,...this.getLsParams(t)},f=await Le.configure(n.callbacks,this.callbacks,n.tags,this.tags,d,this.metadata,{verbose:this.verbose}),p={options:t,invocation_params:this?.invocationParams(t),batch_size:1};i=await f?.handleChatModelStart(this.toJSON(),a.map(Xm),n.runId,void 0,p,void 0,void 0,n.runName)}let o=[],u=[];if(!!i?.[0].handlers.find(xp)&&!this.disableStreaming&&a.length===1&&this._streamResponseChunks!==r.prototype._streamResponseChunks)try{let d=await this._streamResponseChunks(a[0],t,i?.[0]),f,p;for await(let m of d){if(m.message.id==null){let h=i?.at(0)?.runId;h!=null&&m.message._updateId(`run-${h}`)}f===void 0?f=m:f=Dr(f,m),$p(m.message)&&m.message.usage_metadata!==void 0&&(p={tokenUsage:{promptTokens:m.message.usage_metadata.input_tokens,completionTokens:m.message.usage_metadata.output_tokens,totalTokens:m.message.usage_metadata.total_tokens}})}if(f===void 0)throw new Error("Received empty response from chat model call.");o.push([f]),await i?.[0].handleLLMEnd({generations:o,llmOutput:p})}catch(d){throw await i?.[0].handleLLMError(d),d}else{let d=await Promise.allSettled(a.map((f,p)=>this._generate(f,{...t,promptIndex:p},i?.[p])));await Promise.all(d.map(async(f,p)=>{if(f.status==="fulfilled"){let m=f.value;for(let h of m.generations){if(h.message.id==null){let g=i?.at(0)?.runId;g!=null&&h.message._updateId(`run-${g}`)}h.message.response_metadata={...h.generationInfo,...h.message.response_metadata}}return m.generations.length===1&&(m.generations[0].message.response_metadata={...m.llmOutput,...m.generations[0].message.response_metadata}),o[p]=m.generations,u[p]=m.llmOutput,i?.[p]?.handleLLMEnd({generations:[m.generations],llmOutput:m.llmOutput})}else return await i?.[p]?.handleLLMError(f.reason),Promise.reject(f.reason)}))}let l={generations:o,llmOutput:u.length?this._combineLLMOutput?.(...u):void 0};return Object.defineProperty(l,xc,{value:i?{runIds:i?.map(d=>d.runId)}:void 0,configurable:!0}),l}async _generateCached({messages:e,cache:t,llmStringKey:n,parsedOptions:s,handledOptions:a}){let i=e.map(g=>g.map(Vt)),o={...a.metadata,...this.getLsParams(s)},u=await Le.configure(a.callbacks,this.callbacks,a.tags,this.tags,o,this.metadata,{verbose:this.verbose}),c={options:s,invocation_params:this?.invocationParams(s),batch_size:1},l=await u?.handleChatModelStart(this.toJSON(),i.map(Xm),a.runId,void 0,c,void 0,void 0,a.runName),d=[],p=(await Promise.allSettled(i.map(async(g,w)=>{let b=r._convertInputToPromptValue(g).toString(),x=await t.lookup(b,n);return x==null&&d.push(w),x}))).map((g,w)=>({result:g,runManager:l?.[w]})).filter(({result:g})=>g.status==="fulfilled"&&g.value!=null||g.status==="rejected"),m=[];await Promise.all(p.map(async({result:g,runManager:w},b)=>{if(g.status==="fulfilled"){let x=g.value;return m[b]=x.map(I=>("message"in I&&cr(I.message)&&ln(I.message)&&(I.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0}),I.generationInfo={...I.generationInfo,tokenUsage:{}},I)),x.length&&await w?.handleLLMNewToken(x[0].text),w?.handleLLMEnd({generations:[x]},void 0,void 0,void 0,{cached:!0})}else return await w?.handleLLMError(g.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(g.reason)}));let h={generations:m,missingPromptIndices:d,startedRunManagers:l};return Object.defineProperty(h,xc,{value:l?{runIds:l?.map(g=>g.runId)}:void 0,configurable:!0}),h}async generate(e,t,n){let s;Array.isArray(t)?s={stop:t}:s=t;let a=e.map(m=>m.map(Vt)),[i,o]=this._separateRunnableConfigFromCallOptionsCompat(s);if(i.callbacks=i.callbacks??n,!this.cache)return this._generateUncached(a,o,i);let{cache:u}=this,c=this._getSerializedCacheKeyParametersForCall(o),{generations:l,missingPromptIndices:d,startedRunManagers:f}=await this._generateCached({messages:a,cache:u,llmStringKey:c,parsedOptions:o,handledOptions:i}),p={};if(d.length>0){let m=await this._generateUncached(d.map(h=>a[h]),o,i,f!==void 0?d.map(h=>f?.[h]):void 0);await Promise.all(m.generations.map(async(h,g)=>{let w=d[g];l[w]=h;let b=r._convertInputToPromptValue(a[w]).toString();return u.update(b,c,h)})),p=m.llmOutput??{}}return{generations:l,llmOutput:p}}invocationParams(e){return{}}_modelType(){return"base_chat_model"}serialize(){return{...this.invocationParams(),_type:this._llmType(),_model:this._modelType()}}async generatePrompt(e,t,n){let s=e.map(a=>a.toChatMessages());return this.generate(s,t,n)}async call(e,t,n){return(await this.generate([e.map(Vt)],t,n)).generations[0][0].message}async callPrompt(e,t,n){let s=e.toChatMessages();return this.call(s,t,n)}async predictMessages(e,t,n){return this.call(e,t,n)}async predict(e,t,n){let s=new ut(e),a=await this.call([s],t,n);if(typeof a.content!="string")throw new Error("Cannot use predict when output is not a string.");return a.content}withStructuredOutput(e,t){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(t?.strict)throw new Error('"strict" mode is not supported for this model by default.');let n=e,s=t?.name,a=_s(n)??"A function available to call.",i=t?.method,o=t?.includeRaw;if(i==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let u=s??"extract",c;yt(n)?c=[{type:"function",function:{name:u,description:a,parameters:lt(n)}}]:("name"in n&&(u=n.name),c=[{type:"function",function:{name:u,description:a,parameters:n}}]);let l=this.bindTools(c),d=Wt.from(h=>{if(!h.tool_calls||h.tool_calls.length===0)throw new Error("No tool calls found in the response.");let g=h.tool_calls.find(w=>w.name===u);if(!g)throw new Error(`No tool call found with name ${u}.`);return g.args});if(!o)return l.pipe(d).withConfig({runName:"StructuredOutput"});let f=hr.assign({parsed:(h,g)=>d.invoke(h.raw,g)}),p=hr.assign({parsed:()=>null}),m=f.withFallbacks({fallbacks:[p]});return Kt.from([{raw:l},m]).withConfig({runName:"StructuredOutputRunnable"})}};Ki();var Ym=class extends pe{parseResultWithPrompt(e,t,n){return this.parseResult(e,n)}_baseMessageToString(e){return typeof e.content=="string"?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return typeof e=="string"?this._callWithConfig(async(n,s)=>this.parseResult([{text:n}],s?.callbacks),e,{...t,runType:"parser"}):this._callWithConfig(async(n,s)=>this.parseResult([{message:n,text:this._baseMessageToString(n)}],s?.callbacks),e,{...t,runType:"parser"})}},Nn=class extends Ym{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,n){return this.parse(e,n)}_type(){throw new Error("_type not implemented")}},jn=class extends Error{constructor(e,t,n,s=!1){if(super(e),Object.defineProperty(this,"llmOutput",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"observation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sendToLLM",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.llmOutput=t,this.observation=n,this.sendToLLM=s,s&&(n===void 0||t===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");un(this,"OUTPUT_PARSING_FAILURE")}};fo();Ct();fn();_a();var wi=class extends Nn{async*_transform(e){for await(let t of e)typeof t=="string"?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async*transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:"parser"})}},Vs=class extends wi{constructor(e){super(e),Object.defineProperty(this,"diff",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.diff=e?.diff??this.diff}async*_transform(e){let t,n;for await(let s of e){if(typeof s!="string"&&typeof s.content!="string")throw new Error("Cannot handle non-string output.");let a;if(Cp(s)){if(typeof s.content!="string")throw new Error("Cannot handle non-string message output.");a=new Ur({message:s,text:s.content})}else if(cr(s)){if(typeof s.content!="string")throw new Error("Cannot handle non-string message output.");a=new Ur({message:jp(s),text:s.content})}else a=new dr({text:s});n===void 0?n=a:n=n.concat(a);let i=await this.parsePartialResult([n]);i!=null&&!Zr(i,t)&&(this.diff?yield this._diff(t,i):yield i,t=i)}}getFormatInstructions(){return""}};wu();Vr();ys();var qs=class extends Nn{static lc_name(){return"StructuredOutputParser"}toJSON(){return this.toJSONNotImplemented()}constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","structured"]})}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){let t=ft.object(Object.fromEntries(Object.entries(e).map(([n,s])=>[n,ft.string().describe(s)])));return new this(t)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
119
+
120
+ "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
121
+
122
+ For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
123
+ 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.
124
+ 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.
125
+
126
+ 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!
127
+
128
+ Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
129
+ \`\`\`json
130
+ ${JSON.stringify(lt(this.schema))}
131
+ \`\`\`
132
+ `}async parse(e){try{let t=e.trim(),s=(t.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||t.match(/```json\s*([\s\S]*?)```/)?.[1]||t).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(a,i)=>`"${i.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await Oa(this.schema,JSON.parse(s))}catch(t){throw new jn(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}};gd();Tp();var Yo=class extends Vs{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}static lc_name(){return"JsonOutputParser"}_concatOutputChunks(e,t){return this.diff?super._concatOutputChunks(e,t):t}_diff(e,t){if(t)return e?Mu(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return Ip(e[0].text)}async parse(e){return Ip(e,JSON.parse)}getFormatInstructions(){return""}};ls();Vr();function jl(r,e){if(r.function===void 0)return;let t;if(e?.partial)try{t=la(r.function.arguments??"{}")}catch{return}else try{t=JSON.parse(r.function.arguments)}catch(s){throw new jn([`Function "${r.function.name}" arguments:`,"",r.function.arguments,"","are not valid JSON.",`Error: ${s.message}`].join(`
133
+ `))}let n={name:r.function.name,args:t,type:"tool_call"};return e?.returnId&&(n.id=r.id),n}function Ux(r){if(r.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:r.id,type:"function",function:{name:r.name,arguments:JSON.stringify(r.args)}}}function Ml(r,e){return{name:r.function?.name,args:r.function?.arguments,id:r.id,error:e,type:"invalid_tool_call"}}var Qm=class extends Vs{static lc_name(){return"JsonOutputToolsParser"}constructor(e){super(e),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.returnId=e?.returnId??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,t=!0){let n=e[0].message,s;if(ln(n)&&n.tool_calls?.length?s=n.tool_calls.map(i=>{let{id:o,...u}=i;return this.returnId?{id:o,...u}:u}):n.additional_kwargs.tool_calls!==void 0&&(s=JSON.parse(JSON.stringify(n.additional_kwargs.tool_calls)).map(o=>jl(o,{returnId:this.returnId,partial:t}))),!s)return[];let a=[];for(let i of s)if(i!==void 0){let o={type:i.name,args:i.args,id:i.id};a.push(o)}return a}},Qo=class extends Qm{static lc_name(){return"JsonOutputKeyToolsParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(this.zodSchema===void 0)return e;let t=await _v(this.zodSchema,e);if(t.success)return t.data;throw new jn(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){let n=(await super.parsePartialResult(e)).filter(a=>a.type===this.keyName),s=n;if(n.length)return this.returnId||(s=n.map(a=>a.args)),this.returnSingle?s[0]:s}async parseResult(e){let n=(await super.parsePartialResult(e,!1)).filter(i=>i.type===this.keyName),s=n;return n.length?(this.returnId||(s=n.map(i=>i.args)),this.returnSingle?this._validateResult(s[0]):await Promise.all(s.map(i=>this._validateResult(i)))):void 0}};Vr();ys();function Gs(r){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:t,azureOpenAIApiKey:n,azureOpenAIBasePath:s,baseURL:a,azureADTokenProvider:i,azureOpenAIEndpoint:o}=r;if((n||i)&&s&&e)return`${s}/${e}`;if((n||i)&&o&&e)return`${o}/openai/deployments/${e}`;if(n||i){if(!t)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${t}.openai.azure.com/openai/deployments/${e}`}return a}dt();Vr();function eh(r){return r!==void 0&&Array.isArray(r.lc_namespace)}function th(r){return r!==void 0&&pe.isRunnable(r)&&"lc_name"in r.constructor&&typeof r.constructor.lc_name=="function"&&r.constructor.lc_name()==="RunnableToolLike"}function rh(r){return!!r&&typeof r=="object"&&"name"in r&&"schema"in r&&(yt(r.schema)||r.schema!=null&&typeof r.schema=="object"&&"type"in r.schema&&typeof r.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(r.schema.type))}function vi(r){return rh(r)||th(r)||eh(r)}ys();function Bx(r,e){let t=typeof e=="number"?void 0:e;return{name:r.name,description:r.description,parameters:lt(r.schema),...t?.strict!==void 0?{strict:t.strict}:{}}}function nh(r,e){let t=typeof e=="number"?void 0:e,n;return vi(r)?n={type:"function",function:Bx(r)}:n=r,t?.strict!==void 0&&(n.function.strict=t.strict),n}Rc();var Vx=Symbol("Let zodToJsonSchema decide on which parser to use"),Zx={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},qx=r=>typeof r=="string"?{...Zx,basePath:["#"],definitions:{},name:r}:{...Zx,basePath:["#"],definitions:{},...r};var eu=r=>"_def"in r?r._def:r;function Gx(r){if(!r)return!0;for(let e in r)return!1;return!0}var Hx=r=>{let e=qx(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:t,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[eu(s),{def:eu(s),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function sh(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function le(r,e,t,n,s){r[e]=t,sh(r,e,n,s)}gs();function Kx(){return{}}gs();function Wx(r,e){let t={type:"array"};return r.type?._def?.typeName!==v.ZodAny&&(t.items=G(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&le(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&le(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(le(t,"minItems",r.exactLength.value,r.exactLength.message,e),le(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function Jx(r,e){let t={type:"integer",format:"int64"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?le(t,"minimum",n.value,n.message,e):le(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),le(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?le(t,"maximum",n.value,n.message,e):le(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),le(t,"maximum",n.value,n.message,e));break;case"multipleOf":le(t,"multipleOf",n.value,n.message,e);break}return t}function Xx(){return{type:"boolean"}}function Yx(r,e){return G(r.type._def,e)}var Qx=(r,e)=>G(r.innerType._def,e);function ah(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,a)=>ah(r,e,s))};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 FR(r,e)}}var FR=(r,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let n of r.checks)switch(n.kind){case"min":le(t,"minimum",n.value,n.message,e);break;case"max":le(t,"maximum",n.value,n.message,e);break}return t};function e0(r,e){return{...G(r.innerType._def,e),default:r.defaultValue()}}function t0(r,e,t){return e.effectStrategy==="input"?G(r.schema._def,e,t):{}}function r0(r){return{type:"string",enum:[...r.values]}}var UR=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function n0(r,e){let t=[G(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),G(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return t.forEach(a=>{if(UR(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(n=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){let{additionalProperties:o,...u}=a;i=u}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}function s0(r,e){let t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}gs();var ih,Hs={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:()=>(ih===void 0&&(ih=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ih),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])$/,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})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function zl(r,e){let t={type:"string"};function n(s){return e.patternStrategy==="escape"?BR(s):s}if(r.checks)for(let s of r.checks)switch(s.kind){case"min":le(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,s.value):s.value,s.message,e);break;case"max":le(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,s.value):s.value,s.message,e);break;case"email":switch(e.emailStrategy){case"format:email":tr(t,"email",s.message,e);break;case"format:idn-email":tr(t,"idn-email",s.message,e);break;case"pattern:zod":rr(t,Hs.email,s.message,e);break}break;case"url":tr(t,"uri",s.message,e);break;case"uuid":tr(t,"uuid",s.message,e);break;case"regex":rr(t,s.regex,s.message,e);break;case"cuid":rr(t,Hs.cuid,s.message,e);break;case"cuid2":rr(t,Hs.cuid2,s.message,e);break;case"startsWith":rr(t,RegExp(`^${n(s.value)}`),s.message,e);break;case"endsWith":rr(t,RegExp(`${n(s.value)}$`),s.message,e);break;case"datetime":tr(t,"date-time",s.message,e);break;case"date":tr(t,"date",s.message,e);break;case"time":tr(t,"time",s.message,e);break;case"duration":tr(t,"duration",s.message,e);break;case"length":le(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,s.value):s.value,s.message,e),le(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,s.value):s.value,s.message,e);break;case"includes":{rr(t,RegExp(n(s.value)),s.message,e);break}case"ip":{s.version!=="v6"&&tr(t,"ipv4",s.message,e),s.version!=="v4"&&tr(t,"ipv6",s.message,e);break}case"emoji":rr(t,Hs.emoji,s.message,e);break;case"ulid":{rr(t,Hs.ulid,s.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{tr(t,"binary",s.message,e);break}case"contentEncoding:base64":{le(t,"contentEncoding","base64",s.message,e);break}case"pattern:zod":{rr(t,Hs.base64,s.message,e);break}}break}case"nanoid":rr(t,Hs.nanoid,s.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}var BR=r=>Array.from(r).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),tr=(r,e,t,n)=>{r.format||r.anyOf?.some(s=>s.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})):le(r,"format",e,t,n)},rr=(r,e,t,n)=>{r.pattern||r.allOf?.some(s=>s.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:a0(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):le(r,"pattern",a0(e,n),t,n)},a0=(r,e)=>{let t=typeof r=="function"?r():r;if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},s=n.i?t.source.toLowerCase():t.source,a="",i=!1,o=!1,u=!1;for(let c=0;c<s.length;c++){if(i){a+=s[c],i=!1;continue}if(n.i){if(o){if(s[c].match(/[a-z]/)){u?(a+=s[c],a+=`${s[c-2]}-${s[c]}`.toUpperCase(),u=!1):s[c+1]==="-"&&s[c+2]?.match(/[a-z]/)?(a+=s[c],u=!0):a+=`${s[c]}${s[c].toUpperCase()}`;continue}}else if(s[c].match(/[a-z]/)){a+=`[${s[c]}${s[c].toUpperCase()}]`;continue}}if(n.m){if(s[c]==="^"){a+=`(^|(?<=[\r
134
+ ]))`;continue}else if(s[c]==="$"){a+=`($|(?=[\r
135
+ ]))`;continue}}if(n.s&&s[c]==="."){a+=o?`${s[c]}\r
136
+ `:`[${s[c]}\r
137
+ ]`;continue}a+=s[c],s[c]==="\\"?i=!0:o&&s[c]==="]"?o=!1:!o&&s[c]==="["&&(o=!0)}try{let c=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 Ll(r,e){if(e.target==="openApi3"&&r.keyType?._def.typeName===v.ZodEnum)return{type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((n,s)=>({...n,[s]:G(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??{}}),{}),additionalProperties:!1};let t={type:"object",additionalProperties:G(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return t;if(r.keyType?._def.typeName===v.ZodString&&r.keyType._def.checks?.length){let n=Object.entries(zl(r.keyType._def,e)).reduce((s,[a,i])=>a==="type"?s:{...s,[a]:i},{});return{...t,propertyNames:n}}else if(r.keyType?._def.typeName===v.ZodEnum)return{...t,propertyNames:{enum:r.keyType._def.values}};return t}function i0(r,e){if(e.mapStrategy==="record")return Ll(r,e);let t=G(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=G(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}function o0(r){let e=r.values,n=Object.keys(r.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),s=Array.from(new Set(n.map(a=>typeof a)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function u0(){return{not:{}}}function c0(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var tu={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function d0(r,e){if(e.target==="openApi3")return l0(r,e);let t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(n=>n._def.typeName in tu&&(!n._def.checks||!n._def.checks.length))){let n=t.reduce((s,a)=>{let i=tu[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(t.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=t.reduce((s,a)=>{let i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(a._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===t.length){let s=n.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:t.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(t.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((n,s)=>[...n,...s._def.values.filter(a=>!n.includes(a))],[])};return l0(r,e)}var l0=(r,e)=>{let t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((n,s)=>G(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return t.length?{anyOf:t}:void 0};function p0(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:tu[r.innerType._def.typeName],nullable:!0}:{type:[tu[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=G(r.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let t=G(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function f0(r,e){let t={type:"number"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"int":t.type="integer",sh(t,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?le(t,"minimum",n.value,n.message,e):le(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),le(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?le(t,"maximum",n.value,n.message,e):le(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),le(t,"maximum",n.value,n.message,e));break;case"multipleOf":le(t,"multipleOf",n.value,n.message,e);break}return t}function ZR(r,e){return e.removeAdditionalStrategy==="strict"?r.catchall._def.typeName==="ZodNever"?r.unknownKeys!=="strict":G(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:r.catchall._def.typeName==="ZodNever"?r.unknownKeys==="passthrough":G(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function m0(r,e){let t={type:"object",...Object.entries(r.shape()).reduce((n,[s,a])=>{if(a===void 0||a._def===void 0)return n;let i=[...e.currentPath,"properties",s],o=G(a._def,{...e,currentPath:i,propertyPath:i});if(o===void 0)return n;if(e.openaiStrictMode&&a.isOptional()&&!a.isNullable()&&typeof a._def?.defaultValue>"u")throw new Error(`Zod field at \`${i.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...n.properties,[s]:o},required:a.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,s]}},{properties:{},required:[]}),additionalProperties:ZR(r,e)};return t.required.length||delete t.required,t}var h0=(r,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return G(r.innerType._def,{...e,currentPath:e.currentPath});let t=G(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};var g0=(r,e)=>{if(e.pipeStrategy==="input")return G(r.in._def,e);if(e.pipeStrategy==="output")return G(r.out._def,e);let t=G(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=G(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,n].filter(s=>s!==void 0)}};function _0(r,e){return G(r.type._def,e)}function y0(r,e){let n={type:"array",uniqueItems:!0,items:G(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&le(n,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&le(n,"maxItems",r.maxSize.value,r.maxSize.message,e),n}function b0(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,n)=>G(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:G(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,n)=>G(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}function w0(){return{not:{}}}function v0(){return{}}var x0=(r,e)=>G(r.innerType._def,e);function G(r,e,t=!1){let n=e.seen.get(r);if(e.override){let i=e.override?.(r,e,n,t);if(i!==Vx)return i}if(n&&!t){let i=VR(n,e);if(i!==void 0)return"$ref"in i&&e.seenRefs.add(i.$ref),i}let s={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,s);let a=GR(r,r.typeName,e,t);return a&&HR(r,e,a),s.jsonSchema=a,a}var VR=(r,e)=>{switch(e.$refStrategy){case"root":return{$ref:r.path.join("/")};case"extract-to-root":let t=r.path.slice(e.basePath.length+1).join("_");return t!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[t]=r.def),{$ref:[...e.basePath,e.definitionPath,t].join("/")};case"relative":return{$ref:qR(e.currentPath,r.path)};case"none":case"seen":return r.path.length<e.currentPath.length&&r.path.every((n,s)=>e.currentPath[s]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},qR=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return[(r.length-t).toString(),...e.slice(t)].join("/")},GR=(r,e,t,n)=>{switch(e){case v.ZodString:return zl(r,t);case v.ZodNumber:return f0(r,t);case v.ZodObject:return m0(r,t);case v.ZodBigInt:return Jx(r,t);case v.ZodBoolean:return Xx();case v.ZodDate:return ah(r,t);case v.ZodUndefined:return w0();case v.ZodNull:return c0(t);case v.ZodArray:return Wx(r,t);case v.ZodUnion:case v.ZodDiscriminatedUnion:return d0(r,t);case v.ZodIntersection:return n0(r,t);case v.ZodTuple:return b0(r,t);case v.ZodRecord:return Ll(r,t);case v.ZodLiteral:return s0(r,t);case v.ZodEnum:return r0(r);case v.ZodNativeEnum:return o0(r);case v.ZodNullable:return p0(r,t);case v.ZodOptional:return h0(r,t);case v.ZodMap:return i0(r,t);case v.ZodSet:return y0(r,t);case v.ZodLazy:return G(r.getter()._def,t);case v.ZodPromise:return _0(r,t);case v.ZodNaN:case v.ZodNever:return u0();case v.ZodEffects:return t0(r,t,n);case v.ZodAny:return Kx();case v.ZodUnknown:return v0();case v.ZodDefault:return e0(r,t);case v.ZodBranded:return Yx(r,t);case v.ZodReadonly:return x0(r,t);case v.ZodCatch:return Qx(r,t);case v.ZodPipeline:return g0(r,t);case v.ZodFunction:case v.ZodVoid:case v.ZodSymbol:return;default:return(s=>{})(e)}},HR=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t);var oh=(r,e)=>{let t=Hx(e),n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=G(r._def,n===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,n]},!1)??{},a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(s.title=a);let i=(()=>{if(Gx(t.definitions))return;let u={},c=new Set;for(let l=0;l<500;l++){let d=Object.entries(t.definitions).filter(([f])=>!c.has(f));if(d.length===0)break;for(let[f,p]of d)u[f]=G(eu(p),{...t,currentPath:[...t.basePath,t.definitionPath,f]},!0)??{},c.add(f)}return u})(),o=n===void 0?i?{...s,[t.definitionPath]:i}:s:t.nameStrategy==="duplicate-ref"?{...s,...i||t.seenRefs.size?{[t.definitionPath]:{...i,...t.seenRefs.size?{[n]:s}:void 0}}:void 0}:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,n].join("/"),[t.definitionPath]:{...i,[n]:s}};return t.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="jsonSchema2019-09"&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o};function KR(r,e){return oh(r,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function E0(r,e,t){return ux({type:"json_schema",json_schema:{...t,name:e,strict:!0,schema:KR(r,{name:e})}},n=>r.parse(JSON.parse(n)))}function ru(r,e){return r.lc_error_code=e,r.message=`${r.message}
138
+
139
+ Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
140
+ `,r}function xi(r){let e;return r.constructor.name===gr.name?(e=new Error(r.message),e.name="TimeoutError"):r.constructor.name===be.name?(e=new Error(r.message),e.name="AbortError"):r.status===400&&r.message.includes("tool_calls")?e=ru(r,"INVALID_TOOL_RESULTS"):r.status===401?e=ru(r,"MODEL_AUTHENTICATION"):r.status===429?e=ru(r,"MODEL_RATE_LIMIT"):r.status===404?e=ru(r,"MODEL_NOT_FOUND"):e=r,e}function uh(r){if(r)return r==="any"||r==="required"?"required":r==="auto"?"auto":r==="none"?"none":typeof r=="string"?{type:"function",function:{name:r}}:r}function WR(r,e){let t={...r};return Object.defineProperties(t,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),t}function A0(r,e,t){if(jt(r))return E0(r,e,t);if(_t(r))return WR({type:"json_schema",json_schema:{...t,name:e,strict:!0,schema:lo(r,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>Sc(r,JSON.parse(n)));throw new Error("Unsupported schema response format")}function JR(r){return r.anyOf!==void 0&&Array.isArray(r.anyOf)}function O0(r){let e=["namespace functions {",""];for(let t of r)t.description&&e.push(`// ${t.description}`),Object.keys(t.parameters.properties??{}).length>0?(e.push(`type ${t.name} = (_: {`),e.push(I0(t.parameters,0)),e.push("}) => any;")):e.push(`type ${t.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
141
+ `)}function I0(r,e){let t=[];for(let[n,s]of Object.entries(r.properties??{}))s.description&&e<2&&t.push(`// ${s.description}`),r.required?.includes(n)?t.push(`${n}: ${Dl(s,e)},`):t.push(`${n}?: ${Dl(s,e)},`);return t.map(n=>" ".repeat(e)+n).join(`
142
+ `)}function Dl(r,e){if(JR(r))return r.anyOf.map(t=>Dl(t,e)).join(" | ");switch(r.type){case"string":return r.enum?r.enum.map(t=>`"${t}"`).join(" | "):"string";case"number":return r.enum?r.enum.map(t=>`${t}`).join(" | "):"number";case"integer":return r.enum?r.enum.map(t=>`${t}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",I0(r,e+2),"}"].join(`
143
+ `);case"array":return r.items?`${Dl(r.items,e)}[]`:"any[]";default:return""}}function T0(r,e){let t;return vi(r)?t=nh(r):t=r,t.type==="function"&&e?.strict!==void 0&&(t.function.strict=e.strict),t}function Fl(r){return"type"in r&&r.type!=="function"&&r.type!=="custom"}function P0(r){return r!=null&&typeof r=="object"&&"type"in r&&r.type!=="function"}function S0(r){return typeof r=="object"&&r!==null&&"metadata"in r&&typeof r.metadata=="object"&&r.metadata!==null&&"customTool"in r.metadata&&typeof r.metadata.customTool=="object"&&r.metadata.customTool!==null}function ch(r){return"type"in r&&r.type==="custom"&&"custom"in r&&typeof r.custom=="object"&&r.custom!==null}function k0(r){if(r.type==="custom_tool_call")return{...r,type:"tool_call",call_id:r.id,id:r.call_id,name:r.name,isCustomTool:!0,args:{input:r.input}}}function R0(r){return r.type==="tool_call"&&"isCustomTool"in r&&r.isCustomTool===!0}function C0(r){let e=()=>{if(r.custom.format){if(r.custom.format.type==="grammar")return{type:"grammar",definition:r.custom.format.grammar.definition,syntax:r.custom.format.grammar.syntax};if(r.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:r.custom.name,description:r.custom.description,format:e()}}function $0(r){let e=()=>{if(r.format){if(r.format.type==="grammar")return{type:"grammar",grammar:{definition:r.format.definition,syntax:r.format.syntax}};if(r.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:r.name,description:r.description,format:e()}}}var Ul="__openai_function_call_ids__";function Vl(r){return r&&(/^o\d/.test(r)||r.startsWith("gpt-5"))}function XR(r){return r!==void 0&&typeof r.schema=="object"}function YR(r){return r.role!=="system"&&r.role!=="developer"&&r.role!=="assistant"&&r.role!=="user"&&r.role!=="function"&&r.role!=="tool"&&console.warn(`Unknown message role: ${r.role}`),r.role}function dh(r){let e=r._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":{if(!Zt.isInstance(r))throw new Error("Invalid generic chat message");return YR(r)}default:throw new Error(`Unknown message type: ${e}`)}}var N0={providerName:"ChatOpenAI",fromStandardTextBlock(r){return{type:"text",text:r.text}},fromStandardImageBlock(r){if(r.source_type==="url")return{type:"image_url",image_url:{url:r.url,...r.metadata?.detail?{detail:r.metadata.detail}:{}}};if(r.source_type==="base64")return{type:"image_url",image_url:{url:`data:${r.mime_type??""};base64,${r.data}`,...r.metadata?.detail?{detail:r.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${r.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(r){if(r.source_type==="url"){let e=Sp({dataUrl:r.url});if(!e)throw new Error(`URL audio blocks with source_type ${r.source_type} must be formatted as a data URL for ChatOpenAI`);let t=e.mime_type||r.mime_type||"",n;try{n=Pp(t)}catch{throw new Error(`Audio blocks with source_type ${r.source_type} must have mime type of audio/wav or audio/mp3`)}if(n.type!=="audio"||n.subtype!=="wav"&&n.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${r.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:n.subtype,data:e.data}}}if(r.source_type==="base64"){let e;try{e=Pp(r.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${r.source_type} must have mime type of audio/wav or audio/mp3`)}if(e.type!=="audio"||e.subtype!=="wav"&&e.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${r.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:r.data}}}throw new Error(`Audio content blocks with source_type ${r.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(r){if(r.source_type==="url"){if(!Sp({dataUrl:r.url}))throw new Error(`URL file blocks with source_type ${r.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:r.url,...r.metadata?.filename||r.metadata?.name?{filename:r.metadata?.filename||r.metadata?.name}:{}}}}if(r.source_type==="base64")return{type:"file",file:{file_data:`data:${r.mime_type??""};base64,${r.data}`,...r.metadata?.filename||r.metadata?.name||r.metadata?.title?{filename:r.metadata?.filename||r.metadata?.name||r.metadata?.title}:{}}};if(r.source_type==="id")return{type:"file",file:{file_id:r.id}};throw new Error(`File content blocks with source_type ${r.source_type} are not supported for ChatOpenAI`)}};function lh(r,e){return r.flatMap(t=>{let n=dh(t);n==="system"&&Vl(e)&&(n="developer");let s=typeof t.content=="string"?t.content:t.content.map(i=>jr(i)?kp(i,N0):i),a={role:n,content:s};if(t.name!=null&&(a.name=t.name),t.additional_kwargs.function_call!=null&&(a.function_call=t.additional_kwargs.function_call,a.content=""),ln(t)&&t.tool_calls?.length?(a.tool_calls=t.tool_calls.map(Ux),a.content=""):(t.additional_kwargs.tool_calls!=null&&(a.tool_calls=t.additional_kwargs.tool_calls),t.tool_call_id!=null&&(a.tool_call_id=t.tool_call_id)),t.additional_kwargs.audio&&typeof t.additional_kwargs.audio=="object"&&"id"in t.additional_kwargs.audio){let i={role:"assistant",audio:{id:t.additional_kwargs.audio.id}};return[a,i]}return a})}var nu=class extends Nl{_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","service_tier"]}get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","verbosity","promptCacheKey"]}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(e){super(e??{}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"frequencyPenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"presencePenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logitBias",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"gpt-3.5-turbo"}),Object.defineProperty(this,"modelKwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stopSequences",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logprobs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topLogprobs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"organization",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"__includeRawResponse",{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,"clientConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"supportsStrictToolCalling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"audio",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"modalities",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reasoning",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"zdrEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"service_tier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"promptCacheKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"defaultOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.apiKey=e?.apiKey??e?.configuration?.apiKey??we("OPENAI_API_KEY"),this.organization=e?.configuration?.organization??we("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,this.user=e?.user,this.__includeRawResponse=e?.__includeRawResponse,this.audio=e?.audio,this.modalities=e?.modalities,this.reasoning=e?.reasoning,this.maxTokens=e?.maxCompletionTokens??e?.maxTokens,this.disableStreaming=e?.disableStreaming??this.disableStreaming,this.promptCacheKey=e?.promptCacheKey??this.promptCacheKey,this.streaming=e?.streaming??!1,this.disableStreaming&&(this.streaming=!1),this.streamUsage=e?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration},e?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),e?.service_tier!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=e?.zdrEnabled??!1}_getReasoningParams(e){if(!Vl(this.model))return;let t;return this.reasoning!==void 0&&(t={...t,...this.reasoning}),e?.reasoning!==void 0&&(t={...t,...e.reasoning}),t}_getResponseFormat(e){return e&&e.type==="json_schema"&&e.json_schema.schema&&yt(e.json_schema.schema)?A0(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}_combineCallOptions(e){return{...this.defaultOptions,...e??{}}}_getClientOptions(e){if(!this.client){let n={baseURL:this.clientConfig.baseURL},s=Gs(n),a={...this.clientConfig,baseURL:s,timeout:this.timeout,maxRetries:0};a.baseURL||delete a.baseURL,this.client=new W(a)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return S0(e)?$0(e.metadata.customTool):Jm(e)?t?.strict!==void 0?{...e,function:{...e.function,strict:t.strict}}:e:T0(e,t)}bindTools(e,t){let n;return t?.strict!==void 0?n=t.strict:this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling),this.withConfig({tools:e.map(s=>Fl(s)?s:this._convertChatOpenAIToolToCompletionsTool(s,{strict:n})),...t})}async stream(e,t){return super.stream(e,this._combineCallOptions(t))}async invoke(e,t){return super.invoke(e,this._combineCallOptions(t))}_combineLLMOutput(...e){return e.reduce((t,n)=>(n&&n.tokenUsage&&(t.tokenUsage.completionTokens+=n.tokenUsage.completionTokens??0,t.tokenUsage.promptTokens+=n.tokenUsage.promptTokens??0,t.tokenUsage.totalTokens+=n.tokenUsage.totalTokens??0),t),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let t=0,n=0,s=0;this.model==="gpt-3.5-turbo-0301"?(n=4,s=-1):(n=3,s=1);let a=await Promise.all(e.map(async i=>{let o=await this.getNumTokens(i.content),u=await this.getNumTokens(dh(i)),c=i.name!==void 0?s+await this.getNumTokens(i.name):0,l=o+n+u+c,d=i;if(d._getType()==="function"&&(l-=2),d.additional_kwargs?.function_call&&(l+=3),d?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(d.additional_kwargs.function_call?.name)),d.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(d.additional_kwargs.function_call?.arguments)))}catch(f){console.error("Error parsing function arguments",f,JSON.stringify(d.additional_kwargs.function_call)),l+=await this.getNumTokens(d.additional_kwargs.function_call?.arguments)}return t+=l,l}));return t+=3,{totalCount:t,countPerMessage:a}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async n=>n.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([n.message])).countPerMessage[0]:await this.getNumTokens(n.message.content)))).reduce((n,s)=>n+s,0)}async _getEstimatedTokenCountFromPrompt(e,t,n){let s=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&n!=="auto"){let a=O0(t);s+=await this.getNumTokens(a),s+=9}return t&&e.find(a=>a._getType()==="system")&&(s-=4),n==="none"?s+=1:typeof n=="object"&&(s+=await this.getNumTokens(n.name)+4),s}_getStructuredOutputMethod(e){let t={...e};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(t?.method===void 0)return"jsonSchema"}else t.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return t.method}withStructuredOutput(e,t){let n,s,a,i;XR(e)?(n=e.schema,s=e.name,a=e.method,i=e.includeRaw):(n=e,s=t?.name,a=t?.method,i=t?.includeRaw);let o,u;if(t?.strict!==void 0&&a==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");if(a=this._getStructuredOutputMethod({...t,method:a}),a==="jsonMode"){yt(n)?u=qs.fromZodSchema(n):u=new Yo;let f=lt(n);o=this.withConfig({response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...f}}})}else if(a==="jsonSchema"){let f={name:s??"extract",description:_s(n),schema:n,strict:t?.strict},p=lt(f.schema);if(o=this.withConfig({response_format:{type:"json_schema",json_schema:f},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:f.name,description:f.description,...p}}}),yt(n)){let m=qs.fromZodSchema(n);u=Wt.from(h=>"parsed"in h.additional_kwargs?h.additional_kwargs.parsed:m)}else u=new Yo}else{let f=s??"extract";if(yt(n)){let p=lt(n);o=this.withConfig({tools:[{type:"function",function:{name:f,description:p.description,parameters:p}}],tool_choice:{type:"function",function:{name:f}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:f,...p}},...t?.strict!==void 0?{strict:t.strict}:{}}),u=new Qo({returnSingle:!0,keyName:f,zodSchema:n})}else{let p;typeof n.name=="string"&&typeof n.parameters=="object"&&n.parameters!=null?(p=n,f=n.name):(f=n.title??f,p={name:f,description:n.description??"",parameters:n});let m=lt(n);o=this.withConfig({tools:[{type:"function",function:p}],tool_choice:{type:"function",function:{name:f}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:f,...m}},...t?.strict!==void 0?{strict:t.strict}:{}}),u=new Qo({returnSingle:!0,keyName:f})}}if(!i)return o.pipe(u);let c=hr.assign({parsed:(f,p)=>u.invoke(f.raw,p)}),l=hr.assign({parsed:()=>null}),d=c.withFallbacks({fallbacks:[l]});return Kt.from([{raw:o},d])}},Bl=class extends nu{invocationParams(e){let t;e?.strict!==void 0?t=e.strict:this.supportsStrictToolCalling!==void 0&&(t=this.supportsStrictToolCalling);let n={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,stream:this.streaming,previous_response_id:e?.previous_response_id,truncation:e?.truncation,include:e?.include,tools:e?.tools?.length?this._reduceChatOpenAITools(e.tools,{stream:this.streaming,strict:t}):void 0,tool_choice:P0(e?.tool_choice)?e?.tool_choice:(()=>{let a=uh(e?.tool_choice);if(typeof a=="object"&&"type"in a){if(a.type==="function")return{type:"function",name:a.function.name};if(a.type==="allowed_tools")return{type:"allowed_tools",mode:a.allowed_tools.mode,tools:a.allowed_tools.tools};if(a.type==="custom")return{type:"custom",name:a.custom.name}}})(),text:(()=>{if(e?.text)return e.text;let a=this._getResponseFormat(e?.response_format);return a?.type==="json_schema"?a.json_schema.schema!=null?{format:{type:"json_schema",schema:a.json_schema.schema,description:a.json_schema.description,name:a.json_schema.name,strict:a.json_schema.strict}}:void 0:{format:a}})(),parallel_tool_calls:e?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},s=this._getReasoningParams(e);return s!==void 0&&(n.reasoning=s),n}async _generate(e,t){let n=this.invocationParams(t);if(n.stream){let s=this._streamResponseChunks(e,t),a;for await(let i of s)i.message.response_metadata={...i.generationInfo,...i.message.response_metadata},a=a?.concat(i)??i;return{generations:a?[a]:[],llmOutput:{estimatedTokenUsage:a?.message?.usage_metadata}}}else{let s=this._convertMessagesToResponsesParams(e),a=await this.completionWithRetry({input:s,...n,stream:!1},{signal:t?.signal,...t?.options});return{generations:[{text:a.output_text,message:this._convertResponsesMessageToBaseMessage(a)}],llmOutput:{id:a.id,estimatedTokenUsage:a.usage?{promptTokens:a.usage.input_tokens,completionTokens:a.usage.output_tokens,totalTokens:a.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(e,t,n){let s=await this.completionWithRetry({...this.invocationParams(t),input:this._convertMessagesToResponsesParams(e),stream:!0},t);for await(let a of s){let i=this._convertResponsesDeltaToBaseMessageChunk(a);i!=null&&(yield i,await n?.handleLLMNewToken(i.text||"",{prompt:t.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:i}))}}async completionWithRetry(e,t){return this.caller.call(async()=>{let n=this._getClientOptions(t);try{return e.text?.format?.type==="json_schema"&&!e.stream?await this.client.responses.parse(e,n):await this.client.responses.create(e,n)}catch(s){throw xi(s)}})}_convertResponsesMessageToBaseMessage(e){if(e.error){let u=new Error(e.error.message);throw u.name=e.error.code,u}let t,n=[],s=[],a=[],i={model:e.model,created_at:e.created_at,id:e.id,incomplete_details:e.incomplete_details,metadata:e.metadata,object:e.object,status:e.status,user:e.user,service_tier:e.service_tier,model_name:e.model},o={};for(let u of e.output)if(u.type==="message")t=u.id,n.push(...u.content.flatMap(c=>c.type==="output_text"?("parsed"in c&&c.parsed!=null&&(o.parsed=c.parsed),{type:"text",text:c.text,annotations:c.annotations}):c.type==="refusal"?(o.refusal=c.refusal,[]):c));else if(u.type==="function_call"){let c={function:{name:u.name,arguments:u.arguments},id:u.call_id};try{s.push(jl(c,{returnId:!0}))}catch(l){let d;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(d=l.message),a.push(Ml(c,d))}o[Ul]??={},u.id&&(o[Ul][u.call_id]=u.id)}else if(u.type==="reasoning")o.reasoning=u;else if(u.type==="custom_tool_call"){let c=k0(u);c?s.push(c):a.push(Ml(u,"Malformed custom tool call"))}else o.tool_outputs??=[],o.tool_outputs.push(u);return new Je({id:t,content:n,tool_calls:s,invalid_tool_calls:a,usage_metadata:e.usage,additional_kwargs:o,response_metadata:i})}_convertResponsesDeltaToBaseMessageChunk(e){let t=[],n={},s,a=[],i={},o={},u;if(e.type==="response.output_text.delta")t.push({type:"text",text:e.delta,index:e.content_index});else if(e.type==="response.output_text.annotation.added")t.push({type:"text",text:"",annotations:[e.annotation],index:e.content_index});else if(e.type==="response.output_item.added"&&e.item.type==="message")u=e.item.id;else if(e.type==="response.output_item.added"&&e.item.type==="function_call")a.push({type:"tool_call_chunk",name:e.item.name,args:e.item.arguments,id:e.item.call_id,index:e.output_index}),o[Ul]={[e.item.call_id]:e.item.id};else if(e.type==="response.output_item.done"&&["web_search_call","file_search_call","computer_call","code_interpreter_call","mcp_call","mcp_list_tools","mcp_approval_request","image_generation_call","custom_tool_call"].includes(e.item.type))o.tool_outputs=[e.item];else if(e.type==="response.created")i.id=e.response.id,i.model_name=e.response.model,i.model=e.response.model;else if(e.type==="response.completed"){let c=this._convertResponsesMessageToBaseMessage(e.response);s=e.response.usage,e.response.text?.format?.type==="json_schema"&&(o.parsed??=JSON.parse(c.text));for(let[l,d]of Object.entries(e.response))l!=="id"&&(i[l]=d)}else if(e.type==="response.function_call_arguments.delta")a.push({type:"tool_call_chunk",args:e.delta,index:e.output_index});else if(e.type==="response.web_search_call.completed"||e.type==="response.file_search_call.completed")n={tool_outputs:{id:e.item_id,type:e.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(e.type==="response.refusal.done")o.refusal=e.refusal;else if(e.type==="response.output_item.added"&&"item"in e&&e.item.type==="reasoning"){let c=e.item.summary?e.item.summary.map((l,d)=>({...l,index:d})):void 0;o.reasoning={id:e.item.id,type:e.item.type,...c?{summary:c}:{}}}else if(e.type==="response.reasoning_summary_part.added")o.reasoning={type:"reasoning",summary:[{...e.part,index:e.summary_index}]};else if(e.type==="response.reasoning_summary_text.delta")o.reasoning={type:"reasoning",summary:[{text:e.delta,type:"summary_text",index:e.summary_index}]};else return e.type==="response.image_generation_call.partial_image",null;return new Ur({text:t.map(c=>c.text).join(""),message:new ht({id:u,content:t,tool_call_chunks:a,usage_metadata:s,additional_kwargs:o,response_metadata:i}),generationInfo:n})}_convertMessagesToResponsesParams(e){return e.flatMap(t=>{let n=t.additional_kwargs,s=dh(t);if(s==="system"&&Vl(this.model)&&(s="developer"),s==="function")throw new Error("Function messages are not supported in Responses API");if(s==="tool"){let a=t;return n?.type==="computer_call_output"?{type:"computer_call_output",output:(()=>{if(typeof a.content=="string")return{type:"computer_screenshot",image_url:a.content};if(Array.isArray(a.content)){let o=a.content.find(c=>c.type==="computer_screenshot");if(o)return o;let u=a.content.find(c=>c.type==="image_url");if(u)return{type:"computer_screenshot",image_url:typeof u.image_url=="string"?u.image_url:u.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:a.tool_call_id}:a.metadata?.customTool?{type:"custom_tool_call_output",call_id:a.tool_call_id,output:a.content}:{type:"function_call_output",call_id:a.tool_call_id,id:a.id?.startsWith("fc_")?a.id:void 0,output:typeof a.content!="string"?JSON.stringify(a.content):a.content}}if(s==="assistant"){if(!this.zdrEnabled&&t.response_metadata.output!=null&&Array.isArray(t.response_metadata.output)&&t.response_metadata.output.length>0&&t.response_metadata.output.every(l=>"type"in l))return t.response_metadata.output;let a=[];if(n?.reasoning&&!this.zdrEnabled){let l=this._convertReasoningSummary(n.reasoning);a.push(l)}let{content:i}=t;n?.refusal&&(typeof i=="string"&&(i=[{type:"output_text",text:i,annotations:[]}]),i=[...i,{type:"refusal",refusal:n.refusal}]),(typeof i=="string"||i.length>0)&&a.push({type:"message",role:"assistant",...t.id&&!this.zdrEnabled&&t.id.startsWith("msg_")?{id:t.id}:{},content:typeof i=="string"?i:i.flatMap(l=>l.type==="text"?{type:"output_text",text:l.text,annotations:l.annotations??[]}:l.type==="output_text"||l.type==="refusal"?l:[])});let o=n?.[Ul];ln(t)&&t.tool_calls?.length?a.push(...t.tool_calls.map(l=>R0(l)?{type:"custom_tool_call",id:l.call_id,call_id:l.id??"",input:l.args.input,name:l.name}:{type:"function_call",name:l.name,arguments:JSON.stringify(l.args),call_id:l.id,...this.zdrEnabled?{id:o?.[l.id]}:{}})):n?.tool_calls&&a.push(...n.tool_calls.map(l=>({type:"function_call",name:l.function.name,call_id:l.id,arguments:l.function.arguments,...this.zdrEnabled?{id:o?.[l.id]}:{}})));let u=t.response_metadata.output?.length?t.response_metadata.output:n.tool_outputs,c=["computer_call","mcp_call","code_interpreter_call","image_generation_call"];if(u!=null){let d=u?.filter(f=>c.includes(f.type));d.length>0&&a.push(...d)}return a}if(s==="user"||s==="system"||s==="developer"){if(typeof t.content=="string")return{type:"message",role:s,content:t.content};let a=[],i=t.content.flatMap(o=>(o.type==="mcp_approval_response"&&a.push({type:"mcp_approval_response",approval_request_id:o.approval_request_id,approve:o.approve}),jr(o)?kp(o,N0):o.type==="text"?{type:"input_text",text:o.text}:o.type==="image_url"?{type:"input_image",image_url:typeof o.image_url=="string"?o.image_url:o.image_url.url,detail:typeof o.image_url=="string"?"auto":o.image_url.detail}:o.type==="input_text"||o.type==="input_image"||o.type==="input_file"?o:[]));return i.length>0&&a.push({type:"message",role:s,content:i}),a}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${s}`),[]})}_convertReasoningSummary(e){let t=(e.summary.length>1?e.summary.reduce((n,s)=>{let a=n.at(-1);return a.index===s.index?a.text+=s.text:n.push(s),n},[{...e.summary[0]}]):e.summary).map(n=>Object.fromEntries(Object.entries(n).filter(([s])=>s!=="index")));return{...e,summary:t}}_reduceChatOpenAITools(e,t){let n=[];for(let s of e)Fl(s)?(s.type==="image_generation"&&t?.stream&&(s.partial_images=1),n.push(s)):Jm(s)?n.push({type:"function",name:s.function.name,parameters:s.function.parameters,description:s.function.description,strict:t?.strict??null}):ch(s)&&n.push(C0(s));return n}},Zl=class extends nu{invocationParams(e,t){let n;e?.strict!==void 0?n=e.strict:this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling);let s={};e?.stream_options!==void 0?s={stream_options:e.stream_options}:this.streamUsage&&(this.streaming||t?.streaming)&&(s={stream_options:{include_usage:!0}});let a={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:e?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:e?.functions,function_call:e?.function_call,tools:e?.tools?.length?e.tools.map(o=>this._convertChatOpenAIToolToCompletionsTool(o,{strict:n})):void 0,tool_choice:uh(e?.tool_choice),response_format:this._getResponseFormat(e?.response_format),seed:e?.seed,...s,parallel_tool_calls:e?.parallel_tool_calls,...this.audio||e?.audio?{audio:this.audio||e?.audio}:{},...this.modalities||e?.modalities?{modalities:this.modalities||e?.modalities}:{},...this.modelKwargs,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey};e?.prediction!==void 0&&(a.prediction=e.prediction),this.service_tier!==void 0&&(a.service_tier=this.service_tier),e?.service_tier!==void 0&&(a.service_tier=e.service_tier);let i=this._getReasoningParams(e);return i!==void 0&&i.effort!==void 0&&(a.reasoning_effort=i.effort),Vl(a.model)?a.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:a.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,a}async _generate(e,t,n){let s={},a=this.invocationParams(t),i=lh(e,this.model);if(a.stream){let o=this._streamResponseChunks(e,t,n),u={};for await(let m of o){m.message.response_metadata={...m.generationInfo,...m.message.response_metadata};let h=m.generationInfo?.completion??0;u[h]===void 0?u[h]=m:u[h]=u[h].concat(m)}let c=Object.entries(u).sort(([m],[h])=>parseInt(m,10)-parseInt(h,10)).map(([m,h])=>h),{functions:l,function_call:d}=this.invocationParams(t),f=await this._getEstimatedTokenCountFromPrompt(e,l,d),p=await this._getNumTokensFromGenerations(c);return s.input_tokens=f,s.output_tokens=p,s.total_tokens=f+p,{generations:c,llmOutput:{estimatedTokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}else{let o=await this.completionWithRetry({...a,stream:!1,messages:i},{signal:t?.signal,...t?.options}),{completion_tokens:u,prompt_tokens:c,total_tokens:l,prompt_tokens_details:d,completion_tokens_details:f}=o?.usage??{};u&&(s.output_tokens=(s.output_tokens??0)+u),c&&(s.input_tokens=(s.input_tokens??0)+c),l&&(s.total_tokens=(s.total_tokens??0)+l),(d?.audio_tokens!==null||d?.cached_tokens!==null)&&(s.input_token_details={...d?.audio_tokens!==null&&{audio:d?.audio_tokens},...d?.cached_tokens!==null&&{cache_read:d?.cached_tokens}}),(f?.audio_tokens!==null||f?.reasoning_tokens!==null)&&(s.output_token_details={...f?.audio_tokens!==null&&{audio:f?.audio_tokens},...f?.reasoning_tokens!==null&&{reasoning:f?.reasoning_tokens}});let p=[];for(let m of o?.choices??[]){let g={text:m.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(m.message??{role:"assistant"},o)};g.generationInfo={...m.finish_reason?{finish_reason:m.finish_reason}:{},...m.logprobs?{logprobs:m.logprobs}:{}},ln(g.message)&&(g.message.usage_metadata=s),g.message=new Je(Object.fromEntries(Object.entries(g.message).filter(([w])=>!w.startsWith("lc_")))),p.push(g)}return{generations:p,llmOutput:{tokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}}async*_streamResponseChunks(e,t,n){let s=lh(e,this.model),a={...this.invocationParams(t,{streaming:!0}),messages:s,stream:!0},i,o=await this.completionWithRetry(a,t),u;for await(let c of o){let l=c?.choices?.[0];if(c.usage&&(u=c.usage),!l)continue;let{delta:d}=l;if(!d)continue;let f=this._convertCompletionsDeltaToBaseMessageChunk(d,c,i);i=d.role??i;let p={prompt:t.promptIndex??0,completion:l.index??0};if(typeof f.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let m={...p};l.finish_reason!=null&&(m.finish_reason=l.finish_reason,m.system_fingerprint=c.system_fingerprint,m.model_name=c.model,m.service_tier=c.service_tier),this.logprobs&&(m.logprobs=l.logprobs);let h=new Ur({message:f,text:f.content,generationInfo:m});yield h,await n?.handleLLMNewToken(h.text??"",p,void 0,void 0,void 0,{chunk:h})}if(u){let c={...u.prompt_tokens_details?.audio_tokens!==null&&{audio:u.prompt_tokens_details?.audio_tokens},...u.prompt_tokens_details?.cached_tokens!==null&&{cache_read:u.prompt_tokens_details?.cached_tokens}},l={...u.completion_tokens_details?.audio_tokens!==null&&{audio:u.completion_tokens_details?.audio_tokens},...u.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:u.completion_tokens_details?.reasoning_tokens}};yield new Ur({message:new ht({content:"",response_metadata:{usage:{...u}},usage_metadata:{input_tokens:u.prompt_tokens,output_tokens:u.completion_tokens,total_tokens:u.total_tokens,...Object.keys(c).length>0&&{input_token_details:c},...Object.keys(l).length>0&&{output_token_details:l}}}),text:""})}if(t.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(e,t){let n=this._getClientOptions(t),s=e.response_format&&e.response_format.type==="json_schema";return this.caller.call(async()=>{try{return s&&!e.stream?await this.client.chat.completions.parse(e,n):await this.client.chat.completions.create(e,n)}catch(a){throw xi(a)}})}_convertCompletionsMessageToBaseMessage(e,t){let n=e.tool_calls;switch(e.role){case"assistant":{let s=[],a=[];for(let u of n??[])try{s.push(jl(u,{returnId:!0}))}catch(c){a.push(Ml(u,c.message))}let i={function_call:e.function_call,tool_calls:n};this.__includeRawResponse!==void 0&&(i.__raw_response=t);let o={model_name:t.model,...t.system_fingerprint?{usage:{...t.usage},system_fingerprint:t.system_fingerprint}:{}};return e.audio&&(i.audio=e.audio),new Je({content:e.content||"",tool_calls:s,invalid_tool_calls:a,additional_kwargs:i,response_metadata:o,id:t.id})}default:return new Zt(e.content||"",e.role??"unknown")}}_convertCompletionsDeltaToBaseMessageChunk(e,t,n){let s=e.role??n,a=e.content??"",i;e.function_call?i={function_call:e.function_call}:e.tool_calls?i={tool_calls:e.tool_calls}:i={},this.__includeRawResponse&&(i.__raw_response=t),e.audio&&(i.audio={...e.audio,index:t.choices[0].index});let o={usage:{...t.usage}};if(s==="user")return new fs({content:a,response_metadata:o});if(s==="assistant"){let u=[];if(Array.isArray(e.tool_calls))for(let c of e.tool_calls)u.push({name:c.function?.name,args:c.function?.arguments,id:c.id,index:c.index,type:"tool_call_chunk"});return new ht({content:a,tool_call_chunks:u,additional_kwargs:i,id:t.id,response_metadata:o})}else return s==="system"?new pn({content:a,response_metadata:o}):s==="developer"?new pn({content:a,response_metadata:o,additional_kwargs:{__openai_role__:"developer"}}):s==="function"?new ps({content:a,additional_kwargs:i,name:e.name,response_metadata:o}):s==="tool"?new da({content:a,additional_kwargs:i,tool_call_id:e.tool_call_id,response_metadata:o}):new ds({content:a,role:s,response_metadata:o})}},su=class r extends nu{get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}constructor(e){super(e),Object.defineProperty(this,"fields",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"useResponsesApi",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"responses",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"completions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.useResponsesApi=e?.useResponsesApi??!1,this.responses=e?.responses??new Bl(e),this.completions=e?.completions??new Zl(e)}_useResponsesApi(e){let t=e?.tools?.some(Fl),n=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,s=e?.tools?.some(ch);return this.useResponsesApi||t||n||s}getLsParams(e){let t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(t):this.completions.getLsParams(t)}invocationParams(e){let t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(t):this.completions.invocationParams(t)}async _generate(e,t,n){return this._useResponsesApi(t)?this.responses._generate(e,t):this.completions._generate(e,t,n)}async*_streamResponseChunks(e,t,n){if(this._useResponsesApi(t)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(t),n);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(t),n)}withConfig(e){let t=new r(this.fields);return t.defaultOptions={...this.defaultOptions,...e},t}};$a();_a();ha();Fr();Gi();so();wu();fo();ha();zr();pa();hs();pc();Vr();ys();var ph=class extends Jo{get lc_namespace(){return["langchain","tools"]}constructor(e){super(e??{}),Object.defineProperty(this,"returnDirect",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"verboseParsingErrors",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"responseFormat",{enumerable:!0,configurable:!0,writable:!0,value:"content"}),Object.defineProperty(this,"defaultConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig,this.metadata=e?.metadata??this.metadata}async invoke(e,t){let n,s=ue(ga(this.defaultConfig,t));return cn(e)?(n=e.args,s={...s,toolCall:e}):n=e,this.call(n,s)}async call(e,t,n){let s=cn(e)?e.args:e,a;if(yt(this.schema))try{a=await Oa(this.schema,s)}catch(m){let h="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(h=`${h}
144
+ Details: ${m.message}`),new cs(h,JSON.stringify(e))}else{let m=he(s,this.schema);if(!m.valid){let h="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(h=`${h}
145
+ Details: ${m.errors.map(g=>`${g.keywordLocation}: ${g.error}`).join(`
146
+ `)}`),new cs(h,JSON.stringify(e))}a=s}let i=Wb(t),u=await Le.configure(i.callbacks,this.callbacks,i.tags||n,this.tags,i.metadata,this.metadata,{verbose:this.verbose})?.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),i.runId,void 0,void 0,void 0,i.runName);delete i.runId;let c;try{c=await this._call(a,u,i)}catch(m){throw await u?.handleToolError(m),m}let l,d;if(this.responseFormat==="content_and_artifact")if(Array.isArray(c)&&c.length===2)[l,d]=c;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
147
+ Result: ${JSON.stringify(c)}`);else l=c;let f;cn(e)&&(f=e.id),!f&&Rb(i)&&(f=i.toolCall.id);let p=eC({content:l,artifact:d,toolCallId:f,name:this.name,metadata:this.metadata});return await u?.handleToolEnd(p),p}},ql=class extends ph{constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:ft.object({input:ft.string().optional()}).transform(t=>t.input)})}call(e,t){let n=typeof e=="string"||e==null?{input:e}:e;return super.call(n,t)}};function eC(r){let{content:e,artifact:t,toolCallId:n,metadata:s}=r;return n&&!Lb(e)?typeof e=="string"||Array.isArray(e)&&e.every(a=>typeof a=="object")?new Mr({status:"success",content:e,artifact:t,tool_call_id:n,name:r.name,metadata:s}):new Mr({status:"success",content:tC(e),artifact:t,tool_call_id:n,name:r.name,metadata:s}):e}function tC(r){try{return JSON.stringify(r,null,2)??""}catch{return`${r}`}}var fh=class extends ql{static lc_name(){return"DallEAPIWrapper"}constructor(e){e?.responseFormat!==void 0&&["url","b64_json"].includes(e.responseFormat)&&(e.dallEResponseFormat=e.responseFormat,e.responseFormat="content"),super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:"A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description."}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"dall-e-3"}),Object.defineProperty(this,"style",{enumerable:!0,configurable:!0,writable:!0,value:"vivid"}),Object.defineProperty(this,"quality",{enumerable:!0,configurable:!0,writable:!0,value:"standard"}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:"1024x1024"}),Object.defineProperty(this,"dallEResponseFormat",{enumerable:!0,configurable:!0,writable:!0,value:"url"}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let t=e?.apiKey??e?.openAIApiKey??we("OPENAI_API_KEY"),n=e?.organization??we("OPENAI_ORGANIZATION"),s={apiKey:t,organization:n,dangerouslyAllowBrowser:!0,baseURL:e?.baseUrl};this.client=new W(s),this.model=e?.model??e?.modelName??this.model,this.style=e?.style??this.style,this.quality=e?.quality??this.quality,this.n=e?.n??this.n,this.size=e?.size??this.size,this.dallEResponseFormat=e?.dallEResponseFormat??this.dallEResponseFormat,this.user=e?.user}processMultipleGeneratedUrls(e){return this.dallEResponseFormat==="url"?e.flatMap(t=>t.data?.flatMap(s=>s.url?{type:"image_url",image_url:s.url}:[]).filter(s=>s!==void 0&&s.type==="image_url"&&typeof s.image_url=="string"&&s.image_url!==void 0)??[]):e.flatMap(t=>t.data?.flatMap(s=>s.b64_json?{type:"image_url",image_url:{url:s.b64_json}}:[]).filter(s=>s!==void 0&&s.type==="image_url"&&typeof s.image_url=="object"&&"url"in s.image_url&&typeof s.image_url.url=="string"&&s.image_url.url!==void 0)??[])}async _call(e){let t={model:this.model,prompt:e,n:1,size:this.size,response_format:this.dallEResponseFormat,style:this.style,quality:this.quality,user:this.user};if(this.n>1){let a=await Promise.all(Array.from({length:this.n}).map(()=>this.client.images.generate(t)));return this.processMultipleGeneratedUrls(a)}let n=await this.client.images.generate(t),s="";return this.dallEResponseFormat==="url"?[s]=n.data?.map(a=>a.url).filter(a=>a!=="undefined")??[]:[s]=n.data?.map(a=>a.b64_json).filter(a=>a!=="undefined")??[],s}};Object.defineProperty(fh,"toolName",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"});hs();import*as Ks from"node:process";var Gl=class{constructor(e,t){this.#e="connector-runtime";this.init=()=>Promise.resolve();this.start=()=>Promise.resolve();this.stop=()=>Promise.resolve();this.#t=t,Ks.on?Ks.on("message",n=>{n.cmd===this.#e&&t.logger.verbose(`${Ks.pid} Received message from parent process:`,n)}):t.logger.warn("IPC channel is not available. process.on is undefined."),Ks.send||t.logger.warn("IPC channel is not available. process.send is undefined."),e.actions?.forEach(n=>{if(n.config.templates===void 0)return;let s={};Object.entries(n.config.templates).forEach(([a,i])=>{try{s[a]=t.templating.compile(i)}catch(o){t.logger.error(`Error compiling template ${a} for action ${n.identifier}`,o)}}),n.config.parsedTemplates=s})}#e;#t;set callbackFunction(e){this.connectorSDK.receiver.registerCallback(this.#r(e))}get connectorSDK(){return this.#t}#r(e){return async t=>{let n=this.#t.receiver.getActionConfig(t);return n?e(t,n):this.#t.receiver.responses.badRequest("Action not found")(t)}}};var M0=r=>{if(!r||typeof r!="object"){class e extends Nn{constructor(){super(...arguments);this.lc_namespace=["langchain","output_parsers","str"]}parse(s,a){return Promise.resolve(s)}getFormatInstructions(s){return"Return the output as a plain string."}}return new e}return qs.fromNamesAndDescriptions(r)};var z0=class extends Gl{constructor(t,n,s){super(t,n);this.CONNECTOR_INSTANCE="XOD_CONNECTOR_AI_AGENT_CONFIG";this.init=async()=>{this.#e.debug("Initializing AI Agent Connector Runner"),this.callbackFunction=async(t,n)=>{let s=n.config.systemPrompt;if(!s||s.trim()==="")return this.connectorSDK.receiver.responses.unprocessableEntity("System prompt not found")(t);let a=n.config.userPrompt;if(!a||a.trim()==="")return this.connectorSDK.receiver.responses.unprocessableEntity("Prompt not found")(t);let i=this.processPromptTemplate(`${s}
148
+
149
+ ${a}`,n.inputParameters,t.payload);this.#e.debug(`Processed prompt: ${i}`);let{outputParameters:o}=n,u=M0(o),c=this.escapeFormatInstructions(u.getFormatInstructions());this.#e.debug(`Processed format instructions: ${c}`);let l=Kt.from([ja.fromTemplate(`<system>${i}</system>
150
+ <format>${c}</format>
151
+ <user>{{question}}</user>`),this.langchain,u]);this.#e.info("Invoking AI agent...");let d=await l.invoke({question:n.config.question||""});this.#e.info(`AI response: ${JSON.stringify(d,null,2)}`);let f={...t,payload:d};return this.connectorSDK.receiver.responses.ok()(f)}};let{openai:a}=this.connectorSDK.config;this.#e=this.connectorSDK.logger,this.#e.debug(`Initializing AI Agent Connector Runner with model: ${a.model}`),this.#t=s??new su({apiKey:a.apiKey,model:a.model||"gpt-3.5-turbo",temperature:a.temperature||0,timeout:a.timeout||6e4})}#e;#t;get langchain(){if(this.#t===void 0)throw new Error("Langchain instance not initialized");return this.#t}escapeFormatInstructions(t){return t.replace(/```json\n([\s\S]*?)\n```/g,(n,s)=>`\`\`\`json
152
+ ${s.replace(/{/g,"{{").replace(/}/g,"}}")}
153
+ \`\`\``)}processPromptTemplate(t,n,s){let a=t;return n.forEach(i=>{let o=s[i.name];a=a.replace(new RegExp(`\\{\\{inputs\\.${i.name}\\}\\}`,"g"),o)}),a}};export{z0 as ConnectorRunnerAiAgent};
154
+ /*! Bundled license information:
155
+
156
+ @langchain/core/dist/utils/fast-json-patch/src/helpers.js:
157
+ (*!
158
+ * https://github.com/Starcounter-Jack/JSON-Patch
159
+ * (c) 2017-2022 Joachim Wester
160
+ * MIT licensed
161
+ *)
162
+
163
+ @langchain/core/dist/utils/fast-json-patch/src/duplex.js:
164
+ (*!
165
+ * https://github.com/Starcounter-Jack/JSON-Patch
166
+ * (c) 2013-2021 Joachim Wester
167
+ * MIT license
168
+ *)
169
+
170
+ mustache/mustache.mjs:
171
+ (*!
172
+ * mustache.js - Logic-less {{mustache}} templates with JavaScript
173
+ * http://github.com/janl/mustache.js
174
+ *)
175
+
176
+ @langchain/core/dist/utils/js-sha1/hash.js:
177
+ (*
178
+ * [js-sha1]{@link https://github.com/emn178/js-sha1}
179
+ *
180
+ * @version 0.6.0
181
+ * @author Chen, Yi-Cyuan [emn178@gmail.com]
182
+ * @copyright Chen, Yi-Cyuan 2014-2017
183
+ * @license MIT
184
+ *)
185
+
186
+ @langchain/core/dist/utils/js-sha256/hash.js:
187
+ (**
188
+ * [js-sha256]{@link https://github.com/emn178/js-sha256}
189
+ *
190
+ * @version 0.11.1
191
+ * @author Chen, Yi-Cyuan [emn178@gmail.com]
192
+ * @copyright Chen, Yi-Cyuan 2014-2025
193
+ * @license MIT
194
+ *)
195
+ */
196
+ //# sourceMappingURL=index.js.map