@arcgis/ai-orchestrator 5.0.0-next.139 → 5.0.0-next.140
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/embeddings.worker-hNLs24pe.js +23 -0
- package/dist/index.js +333 -8066
- package/package.json +2 -1
- package/dist/embeddings.worker-19IRaTB4.js +0 -23
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
const s = '(function(){"use strict";var Dd=/^(?:[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 er(n){return typeof n=="string"&&Dd.test(n)}function Ud(n){if(!er(n))throw TypeError("Invalid UUID");var e,t=new Uint8Array(16);return t[0]=(e=parseInt(n.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(n.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(n.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(n.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(n.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}for(var me=[],cs=0;cs<256;++cs)me.push((cs+256).toString(16).slice(1));function Hi(n,e=0){return(me[n[e+0]]+me[n[e+1]]+me[n[e+2]]+me[n[e+3]]+"-"+me[n[e+4]]+me[n[e+5]]+"-"+me[n[e+6]]+me[n[e+7]]+"-"+me[n[e+8]]+me[n[e+9]]+"-"+me[n[e+10]]+me[n[e+11]]+me[n[e+12]]+me[n[e+13]]+me[n[e+14]]+me[n[e+15]]).toLowerCase()}var Br,Fd=new Uint8Array(16);function Bd(){if(!Br&&(Br=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Br))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Br(Fd)}function zd(n){n=unescape(encodeURIComponent(n));for(var e=[],t=0;t<n.length;++t)e.push(n.charCodeAt(t));return e}var qd="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Hd="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Gd(n,e,t){function r(s,a,i,o){var u;if(typeof s=="string"&&(s=zd(s)),typeof a=="string"&&(a=Ud(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)");var 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(var l=0;l<16;++l)i[o+l]=c[l];return i}return Hi(c)}try{r.name=n}catch{}return r.DNS=qd,r.URL=Hd,r}var Vd=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Gi={randomUUID:Vd};function we(n,e,t){if(Gi.randomUUID&&!n)return Gi.randomUUID();n=n||{};var r=n.random||(n.rng||Bd)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Hi(r)}function Zd(n,e,t,r){switch(n){case 0:return e&t^~e&r;case 1:return e^t^r;case 2:return e&t^e&r^t&r;case 3:return e^t^r}}function ls(n,e){return n<<e|n>>>32-e}function Wd(n){var e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof n=="string"){var r=unescape(encodeURIComponent(n));n=[];for(var s=0;s<r.length;++s)n.push(r.charCodeAt(s))}else Array.isArray(n)||(n=Array.prototype.slice.call(n));n.push(128);for(var a=n.length/4+2,i=Math.ceil(a/16),o=new Array(i),u=0;u<i;++u){for(var c=new Uint32Array(16),l=0;l<16;++l)c[l]=n[u*64+l*4]<<24|n[u*64+l*4+1]<<16|n[u*64+l*4+2]<<8|n[u*64+l*4+3];o[u]=c}o[i-1][14]=(n.length-1)*8/Math.pow(2,32),o[i-1][14]=Math.floor(o[i-1][14]),o[i-1][15]=(n.length-1)*8&4294967295;for(var d=0;d<i;++d){for(var h=new Uint32Array(80),f=0;f<16;++f)h[f]=o[d][f];for(var p=16;p<80;++p)h[p]=ls(h[p-3]^h[p-8]^h[p-14]^h[p-16],1);for(var m=t[0],g=t[1],y=t[2],_=t[3],b=t[4],E=0;E<80;++E){var v=Math.floor(E/20),x=ls(m,5)+Zd(v,g,y,_)+b+e[v]+h[E]>>>0;b=_,_=y,y=ls(g,30)>>>0,g=m,m=x}t[0]=t[0]+m>>>0,t[1]=t[1]+g>>>0,t[2]=t[2]+y>>>0,t[3]=t[3]+_>>>0,t[4]=t[4]+b>>>0}return[t[0]>>24&255,t[0]>>16&255,t[0]>>8&255,t[0]&255,t[1]>>24&255,t[1]>>16&255,t[1]>>8&255,t[1]&255,t[2]>>24&255,t[2]>>16&255,t[2]>>8&255,t[2]&255,t[3]>>24&255,t[3]>>16&255,t[3]>>8&255,t[3]&255,t[4]>>24&255,t[4]>>16&255,t[4]>>8&255,t[4]&255]}var Vi=Gd("v5",80,Wd);function tr(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var ds,Zi;function Jd(){return Zi||(Zi=1,ds=function(n,e){if(typeof n!="string")throw new TypeError("Expected a string");return e=typeof e>"u"?"_":e,n.replace(/([a-z\\d])([A-Z])/g,"$1"+e+"$2").replace(/([A-Z]+)([A-Z][a-z\\d]+)/g,"$1"+e+"$2").toLowerCase()}),ds}var Kd=Jd(),Xd=tr(Kd),zr={exports:{}},Wi;function Qd(){if(Wi)return zr.exports;Wi=1;const n=/[\\p{Lu}]/u,e=/[\\p{Ll}]/u,t=/^[\\p{Lu}](?![\\p{Lu}])/gu,r=/([\\p{Alpha}\\p{N}_]|$)/u,s=/[_.\\- ]+/,a=new RegExp("^"+s.source),i=new RegExp(s.source+r.source,"gu"),o=new RegExp("\\\\d+"+r.source,"gu"),u=(h,f,p)=>{let m=!1,g=!1,y=!1;for(let _=0;_<h.length;_++){const b=h[_];m&&n.test(b)?(h=h.slice(0,_)+"-"+h.slice(_),m=!1,y=g,g=!0,_++):g&&y&&e.test(b)?(h=h.slice(0,_-1)+"-"+h.slice(_-1),y=g,g=!1,m=!0):(m=f(b)===b&&p(b)!==b,y=g,g=p(b)===b&&f(b)!==b)}return h},c=(h,f)=>(t.lastIndex=0,h.replace(t,p=>f(p))),l=(h,f)=>(i.lastIndex=0,o.lastIndex=0,h.replace(i,(p,m)=>f(m)).replace(o,p=>f(p))),d=(h,f)=>{if(!(typeof h=="string"||Array.isArray(h)))throw new TypeError("Expected the input to be `string | string[]`");if(f={pascalCase:!1,preserveConsecutiveUppercase:!1,...f},Array.isArray(h)?h=h.map(y=>y.trim()).filter(y=>y.length).join("-"):h=h.trim(),h.length===0)return"";const p=f.locale===!1?y=>y.toLowerCase():y=>y.toLocaleLowerCase(f.locale),m=f.locale===!1?y=>y.toUpperCase():y=>y.toLocaleUpperCase(f.locale);return h.length===1?f.pascalCase?m(h):p(h):(h!==p(h)&&(h=u(h,p,m)),h=h.replace(a,""),f.preserveConsecutiveUppercase?h=c(h,p):h=p(h),f.pascalCase&&(h=m(h.charAt(0))+h.slice(1)),l(h,m))};return zr.exports=d,zr.exports.default=d,zr.exports}Qd();function Yd(n,e){return e?.[n]||Xd(n)}function eh(n,e,t){const r={};for(const s in n)Object.hasOwn(n,s)&&(r[e(s,t)]=n[s]);return r}const Ji="__lc_escaped__";function th(n){return"lc"in n||Object.keys(n).length===1&&Ji in n}function rh(n){return{[Ji]:n}}function nh(n){return n!==null&&typeof n=="object"&&"lc_serializable"in n&&typeof n.toJSON=="function"}function hs(n){if(n!==null&&typeof n=="object"&&!Array.isArray(n)){if(nh(n))return n;const e=n;if(th(e))return rh(e);const t={};for(const[r,s]of Object.entries(e))t[r]=hs(s);return t}return Array.isArray(n)?n.map(e=>hs(e)):n}function Ki(n){return Array.isArray(n)?[...n]:{...n}}function sh(n,e){const t=Ki(n);for(const[r,s]of Object.entries(e)){const[a,...i]=r.split(".").reverse();let o=t;for(const u of i.reverse()){if(o[u]===void 0)break;o[u]=Ki(o[u]),o=o[u]}o[a]!==void 0&&(o[a]={lc:1,type:"secret",id:[s]})}return t}function Xi(n){const e=Object.getPrototypeOf(n);return typeof n.lc_name=="function"&&(typeof e.lc_name!="function"||n.lc_name()!==e.lc_name())?n.lc_name():n.name}class Et{static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Xi(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(([r])=>this.lc_serializable_keys?.includes(r))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof Et||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},t={},r=Object.keys(this.lc_kwargs).reduce((o,u)=>(o[u]=u in this?this[u]:this.lc_kwargs[u],o),{});for(let o=Object.getPrototypeOf(this);o;o=Object.getPrototypeOf(o))Object.assign(e,Reflect.get(o,"lc_aliases",this)),Object.assign(t,Reflect.get(o,"lc_secrets",this)),Object.assign(r,Reflect.get(o,"lc_attributes",this));Object.keys(t).forEach(o=>{let u=this,c=r;const[l,...d]=o.split(".").reverse();for(const h of d.reverse()){if(!(h in u)||u[h]===void 0)return;(!(h in c)||c[h]===void 0)&&(typeof u[h]=="object"&&u[h]!=null?c[h]={}:Array.isArray(u[h])&&(c[h]=[])),u=u[h],c=c[h]}l in u&&u[l]!==void 0&&(c[l]=c[l]||u[l])});const s={};for(const[o,u]of Object.entries(r))s[o]=hs(u);const a=Object.keys(t).length?sh(s,t):s,i=eh(a,Yd,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:i}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}const ah=()=>typeof window<"u"&&typeof window.document<"u",ih=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",oh=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),fs=()=>typeof Deno<"u",uh=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!fs(),ch=()=>{let n;return ah()?n="browser":uh()?n="node":ih()?n="webworker":oh()?n="jsdom":fs()?n="deno":n="other",n};let ps;function lh(){return ps===void 0&&(ps={library:"langchain-js",runtime:ch()}),ps}function Re(n){try{return typeof process<"u"?process.env?.[n]:fs()?Deno?.env.get(n):void 0}catch{return}}class dh{}class rr extends dh{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,Xi(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:Re("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 Et.prototype.toJSON.call(this)}toJSONNotImplemented(){return Et.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends rr{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:we()}),Object.assign(this,e)}}return new t}}const hh=n=>{const e=n;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"};var qr={exports:{}};qr.exports;var Qi;function fh(){return Qi||(Qi=1,(function(n){const t=(a=0)=>i=>`\\x1B[${38+a};5;${i}m`,r=(a=0)=>(i,o,u)=>`\\x1B[${38+a};2;${i};${o};${u}m`;function s(){const a=new Map,i={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};i.color.gray=i.color.blackBright,i.bgColor.bgGray=i.bgColor.bgBlackBright,i.color.grey=i.color.blackBright,i.bgColor.bgGrey=i.bgColor.bgBlackBright;for(const[o,u]of Object.entries(i)){for(const[c,l]of Object.entries(u))i[c]={open:`\\x1B[${l[0]}m`,close:`\\x1B[${l[1]}m`},u[c]=i[c],a.set(l[0],l[1]);Object.defineProperty(i,o,{value:u,enumerable:!1})}return Object.defineProperty(i,"codes",{value:a,enumerable:!1}),i.color.close="\\x1B[39m",i.bgColor.close="\\x1B[49m",i.color.ansi256=t(),i.color.ansi16m=r(),i.bgColor.ansi256=t(10),i.bgColor.ansi16m=r(10),Object.defineProperties(i,{rgbToAnsi256:{value:(o,u,c)=>o===u&&u===c?o<8?16:o>248?231:Math.round((o-8)/247*24)+232:16+36*Math.round(o/255*5)+6*Math.round(u/255*5)+Math.round(c/255*5),enumerable:!1},hexToRgb:{value:o=>{const u=/(?<colorString>[a-f\\d]{6}|[a-f\\d]{3})/i.exec(o.toString(16));if(!u)return[0,0,0];let{colorString:c}=u.groups;c.length===3&&(c=c.split("").map(d=>d+d).join(""));const l=Number.parseInt(c,16);return[l>>16&255,l>>8&255,l&255]},enumerable:!1},hexToAnsi256:{value:o=>i.rgbToAnsi256(...i.hexToRgb(o)),enumerable:!1}}),i}Object.defineProperty(n,"exports",{enumerable:!0,get:s})})(qr)),qr.exports}var ph=fh(),Yi=tr(ph);const mh="gen_ai.operation.name",gh="gen_ai.system",eo="gen_ai.request.model",_h="gen_ai.response.model",to="gen_ai.usage.input_tokens",ro="gen_ai.usage.output_tokens",no="gen_ai.usage.total_tokens",yh="gen_ai.request.max_tokens",bh="gen_ai.request.temperature",wh="gen_ai.request.top_p",vh="gen_ai.request.frequency_penalty",Eh="gen_ai.request.presence_penalty",Sh="gen_ai.response.finish_reasons",Ah="gen_ai.prompt",Oh="gen_ai.completion",Ih="gen_ai.request.extra_query",Rh="gen_ai.request.extra_body",Th="gen_ai.serialized.name",xh="gen_ai.serialized.signature",kh="gen_ai.serialized.doc",Ph="gen_ai.response.id",Ch="gen_ai.response.service_tier",Nh="gen_ai.response.system_fingerprint",$h="gen_ai.usage.input_token_details",Lh="gen_ai.usage.output_token_details",jh="langsmith.trace.session_id",Mh="langsmith.trace.session_name",Dh="langsmith.span.kind",Uh="langsmith.trace.name",Fh="langsmith.metadata",so="langsmith.span.tags",Bh="langsmith.request.streaming",zh="langsmith.request.headers",qh=(...n)=>fetch(...n),ao=Symbol.for("ls:fetch_implementation"),Hh=()=>{const n=globalThis[ao];return n?typeof n=="function"&&"Headers"in n&&"Request"in n&&"Response"in n:!1},Gh=n=>async(...e)=>{if(n||Te("DEBUG")==="true"){const[r,s]=e;console.log(`→ ${s?.method||"GET"} ${r}`)}const t=await(globalThis[ao]??qh)(...e);return(n||Te("DEBUG")==="true")&&console.log(`← ${t.status} ${t.statusText} ${t.url}`),t},io=()=>Te("PROJECT")??Xe("LANGCHAIN_SESSION")??"default",oo="0.3.74";let Ke;const Vh=()=>typeof window<"u"&&typeof window.document<"u",Zh=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Wh=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),uo=()=>typeof Deno<"u",Jh=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!uo(),co=()=>Ke||(typeof Bun<"u"?Ke="bun":Vh()?Ke="browser":Jh()?Ke="node":Zh()?Ke="webworker":Wh()?Ke="jsdom":uo()?Ke="deno":Ke="other",Ke);let ms;function lo(){if(ms===void 0){const n=co(),e=Xh();ms={library:"langsmith",runtime:n,sdk:"langsmith-js",sdk_version:oo,...e}}return ms}function ho(){const n=Kh(),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(const[r,s]of Object.entries(n))typeof s=="string"&&!t.includes(r)&&!r.toLowerCase().includes("key")&&!r.toLowerCase().includes("secret")&&!r.toLowerCase().includes("token")&&(r==="LANGCHAIN_REVISION_ID"?e.revision_id=s:e[r]=s);return e}function Kh(){const n={};try{if(typeof process<"u"&&process.env)for(const[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"?n[e]=t.slice(0,2)+"*".repeat(t.length-4)+t.slice(-2):n[e]=t)}catch{}return n}function Xe(n){try{return typeof process<"u"?process.env?.[n]:void 0}catch{return}}function Te(n){return Xe(`LANGSMITH_${n}`)||Xe(`LANGCHAIN_${n}`)}let gs;function Xh(){if(gs!==void 0)return gs;const n=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(const t of n){const r=Xe(t);r!==void 0&&(e[t]=r)}return gs=e,e}function fo(){return Xe("OTEL_ENABLED")==="true"||Te("OTEL_ENABLED")==="true"}class Qh{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){!this.hasWarned&&fo()&&(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 r;if(t.length===1&&typeof t[0]=="function"?r=t[0]:t.length===2&&typeof t[1]=="function"?r=t[1]:t.length===3&&typeof t[2]=="function"&&(r=t[2]),typeof r=="function")return r()}}class Yh{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new Qh})}getTracer(e,t){return this.mockTracer}getActiveSpan(){}setSpan(e,t){return e}getSpan(e){}setSpanContext(e,t){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}}class ef{active(){return{}}with(e,t){return t()}}const _s=Symbol.for("ls:otel_trace"),ys=Symbol.for("ls:otel_context"),po=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),tf=new Yh,rf=new ef;class nf{getTraceInstance(){return globalThis[_s]??tf}getContextInstance(){return globalThis[ys]??rf}initializeGlobalInstances(e){globalThis[_s]===void 0&&(globalThis[_s]=e.trace),globalThis[ys]===void 0&&(globalThis[ys]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[po]=e}getDefaultOTLPTracerComponents(){return globalThis[po]??void 0}}const bs=new nf;function mo(){return bs.getTraceInstance()}function sf(){return bs.getContextInstance()}function af(){return bs.getDefaultOTLPTracerComponents()}const of={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function uf(n){return of[n]||n}class cf{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,t){for(const r of e)try{if(!r.run)continue;if(r.operation==="post"){const s=this.createSpanForRun(r,r.run,t.get(r.id));s&&!r.run.end_time&&this.spans.set(r.id,s)}else this.updateSpanForRun(r,r.run)}catch(s){console.error(`Error processing operation ${r.id}:`,s)}}createSpanForRun(e,t,r){const s=r&&mo().getSpan(r);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,r){return this.setSpanAttributes(e,t,r),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{const r=this.spans.get(e.id);if(!r){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(r,t,e),t.error?(r.setStatus({code:2}),r.recordException(new Error(t.error))):r.setStatus({code:1});const s=t.end_time;s&&(r.end(new Date(s)),this.spans.delete(e.id))}catch(r){console.error(`Failed to update span for run ${e.id}:`,r)}}extractModelName(e){if(e.extra?.metadata){const t=e.extra.metadata;if(t.ls_model_name)return t.ls_model_name;if(t.invocation_params){const r=t.invocation_params;if(r.model)return r.model;if(r.model_name)return r.model_name}}}setSpanAttributes(e,t,r){if("run_type"in t&&t.run_type){e.setAttribute(Dh,t.run_type);const o=uf(t.run_type||"chain");e.setAttribute(mh,o)}"name"in t&&t.name&&e.setAttribute(Uh,t.name),"session_id"in t&&t.session_id&&e.setAttribute(jh,t.session_id),"session_name"in t&&t.session_name&&e.setAttribute(Mh,t.session_name),this.setGenAiSystem(e,t);const s=this.extractModelName(t);s&&e.setAttribute(eo,s),"prompt_tokens"in t&&typeof t.prompt_tokens=="number"&&e.setAttribute(to,t.prompt_tokens),"completion_tokens"in t&&typeof t.completion_tokens=="number"&&e.setAttribute(ro,t.completion_tokens),"total_tokens"in t&&typeof t.total_tokens=="number"&&e.setAttribute(no,t.total_tokens),this.setInvocationParameters(e,t);const a=t.extra?.metadata||{};for(const[o,u]of Object.entries(a))u!=null&&e.setAttribute(`${Fh}.${o}`,String(u));const i=t.tags;if(i&&Array.isArray(i)?e.setAttribute(so,i.join(", ")):i&&e.setAttribute(so,String(i)),"serialized"in t&&typeof t.serialized=="object"){const o=t.serialized;o.name&&e.setAttribute(Th,String(o.name)),o.signature&&e.setAttribute(xh,String(o.signature)),o.doc&&e.setAttribute(kh,String(o.doc))}this.setIOAttributes(e,r)}setGenAiSystem(e,t){let r="langchain";const s=this.extractModelName(t);if(s){const a=s.toLowerCase();a.includes("anthropic")||a.startsWith("claude")?r="anthropic":a.includes("bedrock")?r="aws.bedrock":a.includes("azure")&&a.includes("openai")?r="az.ai.openai":a.includes("azure")&&a.includes("inference")?r="az.ai.inference":a.includes("cohere")?r="cohere":a.includes("deepseek")?r="deepseek":a.includes("gemini")?r="gemini":a.includes("groq")?r="groq":a.includes("watson")||a.includes("ibm")?r="ibm.watsonx.ai":a.includes("mistral")?r="mistral_ai":a.includes("gpt")||a.includes("openai")?r="openai":a.includes("perplexity")||a.includes("sonar")?r="perplexity":a.includes("vertex")?r="vertex_ai":(a.includes("xai")||a.includes("grok"))&&(r="xai")}e.setAttribute(gh,r)}setInvocationParameters(e,t){if(!t.extra?.metadata?.invocation_params)return;const r=t.extra.metadata.invocation_params;r.max_tokens!==void 0&&e.setAttribute(yh,r.max_tokens),r.temperature!==void 0&&e.setAttribute(bh,r.temperature),r.top_p!==void 0&&e.setAttribute(wh,r.top_p),r.frequency_penalty!==void 0&&e.setAttribute(vh,r.frequency_penalty),r.presence_penalty!==void 0&&e.setAttribute(Eh,r.presence_penalty)}setIOAttributes(e,t){if(t.run.inputs)try{const r=t.run.inputs;typeof r=="object"&&r!==null&&(r.model&&Array.isArray(r.messages)&&e.setAttribute(eo,r.model),r.stream!==void 0&&e.setAttribute(Bh,r.stream),r.extra_headers&&e.setAttribute(zh,JSON.stringify(r.extra_headers)),r.extra_query&&e.setAttribute(Ih,JSON.stringify(r.extra_query)),r.extra_body&&e.setAttribute(Rh,JSON.stringify(r.extra_body))),e.setAttribute(Ah,JSON.stringify(r))}catch(r){console.debug(`Failed to process inputs for run ${t.id}`,r)}if(t.run.outputs)try{const r=t.run.outputs,s=this.getUnifiedRunTokens(r);if(s&&(e.setAttribute(to,s[0]),e.setAttribute(ro,s[1]),e.setAttribute(no,s[0]+s[1])),r&&typeof r=="object"){if(r.model&&e.setAttribute(_h,String(r.model)),r.id&&e.setAttribute(Ph,r.id),r.choices&&Array.isArray(r.choices)){const a=r.choices.map(i=>i.finish_reason).filter(i=>i).map(String);a.length>0&&e.setAttribute(Sh,a.join(", "))}if(r.service_tier&&e.setAttribute(Ch,r.service_tier),r.system_fingerprint&&e.setAttribute(Nh,r.system_fingerprint),r.usage_metadata&&typeof r.usage_metadata=="object"){const a=r.usage_metadata;a.input_token_details&&e.setAttribute($h,JSON.stringify(a.input_token_details)),a.output_token_details&&e.setAttribute(Lh,JSON.stringify(a.output_token_details))}}e.setAttribute(Oh,JSON.stringify(r))}catch(r){console.debug(`Failed to process outputs for run ${t.id}`,r)}}getUnifiedRunTokens(e){if(!e)return null;let t=this.extractUnifiedRunTokens(e.usage_metadata);if(t)return t;const r=Object.keys(e);for(const i of r){const 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}const s=e.generations||[];if(!Array.isArray(s))return null;const a=Array.isArray(s[0])?s.flat():s;for(const 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 nr={exports:{}},ws={},vs,go;function lf(){if(go)return vs;go=1;function n(e,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return vs=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(r===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1);else return!1;var s=this;return this._timer=setTimeout(function(){s._attempts++,s._operationTimeoutCb&&(s._timeout=setTimeout(function(){s._operationTimeoutCb(s._attempts)},s._operationTimeout),s._options.unref&&s._timeout.unref()),s._fn(s._attempts)},r),this._options.unref&&this._timer.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},n.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,r=0,s=0;s<this._errors.length;s++){var a=this._errors[s],i=a.message,o=(e[i]||0)+1;e[i]=o,o>=r&&(t=a,r=o)}return t},vs}var _o;function df(){return _o||(_o=1,(function(n){var e=lf();n.operation=function(t){var r=n.timeouts(t);return new e(r,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})},n.timeouts=function(t){if(t instanceof Array)return[].concat(t);var r={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var s in t)r[s]=t[s];if(r.minTimeout>r.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var a=[],i=0;i<r.retries;i++)a.push(this.createTimeout(i,r));return t&&t.forever&&!a.length&&a.push(this.createTimeout(i,r)),a.sort(function(o,u){return o-u}),a},n.createTimeout=function(t,r){var s=r.randomize?Math.random()+1:1,a=Math.round(s*Math.max(r.minTimeout,1)*Math.pow(r.factor,t));return a=Math.min(a,r.maxTimeout),a},n.wrap=function(t,r,s){if(r instanceof Array&&(s=r,r=null),!s){s=[];for(var a in t)typeof t[a]=="function"&&s.push(a)}for(var i=0;i<s.length;i++){var o=s[i],u=t[o];t[o]=function(l){var d=n.operation(r),h=Array.prototype.slice.call(arguments,1),f=h.pop();h.push(function(p){d.retry(p)||(p&&(arguments[0]=d.mainError()),f.apply(this,arguments))}),d.attempt(function(){l.apply(t,h)})}.bind(t,u),t[o].options=r}}})(ws)),ws}var Es,yo;function hf(){return yo||(yo=1,Es=df()),Es}var bo;function ff(){if(bo)return nr.exports;bo=1;const n=hf(),e=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class t extends Error{constructor(o){super(),o instanceof Error?(this.originalError=o,{message:o}=o):(this.originalError=new Error(o),this.originalError.stack=this.stack),this.name="AbortError",this.message=o}}const r=(i,o,u)=>{const c=u.retries-(o-1);return i.attemptNumber=o,i.retriesLeft=c,i},s=i=>e.includes(i),a=(i,o)=>new Promise((u,c)=>{o={onFailedAttempt:()=>{},retries:10,...o};const l=n.operation(o);l.attempt(async d=>{try{u(await i(d))}catch(h){if(!(h instanceof Error)){c(new TypeError(`Non-error was thrown: "${h}". You should only throw errors.`));return}if(h instanceof t)l.stop(),c(h.originalError);else if(h instanceof TypeError&&!s(h.message))l.stop(),c(h);else{r(h,d,o);try{await o.onFailedAttempt(h)}catch(f){c(f);return}l.retry(h)||c(l.mainError())}}})});return nr.exports=a,nr.exports.default=a,nr.exports.AbortError=t,nr.exports}var pf=ff(),Hr=tr(pf),Gr={},Ss={exports:{}},wo;function mf(){return wo||(wo=1,(function(n){var e=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function s(u,c,l){this.fn=u,this.context=c,this.once=l||!1}function a(u,c,l,d,h){if(typeof l!="function")throw new TypeError("The listener must be a function");var f=new s(l,d||u,h),p=t?t+c:c;return u._events[p]?u._events[p].fn?u._events[p]=[u._events[p],f]:u._events[p].push(f):(u._events[p]=f,u._eventsCount++),u}function i(u,c){--u._eventsCount===0?u._events=new r:delete u._events[c]}function o(){this._events=new r,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],l,d;if(this._eventsCount===0)return c;for(d in l=this._events)e.call(l,d)&&c.push(t?d.slice(1):d);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(l)):c},o.prototype.listeners=function(c){var l=t?t+c:c,d=this._events[l];if(!d)return[];if(d.fn)return[d.fn];for(var h=0,f=d.length,p=new Array(f);h<f;h++)p[h]=d[h].fn;return p},o.prototype.listenerCount=function(c){var l=t?t+c:c,d=this._events[l];return d?d.fn?1:d.length:0},o.prototype.emit=function(c,l,d,h,f,p){var m=t?t+c:c;if(!this._events[m])return!1;var g=this._events[m],y=arguments.length,_,b;if(g.fn){switch(g.once&&this.removeListener(c,g.fn,void 0,!0),y){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,l),!0;case 3:return g.fn.call(g.context,l,d),!0;case 4:return g.fn.call(g.context,l,d,h),!0;case 5:return g.fn.call(g.context,l,d,h,f),!0;case 6:return g.fn.call(g.context,l,d,h,f,p),!0}for(b=1,_=new Array(y-1);b<y;b++)_[b-1]=arguments[b];g.fn.apply(g.context,_)}else{var E=g.length,v;for(b=0;b<E;b++)switch(g[b].once&&this.removeListener(c,g[b].fn,void 0,!0),y){case 1:g[b].fn.call(g[b].context);break;case 2:g[b].fn.call(g[b].context,l);break;case 3:g[b].fn.call(g[b].context,l,d);break;case 4:g[b].fn.call(g[b].context,l,d,h);break;default:if(!_)for(v=1,_=new Array(y-1);v<y;v++)_[v-1]=arguments[v];g[b].fn.apply(g[b].context,_)}}return!0},o.prototype.on=function(c,l,d){return a(this,c,l,d,!1)},o.prototype.once=function(c,l,d){return a(this,c,l,d,!0)},o.prototype.removeListener=function(c,l,d,h){var f=t?t+c:c;if(!this._events[f])return this;if(!l)return i(this,f),this;var p=this._events[f];if(p.fn)p.fn===l&&(!h||p.once)&&(!d||p.context===d)&&i(this,f);else{for(var m=0,g=[],y=p.length;m<y;m++)(p[m].fn!==l||h&&!p[m].once||d&&p[m].context!==d)&&g.push(p[m]);g.length?this._events[f]=g.length===1?g[0]:g:i(this,f)}return this},o.prototype.removeAllListeners=function(c){var l;return c?(l=t?t+c:c,this._events[l]&&i(this,l)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,n.exports=o})(Ss)),Ss.exports}var sr={exports:{}},As,vo;function gf(){return vo||(vo=1,As=(n,e)=>(e=e||(()=>{}),n.then(t=>new Promise(r=>{r(e())}).then(()=>t),t=>new Promise(r=>{r(e())}).then(()=>{throw t})))),As}var Eo;function _f(){if(Eo)return sr.exports;Eo=1;const n=gf();class e extends Error{constructor(s){super(s),this.name="TimeoutError"}}const t=(r,s,a)=>new Promise((i,o)=>{if(typeof s!="number"||s<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(s===1/0){i(r);return}const u=setTimeout(()=>{if(typeof a=="function"){try{i(a())}catch(d){o(d)}return}const c=typeof a=="string"?a:`Promise timed out after ${s} milliseconds`,l=a instanceof Error?a:new e(c);typeof r.cancel=="function"&&r.cancel(),o(l)},s);n(r.then(i,o),()=>{clearTimeout(u)})});return sr.exports=t,sr.exports.default=t,sr.exports.TimeoutError=e,sr.exports}var Vr={},Zr={},So;function yf(){if(So)return Zr;So=1,Object.defineProperty(Zr,"__esModule",{value:!0});function n(e,t,r){let s=0,a=e.length;for(;a>0;){const i=a/2|0;let o=s+i;r(e[o],t)<=0?(s=++o,a-=i+1):a=i}return s}return Zr.default=n,Zr}var Ao;function bf(){if(Ao)return Vr;Ao=1,Object.defineProperty(Vr,"__esModule",{value:!0});const n=yf();class e{constructor(){this._queue=[]}enqueue(r,s){s=Object.assign({priority:0},s);const a={priority:s.priority,run:r};if(this.size&&this._queue[this.size-1].priority>=s.priority){this._queue.push(a);return}const i=n.default(this._queue,a,(o,u)=>u.priority-o.priority);this._queue.splice(i,0,a)}dequeue(){const r=this._queue.shift();return r?.run}filter(r){return this._queue.filter(s=>s.priority===r.priority).map(s=>s.run)}get size(){return this._queue.length}}return Vr.default=e,Vr}var Oo;function wf(){if(Oo)return Gr;Oo=1,Object.defineProperty(Gr,"__esModule",{value:!0});const n=mf(),e=_f(),t=bf(),r=()=>{},s=new e.TimeoutError;class a extends n{constructor(o){var u,c,l,d;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=r,this._resolveIdle=r,o=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:t.default},o),!(typeof o.intervalCap=="number"&&o.intervalCap>=1))throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${(c=(u=o.intervalCap)===null||u===void 0?void 0:u.toString())!==null&&c!==void 0?c:""}\\` (${typeof o.intervalCap})`);if(o.interval===void 0||!(Number.isFinite(o.interval)&&o.interval>=0))throw new TypeError(`Expected \\`interval\\` to be a finite number >= 0, got \\`${(d=(l=o.interval)===null||l===void 0?void 0:l.toString())!==null&&d!==void 0?d:""}\\` (${typeof o.interval})`);this._carryoverConcurrencyCount=o.carryoverConcurrencyCount,this._isIntervalIgnored=o.intervalCap===1/0||o.interval===0,this._intervalCap=o.intervalCap,this._interval=o.interval,this._queue=new o.queueClass,this._queueClass=o.queueClass,this.concurrency=o.concurrency,this._timeout=o.timeout,this._throwOnTimeout=o.throwOnTimeout===!0,this._isPaused=o.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=r,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=r,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const o=Date.now();if(this._intervalId===void 0){const u=this._intervalEnd-o;if(u<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},u)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const o=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const u=this._queue.dequeue();return u?(this.emit("active"),u(),o&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(o){if(!(typeof o=="number"&&o>=1))throw new TypeError(`Expected \\`concurrency\\` to be a number from 1 and up, got \\`${o}\\` (${typeof o})`);this._concurrency=o,this._processQueue()}async add(o,u={}){return new Promise((c,l)=>{const d=async()=>{this._pendingCount++,this._intervalCount++;try{const h=this._timeout===void 0&&u.timeout===void 0?o():e.default(Promise.resolve(o()),u.timeout===void 0?this._timeout:u.timeout,()=>{(u.throwOnTimeout===void 0?this._throwOnTimeout:u.throwOnTimeout)&&l(s)});c(await h)}catch(h){l(h)}this._next()};this._queue.enqueue(d,u),this._tryToStartAnother(),this.emit("add")})}async addAll(o,u){return Promise.all(o.map(async c=>this.add(c,u)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(o=>{const u=this._resolveEmpty;this._resolveEmpty=()=>{u(),o()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(o=>{const u=this._resolveIdle;this._resolveIdle=()=>{u(),o()}})}get size(){return this._queue.size}sizeBy(o){return this._queue.filter(o).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(o){this._timeout=o}}return Gr.default=a,Gr}var vf=wf(),rt=tr(vf);const Ef=[429,500,502,503,504];let Io=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 rt?this.queue=new rt.default({concurrency:this.maxConcurrency}):this.queue=new rt({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){const r=this.onFailedResponseHook;return this.queue.add(()=>Hr(()=>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;const a=s?.response;if(r&&await r(a))return;const i=a?.status??s?.status;if(i&&!Ef.includes(+i))throw s},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise((s,a)=>{e.signal?.addEventListener("abort",()=>{a(new Error("AbortError"))})})]):this.call(t,...r)}};function Ro(n){return typeof n?._getType=="function"}function To(n){const e={type:n._getType(),data:{content:n.content}};return n?.additional_kwargs&&Object.keys(n.additional_kwargs).length>0&&(e.data.additional_kwargs={...n.additional_kwargs}),e}const Sf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function H(n,e){if(!Sf.test(n)){const t=e!==void 0?`Invalid UUID for ${e}: ${n}`:`Invalid UUID: ${n}`;throw new Error(t)}return n}const xo={};function Os(n){xo[n]||(console.warn(n),xo[n]=!0)}var Wr={exports:{}},Is,ko;function Jr(){if(ko)return Is;ko=1;const n="2.0.0",e=256,t=Number.MAX_SAFE_INTEGER||9007199254740991,r=16,s=e-6;return Is={MAX_LENGTH:e,MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:s,MAX_SAFE_INTEGER:t,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:n,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},Is}var Rs,Po;function Kr(){return Po||(Po=1,Rs=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\\bsemver\\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{}),Rs}var Co;function ar(){return Co||(Co=1,(function(n,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:s}=Jr(),a=Kr();e=n.exports={};const i=e.re=[],o=e.safeRe=[],u=e.src=[],c=e.safeSrc=[],l=e.t={};let d=0;const h="[a-zA-Z0-9-]",f=[["\\\\s",1],["\\\\d",s],[h,r]],p=g=>{for(const[y,_]of f)g=g.split(`${y}*`).join(`${y}{0,${_}}`).split(`${y}+`).join(`${y}{1,${_}}`);return g},m=(g,y,_)=>{const b=p(y),E=d++;a(g,E,y),l[g]=E,u[E]=y,c[E]=b,i[E]=new RegExp(y,_?"g":void 0),o[E]=new RegExp(b,_?"g":void 0)};m("NUMERICIDENTIFIER","0|[1-9]\\\\d*"),m("NUMERICIDENTIFIERLOOSE","\\\\d+"),m("NONNUMERICIDENTIFIER",`\\\\d*[a-zA-Z-]${h}*`),m("MAINVERSION",`(${u[l.NUMERICIDENTIFIER]})\\\\.(${u[l.NUMERICIDENTIFIER]})\\\\.(${u[l.NUMERICIDENTIFIER]})`),m("MAINVERSIONLOOSE",`(${u[l.NUMERICIDENTIFIERLOOSE]})\\\\.(${u[l.NUMERICIDENTIFIERLOOSE]})\\\\.(${u[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASEIDENTIFIER",`(?:${u[l.NONNUMERICIDENTIFIER]}|${u[l.NUMERICIDENTIFIER]})`),m("PRERELEASEIDENTIFIERLOOSE",`(?:${u[l.NONNUMERICIDENTIFIER]}|${u[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASE",`(?:-(${u[l.PRERELEASEIDENTIFIER]}(?:\\\\.${u[l.PRERELEASEIDENTIFIER]})*))`),m("PRERELEASELOOSE",`(?:-?(${u[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\\\.${u[l.PRERELEASEIDENTIFIERLOOSE]})*))`),m("BUILDIDENTIFIER",`${h}+`),m("BUILD",`(?:\\\\+(${u[l.BUILDIDENTIFIER]}(?:\\\\.${u[l.BUILDIDENTIFIER]})*))`),m("FULLPLAIN",`v?${u[l.MAINVERSION]}${u[l.PRERELEASE]}?${u[l.BUILD]}?`),m("FULL",`^${u[l.FULLPLAIN]}$`),m("LOOSEPLAIN",`[v=\\\\s]*${u[l.MAINVERSIONLOOSE]}${u[l.PRERELEASELOOSE]}?${u[l.BUILD]}?`),m("LOOSE",`^${u[l.LOOSEPLAIN]}$`),m("GTLT","((?:<|>)?=?)"),m("XRANGEIDENTIFIERLOOSE",`${u[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`),m("XRANGEIDENTIFIER",`${u[l.NUMERICIDENTIFIER]}|x|X|\\\\*`),m("XRANGEPLAIN",`[v=\\\\s]*(${u[l.XRANGEIDENTIFIER]})(?:\\\\.(${u[l.XRANGEIDENTIFIER]})(?:\\\\.(${u[l.XRANGEIDENTIFIER]})(?:${u[l.PRERELEASE]})?${u[l.BUILD]}?)?)?`),m("XRANGEPLAINLOOSE",`[v=\\\\s]*(${u[l.XRANGEIDENTIFIERLOOSE]})(?:\\\\.(${u[l.XRANGEIDENTIFIERLOOSE]})(?:\\\\.(${u[l.XRANGEIDENTIFIERLOOSE]})(?:${u[l.PRERELEASELOOSE]})?${u[l.BUILD]}?)?)?`),m("XRANGE",`^${u[l.GTLT]}\\\\s*${u[l.XRANGEPLAIN]}$`),m("XRANGELOOSE",`^${u[l.GTLT]}\\\\s*${u[l.XRANGEPLAINLOOSE]}$`),m("COERCEPLAIN",`(^|[^\\\\d])(\\\\d{1,${t}})(?:\\\\.(\\\\d{1,${t}}))?(?:\\\\.(\\\\d{1,${t}}))?`),m("COERCE",`${u[l.COERCEPLAIN]}(?:$|[^\\\\d])`),m("COERCEFULL",u[l.COERCEPLAIN]+`(?:${u[l.PRERELEASE]})?(?:${u[l.BUILD]})?(?:$|[^\\\\d])`),m("COERCERTL",u[l.COERCE],!0),m("COERCERTLFULL",u[l.COERCEFULL],!0),m("LONETILDE","(?:~>?)"),m("TILDETRIM",`(\\\\s*)${u[l.LONETILDE]}\\\\s+`,!0),e.tildeTrimReplace="$1~",m("TILDE",`^${u[l.LONETILDE]}${u[l.XRANGEPLAIN]}$`),m("TILDELOOSE",`^${u[l.LONETILDE]}${u[l.XRANGEPLAINLOOSE]}$`),m("LONECARET","(?:\\\\^)"),m("CARETTRIM",`(\\\\s*)${u[l.LONECARET]}\\\\s+`,!0),e.caretTrimReplace="$1^",m("CARET",`^${u[l.LONECARET]}${u[l.XRANGEPLAIN]}$`),m("CARETLOOSE",`^${u[l.LONECARET]}${u[l.XRANGEPLAINLOOSE]}$`),m("COMPARATORLOOSE",`^${u[l.GTLT]}\\\\s*(${u[l.LOOSEPLAIN]})$|^$`),m("COMPARATOR",`^${u[l.GTLT]}\\\\s*(${u[l.FULLPLAIN]})$|^$`),m("COMPARATORTRIM",`(\\\\s*)${u[l.GTLT]}\\\\s*(${u[l.LOOSEPLAIN]}|${u[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",m("HYPHENRANGE",`^\\\\s*(${u[l.XRANGEPLAIN]})\\\\s+-\\\\s+(${u[l.XRANGEPLAIN]})\\\\s*$`),m("HYPHENRANGELOOSE",`^\\\\s*(${u[l.XRANGEPLAINLOOSE]})\\\\s+-\\\\s+(${u[l.XRANGEPLAINLOOSE]})\\\\s*$`),m("STAR","(<|>)?=?\\\\s*\\\\*"),m("GTE0","^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$"),m("GTE0PRE","^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$")})(Wr,Wr.exports)),Wr.exports}var Ts,No;function xs(){if(No)return Ts;No=1;const n=Object.freeze({loose:!0}),e=Object.freeze({});return Ts=r=>r?typeof r!="object"?n:r:e,Ts}var ks,$o;function Lo(){if($o)return ks;$o=1;const n=/^[0-9]+$/,e=(r,s)=>{if(typeof r=="number"&&typeof s=="number")return r===s?0:r<s?-1:1;const a=n.test(r),i=n.test(s);return a&&i&&(r=+r,s=+s),r===s?0:a&&!i?-1:i&&!a?1:r<s?-1:1};return ks={compareIdentifiers:e,rcompareIdentifiers:(r,s)=>e(s,r)},ks}var Ps,jo;function ve(){if(jo)return Ps;jo=1;const n=Kr(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:t}=Jr(),{safeRe:r,t:s}=ar(),a=xs(),{compareIdentifiers:i}=Lo();class o{constructor(c,l){if(l=a(l),c instanceof o){if(c.loose===!!l.loose&&c.includePrerelease===!!l.includePrerelease)return c;c=c.version}else if(typeof c!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof c}".`);if(c.length>e)throw new TypeError(`version is longer than ${e} characters`);n("SemVer",c,l),this.options=l,this.loose=!!l.loose,this.includePrerelease=!!l.includePrerelease;const d=c.trim().match(l.loose?r[s.LOOSE]:r[s.FULL]);if(!d)throw new TypeError(`Invalid Version: ${c}`);if(this.raw=c,this.major=+d[1],this.minor=+d[2],this.patch=+d[3],this.major>t||this.major<0)throw new TypeError("Invalid major version");if(this.minor>t||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>t||this.patch<0)throw new TypeError("Invalid patch version");d[4]?this.prerelease=d[4].split(".").map(h=>{if(/^[0-9]+$/.test(h)){const f=+h;if(f>=0&&f<t)return f}return h}):this.prerelease=[],this.build=d[5]?d[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(c){if(n("SemVer.compare",this.version,this.options,c),!(c instanceof o)){if(typeof c=="string"&&c===this.version)return 0;c=new o(c,this.options)}return c.version===this.version?0:this.compareMain(c)||this.comparePre(c)}compareMain(c){return c instanceof o||(c=new o(c,this.options)),this.major<c.major?-1:this.major>c.major?1:this.minor<c.minor?-1:this.minor>c.minor?1:this.patch<c.patch?-1:this.patch>c.patch?1:0}comparePre(c){if(c instanceof o||(c=new o(c,this.options)),this.prerelease.length&&!c.prerelease.length)return-1;if(!this.prerelease.length&&c.prerelease.length)return 1;if(!this.prerelease.length&&!c.prerelease.length)return 0;let l=0;do{const d=this.prerelease[l],h=c.prerelease[l];if(n("prerelease compare",l,d,h),d===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(d===void 0)return-1;if(d===h)continue;return i(d,h)}while(++l)}compareBuild(c){c instanceof o||(c=new o(c,this.options));let l=0;do{const d=this.build[l],h=c.build[l];if(n("build compare",l,d,h),d===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(d===void 0)return-1;if(d===h)continue;return i(d,h)}while(++l)}inc(c,l,d){if(c.startsWith("pre")){if(!l&&d===!1)throw new Error("invalid increment argument: identifier is empty");if(l){const h=`-${l}`.match(this.options.loose?r[s.PRERELEASELOOSE]:r[s.PRERELEASE]);if(!h||h[1]!==l)throw new Error(`invalid identifier: ${l}`)}}switch(c){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",l,d);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",l,d);break;case"prepatch":this.prerelease.length=0,this.inc("patch",l,d),this.inc("pre",l,d);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",l,d),this.inc("pre",l,d);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const h=Number(d)?1:0;if(this.prerelease.length===0)this.prerelease=[h];else{let f=this.prerelease.length;for(;--f>=0;)typeof this.prerelease[f]=="number"&&(this.prerelease[f]++,f=-2);if(f===-1){if(l===this.prerelease.join(".")&&d===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(h)}}if(l){let f=[l,h];d===!1&&(f=[l]),i(this.prerelease[0],l)===0?isNaN(this.prerelease[1])&&(this.prerelease=f):this.prerelease=f}break}default:throw new Error(`invalid increment argument: ${c}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return Ps=o,Ps}var Cs,Mo;function Lt(){if(Mo)return Cs;Mo=1;const n=ve();return Cs=(t,r,s=!1)=>{if(t instanceof n)return t;try{return new n(t,r)}catch(a){if(!s)return null;throw a}},Cs}var Ns,Do;function Af(){if(Do)return Ns;Do=1;const n=Lt();return Ns=(t,r)=>{const s=n(t,r);return s?s.version:null},Ns}var $s,Uo;function Of(){if(Uo)return $s;Uo=1;const n=Lt();return $s=(t,r)=>{const s=n(t.trim().replace(/^[=v]+/,""),r);return s?s.version:null},$s}var Ls,Fo;function If(){if(Fo)return Ls;Fo=1;const n=ve();return Ls=(t,r,s,a,i)=>{typeof s=="string"&&(i=a,a=s,s=void 0);try{return new n(t instanceof n?t.version:t,s).inc(r,a,i).version}catch{return null}},Ls}var js,Bo;function Rf(){if(Bo)return js;Bo=1;const n=Lt();return js=(t,r)=>{const s=n(t,null,!0),a=n(r,null,!0),i=s.compare(a);if(i===0)return null;const o=i>0,u=o?s:a,c=o?a:s,l=!!u.prerelease.length;if(!!c.prerelease.length&&!l){if(!c.patch&&!c.minor)return"major";if(c.compareMain(u)===0)return c.minor&&!c.patch?"minor":"patch"}const h=l?"pre":"";return s.major!==a.major?h+"major":s.minor!==a.minor?h+"minor":s.patch!==a.patch?h+"patch":"prerelease"},js}var Ms,zo;function Tf(){if(zo)return Ms;zo=1;const n=ve();return Ms=(t,r)=>new n(t,r).major,Ms}var Ds,qo;function xf(){if(qo)return Ds;qo=1;const n=ve();return Ds=(t,r)=>new n(t,r).minor,Ds}var Us,Ho;function kf(){if(Ho)return Us;Ho=1;const n=ve();return Us=(t,r)=>new n(t,r).patch,Us}var Fs,Go;function Pf(){if(Go)return Fs;Go=1;const n=Lt();return Fs=(t,r)=>{const s=n(t,r);return s&&s.prerelease.length?s.prerelease:null},Fs}var Bs,Vo;function qe(){if(Vo)return Bs;Vo=1;const n=ve();return Bs=(t,r,s)=>new n(t,s).compare(new n(r,s)),Bs}var zs,Zo;function Cf(){if(Zo)return zs;Zo=1;const n=qe();return zs=(t,r,s)=>n(r,t,s),zs}var qs,Wo;function Nf(){if(Wo)return qs;Wo=1;const n=qe();return qs=(t,r)=>n(t,r,!0),qs}var Hs,Jo;function Gs(){if(Jo)return Hs;Jo=1;const n=ve();return Hs=(t,r,s)=>{const a=new n(t,s),i=new n(r,s);return a.compare(i)||a.compareBuild(i)},Hs}var Vs,Ko;function $f(){if(Ko)return Vs;Ko=1;const n=Gs();return Vs=(t,r)=>t.sort((s,a)=>n(s,a,r)),Vs}var Zs,Xo;function Lf(){if(Xo)return Zs;Xo=1;const n=Gs();return Zs=(t,r)=>t.sort((s,a)=>n(a,s,r)),Zs}var Ws,Qo;function Xr(){if(Qo)return Ws;Qo=1;const n=qe();return Ws=(t,r,s)=>n(t,r,s)>0,Ws}var Js,Yo;function Ks(){if(Yo)return Js;Yo=1;const n=qe();return Js=(t,r,s)=>n(t,r,s)<0,Js}var Xs,eu;function tu(){if(eu)return Xs;eu=1;const n=qe();return Xs=(t,r,s)=>n(t,r,s)===0,Xs}var Qs,ru;function nu(){if(ru)return Qs;ru=1;const n=qe();return Qs=(t,r,s)=>n(t,r,s)!==0,Qs}var Ys,su;function ea(){if(su)return Ys;su=1;const n=qe();return Ys=(t,r,s)=>n(t,r,s)>=0,Ys}var ta,au;function ra(){if(au)return ta;au=1;const n=qe();return ta=(t,r,s)=>n(t,r,s)<=0,ta}var na,iu;function ou(){if(iu)return na;iu=1;const n=tu(),e=nu(),t=Xr(),r=ea(),s=Ks(),a=ra();return na=(o,u,c,l)=>{switch(u){case"===":return typeof o=="object"&&(o=o.version),typeof c=="object"&&(c=c.version),o===c;case"!==":return typeof o=="object"&&(o=o.version),typeof c=="object"&&(c=c.version),o!==c;case"":case"=":case"==":return n(o,c,l);case"!=":return e(o,c,l);case">":return t(o,c,l);case">=":return r(o,c,l);case"<":return s(o,c,l);case"<=":return a(o,c,l);default:throw new TypeError(`Invalid operator: ${u}`)}},na}var sa,uu;function jf(){if(uu)return sa;uu=1;const n=ve(),e=Lt(),{safeRe:t,t:r}=ar();return sa=(a,i)=>{if(a instanceof n)return a;if(typeof a=="number"&&(a=String(a)),typeof a!="string")return null;i=i||{};let o=null;if(!i.rtl)o=a.match(i.includePrerelease?t[r.COERCEFULL]:t[r.COERCE]);else{const f=i.includePrerelease?t[r.COERCERTLFULL]:t[r.COERCERTL];let p;for(;(p=f.exec(a))&&(!o||o.index+o[0].length!==a.length);)(!o||p.index+p[0].length!==o.index+o[0].length)&&(o=p),f.lastIndex=p.index+p[1].length+p[2].length;f.lastIndex=-1}if(o===null)return null;const u=o[2],c=o[3]||"0",l=o[4]||"0",d=i.includePrerelease&&o[5]?`-${o[5]}`:"",h=i.includePrerelease&&o[6]?`+${o[6]}`:"";return e(`${u}.${c}.${l}${d}${h}`,i)},sa}var aa,cu;function Mf(){if(cu)return aa;cu=1;class n{constructor(){this.max=1e3,this.map=new Map}get(t){const r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){const a=this.map.keys().next().value;this.delete(a)}this.map.set(t,r)}return this}}return aa=n,aa}var ia,lu;function He(){if(lu)return ia;lu=1;const n=/\\s+/g;class e{constructor(I,U){if(U=s(U),I instanceof e)return I.loose===!!U.loose&&I.includePrerelease===!!U.includePrerelease?I:new e(I.raw,U);if(I instanceof a)return this.raw=I.value,this.set=[[I]],this.formatted=void 0,this;if(this.options=U,this.loose=!!U.loose,this.includePrerelease=!!U.includePrerelease,this.raw=I.trim().replace(n," "),this.set=this.raw.split("||").map(M=>this.parseRange(M.trim())).filter(M=>M.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const M=this.set[0];if(this.set=this.set.filter(F=>!m(F[0])),this.set.length===0)this.set=[M];else if(this.set.length>1){for(const F of this.set)if(F.length===1&&g(F[0])){this.set=[F];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let I=0;I<this.set.length;I++){I>0&&(this.formatted+="||");const U=this.set[I];for(let M=0;M<U.length;M++)M>0&&(this.formatted+=" "),this.formatted+=U[M].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(I){const M=((this.options.includePrerelease&&f)|(this.options.loose&&p))+":"+I,F=r.get(M);if(F)return F;const D=this.options.loose,G=D?u[c.HYPHENRANGELOOSE]:u[c.HYPHENRANGE];I=I.replace(G,Je(this.options.includePrerelease)),i("hyphen replace",I),I=I.replace(u[c.COMPARATORTRIM],l),i("comparator trim",I),I=I.replace(u[c.TILDETRIM],d),i("tilde trim",I),I=I.replace(u[c.CARETTRIM],h),i("caret trim",I);let te=I.split(" ").map(ue=>_(ue,this.options)).join(" ").split(/\\s+/).map(ue=>ne(ue,this.options));D&&(te=te.filter(ue=>(i("loose invalid filter",ue,this.options),!!ue.match(u[c.COMPARATORLOOSE])))),i("range list",te);const W=new Map,se=te.map(ue=>new a(ue,this.options));for(const ue of se){if(m(ue))return[ue];W.set(ue.value,ue)}W.size>1&&W.has("")&&W.delete("");const Ie=[...W.values()];return r.set(M,Ie),Ie}intersects(I,U){if(!(I instanceof e))throw new TypeError("a Range is required");return this.set.some(M=>y(M,U)&&I.set.some(F=>y(F,U)&&M.every(D=>F.every(G=>D.intersects(G,U)))))}test(I){if(!I)return!1;if(typeof I=="string")try{I=new o(I,this.options)}catch{return!1}for(let U=0;U<this.set.length;U++)if($t(this.set[U],I,this.options))return!0;return!1}}ia=e;const t=Mf(),r=new t,s=xs(),a=Qr(),i=Kr(),o=ve(),{safeRe:u,t:c,comparatorTrimReplace:l,tildeTrimReplace:d,caretTrimReplace:h}=ar(),{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:p}=Jr(),m=k=>k.value==="<0.0.0-0",g=k=>k.value==="",y=(k,I)=>{let U=!0;const M=k.slice();let F=M.pop();for(;U&&M.length;)U=M.every(D=>F.intersects(D,I)),F=M.pop();return U},_=(k,I)=>(k=k.replace(u[c.BUILD],""),i("comp",k,I),k=x(k,I),i("caret",k),k=E(k,I),i("tildes",k),k=O(k,I),i("xrange",k),k=K(k,I),i("stars",k),k),b=k=>!k||k.toLowerCase()==="x"||k==="*",E=(k,I)=>k.trim().split(/\\s+/).map(U=>v(U,I)).join(" "),v=(k,I)=>{const U=I.loose?u[c.TILDELOOSE]:u[c.TILDE];return k.replace(U,(M,F,D,G,te)=>{i("tilde",k,M,F,D,G,te);let W;return b(F)?W="":b(D)?W=`>=${F}.0.0 <${+F+1}.0.0-0`:b(G)?W=`>=${F}.${D}.0 <${F}.${+D+1}.0-0`:te?(i("replaceTilde pr",te),W=`>=${F}.${D}.${G}-${te} <${F}.${+D+1}.0-0`):W=`>=${F}.${D}.${G} <${F}.${+D+1}.0-0`,i("tilde return",W),W})},x=(k,I)=>k.trim().split(/\\s+/).map(U=>P(U,I)).join(" "),P=(k,I)=>{i("caret",k,I);const U=I.loose?u[c.CARETLOOSE]:u[c.CARET],M=I.includePrerelease?"-0":"";return k.replace(U,(F,D,G,te,W)=>{i("caret",k,F,D,G,te,W);let se;return b(D)?se="":b(G)?se=`>=${D}.0.0${M} <${+D+1}.0.0-0`:b(te)?D==="0"?se=`>=${D}.${G}.0${M} <${D}.${+G+1}.0-0`:se=`>=${D}.${G}.0${M} <${+D+1}.0.0-0`:W?(i("replaceCaret pr",W),D==="0"?G==="0"?se=`>=${D}.${G}.${te}-${W} <${D}.${G}.${+te+1}-0`:se=`>=${D}.${G}.${te}-${W} <${D}.${+G+1}.0-0`:se=`>=${D}.${G}.${te}-${W} <${+D+1}.0.0-0`):(i("no pr"),D==="0"?G==="0"?se=`>=${D}.${G}.${te}${M} <${D}.${G}.${+te+1}-0`:se=`>=${D}.${G}.${te}${M} <${D}.${+G+1}.0-0`:se=`>=${D}.${G}.${te} <${+D+1}.0.0-0`),i("caret return",se),se})},O=(k,I)=>(i("replaceXRanges",k,I),k.split(/\\s+/).map(U=>J(U,I)).join(" ")),J=(k,I)=>{k=k.trim();const U=I.loose?u[c.XRANGELOOSE]:u[c.XRANGE];return k.replace(U,(M,F,D,G,te,W)=>{i("xRange",k,M,F,D,G,te,W);const se=b(D),Ie=se||b(G),ue=Ie||b(te),Fr=ue;return F==="="&&Fr&&(F=""),W=I.includePrerelease?"-0":"",se?F===">"||F==="<"?M="<0.0.0-0":M="*":F&&Fr?(Ie&&(G=0),te=0,F===">"?(F=">=",Ie?(D=+D+1,G=0,te=0):(G=+G+1,te=0)):F==="<="&&(F="<",Ie?D=+D+1:G=+G+1),F==="<"&&(W="-0"),M=`${F+D}.${G}.${te}${W}`):Ie?M=`>=${D}.0.0${W} <${+D+1}.0.0-0`:ue&&(M=`>=${D}.${G}.0${W} <${D}.${+G+1}.0-0`),i("xRange return",M),M})},K=(k,I)=>(i("replaceStars",k,I),k.trim().replace(u[c.STAR],"")),ne=(k,I)=>(i("replaceGTE0",k,I),k.trim().replace(u[I.includePrerelease?c.GTE0PRE:c.GTE0],"")),Je=k=>(I,U,M,F,D,G,te,W,se,Ie,ue,Fr)=>(b(M)?U="":b(F)?U=`>=${M}.0.0${k?"-0":""}`:b(D)?U=`>=${M}.${F}.0${k?"-0":""}`:G?U=`>=${U}`:U=`>=${U}${k?"-0":""}`,b(se)?W="":b(Ie)?W=`<${+se+1}.0.0-0`:b(ue)?W=`<${se}.${+Ie+1}.0-0`:Fr?W=`<=${se}.${Ie}.${ue}-${Fr}`:k?W=`<${se}.${Ie}.${+ue+1}-0`:W=`<=${W}`,`${U} ${W}`.trim()),$t=(k,I,U)=>{for(let M=0;M<k.length;M++)if(!k[M].test(I))return!1;if(I.prerelease.length&&!U.includePrerelease){for(let M=0;M<k.length;M++)if(i(k[M].semver),k[M].semver!==a.ANY&&k[M].semver.prerelease.length>0){const F=k[M].semver;if(F.major===I.major&&F.minor===I.minor&&F.patch===I.patch)return!0}return!1}return!0};return ia}var oa,du;function Qr(){if(du)return oa;du=1;const n=Symbol("SemVer ANY");class e{static get ANY(){return n}constructor(l,d){if(d=t(d),l instanceof e){if(l.loose===!!d.loose)return l;l=l.value}l=l.trim().split(/\\s+/).join(" "),i("comparator",l,d),this.options=d,this.loose=!!d.loose,this.parse(l),this.semver===n?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(l){const d=this.options.loose?r[s.COMPARATORLOOSE]:r[s.COMPARATOR],h=l.match(d);if(!h)throw new TypeError(`Invalid comparator: ${l}`);this.operator=h[1]!==void 0?h[1]:"",this.operator==="="&&(this.operator=""),h[2]?this.semver=new o(h[2],this.options.loose):this.semver=n}toString(){return this.value}test(l){if(i("Comparator.test",l,this.options.loose),this.semver===n||l===n)return!0;if(typeof l=="string")try{l=new o(l,this.options)}catch{return!1}return a(l,this.operator,this.semver,this.options)}intersects(l,d){if(!(l instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new u(l.value,d).test(this.value):l.operator===""?l.value===""?!0:new u(this.value,d).test(l.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||l.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||l.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&l.operator.startsWith(">")||this.operator.startsWith("<")&&l.operator.startsWith("<")||this.semver.version===l.semver.version&&this.operator.includes("=")&&l.operator.includes("=")||a(this.semver,"<",l.semver,d)&&this.operator.startsWith(">")&&l.operator.startsWith("<")||a(this.semver,">",l.semver,d)&&this.operator.startsWith("<")&&l.operator.startsWith(">")))}}oa=e;const t=xs(),{safeRe:r,t:s}=ar(),a=ou(),i=Kr(),o=ve(),u=He();return oa}var ua,hu;function Yr(){if(hu)return ua;hu=1;const n=He();return ua=(t,r,s)=>{try{r=new n(r,s)}catch{return!1}return r.test(t)},ua}var ca,fu;function Df(){if(fu)return ca;fu=1;const n=He();return ca=(t,r)=>new n(t,r).set.map(s=>s.map(a=>a.value).join(" ").trim().split(" ")),ca}var la,pu;function Uf(){if(pu)return la;pu=1;const n=ve(),e=He();return la=(r,s,a)=>{let i=null,o=null,u=null;try{u=new e(s,a)}catch{return null}return r.forEach(c=>{u.test(c)&&(!i||o.compare(c)===-1)&&(i=c,o=new n(i,a))}),i},la}var da,mu;function Ff(){if(mu)return da;mu=1;const n=ve(),e=He();return da=(r,s,a)=>{let i=null,o=null,u=null;try{u=new e(s,a)}catch{return null}return r.forEach(c=>{u.test(c)&&(!i||o.compare(c)===1)&&(i=c,o=new n(i,a))}),i},da}var ha,gu;function Bf(){if(gu)return ha;gu=1;const n=ve(),e=He(),t=Xr();return ha=(s,a)=>{s=new e(s,a);let i=new n("0.0.0");if(s.test(i)||(i=new n("0.0.0-0"),s.test(i)))return i;i=null;for(let o=0;o<s.set.length;++o){const u=s.set[o];let c=null;u.forEach(l=>{const d=new n(l.semver.version);switch(l.operator){case">":d.prerelease.length===0?d.patch++:d.prerelease.push(0),d.raw=d.format();case"":case">=":(!c||t(d,c))&&(c=d);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${l.operator}`)}}),c&&(!i||t(i,c))&&(i=c)}return i&&s.test(i)?i:null},ha}var fa,_u;function zf(){if(_u)return fa;_u=1;const n=He();return fa=(t,r)=>{try{return new n(t,r).range||"*"}catch{return null}},fa}var pa,yu;function ma(){if(yu)return pa;yu=1;const n=ve(),e=Qr(),{ANY:t}=e,r=He(),s=Yr(),a=Xr(),i=Ks(),o=ra(),u=ea();return pa=(l,d,h,f)=>{l=new n(l,f),d=new r(d,f);let p,m,g,y,_;switch(h){case">":p=a,m=o,g=i,y=">",_=">=";break;case"<":p=i,m=u,g=a,y="<",_="<=";break;default:throw new TypeError(\'Must provide a hilo val of "<" or ">"\')}if(s(l,d,f))return!1;for(let b=0;b<d.set.length;++b){const E=d.set[b];let v=null,x=null;if(E.forEach(P=>{P.semver===t&&(P=new e(">=0.0.0")),v=v||P,x=x||P,p(P.semver,v.semver,f)?v=P:g(P.semver,x.semver,f)&&(x=P)}),v.operator===y||v.operator===_||(!x.operator||x.operator===y)&&m(l,x.semver))return!1;if(x.operator===_&&g(l,x.semver))return!1}return!0},pa}var ga,bu;function qf(){if(bu)return ga;bu=1;const n=ma();return ga=(t,r,s)=>n(t,r,">",s),ga}var _a,wu;function Hf(){if(wu)return _a;wu=1;const n=ma();return _a=(t,r,s)=>n(t,r,"<",s),_a}var ya,vu;function Gf(){if(vu)return ya;vu=1;const n=He();return ya=(t,r,s)=>(t=new n(t,s),r=new n(r,s),t.intersects(r,s)),ya}var ba,Eu;function Vf(){if(Eu)return ba;Eu=1;const n=Yr(),e=qe();return ba=(t,r,s)=>{const a=[];let i=null,o=null;const u=t.sort((h,f)=>e(h,f,s));for(const h of u)n(h,r,s)?(o=h,i||(i=h)):(o&&a.push([i,o]),o=null,i=null);i&&a.push([i,null]);const c=[];for(const[h,f]of a)h===f?c.push(h):!f&&h===u[0]?c.push("*"):f?h===u[0]?c.push(`<=${f}`):c.push(`${h} - ${f}`):c.push(`>=${h}`);const l=c.join(" || "),d=typeof r.raw=="string"?r.raw:String(r);return l.length<d.length?l:r},ba}var wa,Su;function Zf(){if(Su)return wa;Su=1;const n=He(),e=Qr(),{ANY:t}=e,r=Yr(),s=qe(),a=(d,h,f={})=>{if(d===h)return!0;d=new n(d,f),h=new n(h,f);let p=!1;e:for(const m of d.set){for(const g of h.set){const y=u(m,g,f);if(p=p||y!==null,y)continue e}if(p)return!1}return!0},i=[new e(">=0.0.0-0")],o=[new e(">=0.0.0")],u=(d,h,f)=>{if(d===h)return!0;if(d.length===1&&d[0].semver===t){if(h.length===1&&h[0].semver===t)return!0;f.includePrerelease?d=i:d=o}if(h.length===1&&h[0].semver===t){if(f.includePrerelease)return!0;h=o}const p=new Set;let m,g;for(const O of d)O.operator===">"||O.operator===">="?m=c(m,O,f):O.operator==="<"||O.operator==="<="?g=l(g,O,f):p.add(O.semver);if(p.size>1)return null;let y;if(m&&g){if(y=s(m.semver,g.semver,f),y>0)return null;if(y===0&&(m.operator!==">="||g.operator!=="<="))return null}for(const O of p){if(m&&!r(O,String(m),f)||g&&!r(O,String(g),f))return null;for(const J of h)if(!r(O,String(J),f))return!1;return!0}let _,b,E,v,x=g&&!f.includePrerelease&&g.semver.prerelease.length?g.semver:!1,P=m&&!f.includePrerelease&&m.semver.prerelease.length?m.semver:!1;x&&x.prerelease.length===1&&g.operator==="<"&&x.prerelease[0]===0&&(x=!1);for(const O of h){if(v=v||O.operator===">"||O.operator===">=",E=E||O.operator==="<"||O.operator==="<=",m){if(P&&O.semver.prerelease&&O.semver.prerelease.length&&O.semver.major===P.major&&O.semver.minor===P.minor&&O.semver.patch===P.patch&&(P=!1),O.operator===">"||O.operator===">="){if(_=c(m,O,f),_===O&&_!==m)return!1}else if(m.operator===">="&&!r(m.semver,String(O),f))return!1}if(g){if(x&&O.semver.prerelease&&O.semver.prerelease.length&&O.semver.major===x.major&&O.semver.minor===x.minor&&O.semver.patch===x.patch&&(x=!1),O.operator==="<"||O.operator==="<="){if(b=l(g,O,f),b===O&&b!==g)return!1}else if(g.operator==="<="&&!r(g.semver,String(O),f))return!1}if(!O.operator&&(g||m)&&y!==0)return!1}return!(m&&E&&!g&&y!==0||g&&v&&!m&&y!==0||P||x)},c=(d,h,f)=>{if(!d)return h;const p=s(d.semver,h.semver,f);return p>0?d:p<0||h.operator===">"&&d.operator===">="?h:d},l=(d,h,f)=>{if(!d)return h;const p=s(d.semver,h.semver,f);return p<0?d:p>0||h.operator==="<"&&d.operator==="<="?h:d};return wa=a,wa}var va,Au;function Wf(){if(Au)return va;Au=1;const n=ar(),e=Jr(),t=ve(),r=Lo(),s=Lt(),a=Af(),i=Of(),o=If(),u=Rf(),c=Tf(),l=xf(),d=kf(),h=Pf(),f=qe(),p=Cf(),m=Nf(),g=Gs(),y=$f(),_=Lf(),b=Xr(),E=Ks(),v=tu(),x=nu(),P=ea(),O=ra(),J=ou(),K=jf(),ne=Qr(),Je=He(),$t=Yr(),k=Df(),I=Uf(),U=Ff(),M=Bf(),F=zf(),D=ma(),G=qf(),te=Hf(),W=Gf(),se=Vf(),Ie=Zf();return va={parse:s,valid:a,clean:i,inc:o,diff:u,major:c,minor:l,patch:d,prerelease:h,compare:f,rcompare:p,compareLoose:m,compareBuild:g,sort:y,rsort:_,gt:b,lt:E,eq:v,neq:x,gte:P,lte:O,cmp:J,coerce:K,Comparator:ne,Range:Je,satisfies:$t,toComparators:k,maxSatisfying:I,minSatisfying:U,minVersion:M,validRange:F,outside:D,gtr:G,ltr:te,intersects:W,simplifyRange:se,subset:Ie,SemVer:t,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:e.SEMVER_SPEC_VERSION,RELEASE_TYPES:e.RELEASE_TYPES,compareIdentifiers:r.compareIdentifiers,rcompareIdentifiers:r.rcompareIdentifiers},va}Wf();function ut(n){if(!n||n.split("/").length>2||n.startsWith("/")||n.endsWith("/")||n.split(":").length>2)throw new Error(`Invalid identifier format: ${n}`);const[e,t]=n.split(":"),r=t||"latest";if(e.includes("/")){const[s,a]=e.split("/",2);if(!s||!a)throw new Error(`Invalid identifier format: ${n}`);return[s,a,r]}else{if(!e)throw new Error(`Invalid identifier format: ${n}`);return["-",e,r]}}class Jf extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}async function $(n,e,t){let r;if(n.ok){t&&(r=await n.text());return}if(n.status===403)try{(await n.json())?.error==="org_scoped_key_requires_workspace"&&(r="This API key is org-scoped and requires workspace specification. Please provide \'workspaceId\' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{const o=new Error(`${n.status} ${n.statusText}`);throw o.status=n?.status,o}if(r===void 0)try{r=await n.text()}catch{r=""}const s=`Failed to ${e}. Received status [${n.status}]: ${n.statusText}. Message: ${r}`;if(n.status===409)throw new Jf(s);const a=new Error(s);throw a.status=n.status,a}const Ou="ERR_CONFLICTING_ENDPOINTS";class Kf 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:Ou}),this.name="ConflictingEndpointsError"}}function Xf(n){return typeof n=="object"&&n!==null&&n.code===Ou}var Iu="[...]",Qf={result:"[Circular]"},en=[],jt=[];const Yf=new TextEncoder;function ep(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function tn(n){return Yf.encode(n)}function Ru(n){if(n&&typeof n=="object"&&n!==null){if(n instanceof Map)return Object.fromEntries(n);if(n instanceof Set)return Array.from(n);if(n instanceof Date)return n.toISOString();if(n instanceof RegExp)return n.toString();if(n instanceof Error)return{name:n.name,message:n.message}}else if(typeof n=="bigint")return n.toString();return n}function tp(n){return function(e,t){return Ru(t)}}function Ce(n,e,t,r,s){try{const a=JSON.stringify(n,tp(t),r);return tn(a)}catch(a){if(!a.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`\nContext: ${e}`:""}`),tn("[Unserializable]");Te("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`\nContext: ${e}`:""}`),typeof s>"u"&&(s=ep()),Sa(n,"",0,[],void 0,0,s);let i;try{jt.length===0?i=JSON.stringify(n,t,r):i=JSON.stringify(n,rp(t),r)}catch{return tn("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;en.length!==0;){const o=en.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return tn(i)}}function Ea(n,e,t,r){var s=Object.getOwnPropertyDescriptor(r,t);s.get!==void 0?s.configurable?(Object.defineProperty(r,t,{value:n}),en.push([r,t,e,s])):jt.push([e,t,n]):(r[t]=n,en.push([r,t,e]))}function Sa(n,e,t,r,s,a,i){a+=1;var o;if(typeof n=="object"&&n!==null){for(o=0;o<r.length;o++)if(r[o]===n){Ea(Qf,n,e,s);return}if(typeof i.depthLimit<"u"&&a>i.depthLimit){Ea(Iu,n,e,s);return}if(typeof i.edgesLimit<"u"&&t+1>i.edgesLimit){Ea(Iu,n,e,s);return}if(r.push(n),Array.isArray(n))for(o=0;o<n.length;o++)Sa(n[o],o,o,r,n,a,i);else{n=Ru(n);var u=Object.keys(n);for(o=0;o<u.length;o++){var c=u[o];Sa(n[c],c,o,r,n,a,i)}}r.pop()}}function rp(n){return n=typeof n<"u"?n:function(e,t){return t},function(e,t){if(jt.length>0)for(var r=0;r<jt.length;r++){var s=jt[r];if(s[1]===e&&s[0]===t){t=s[2],jt.splice(r,1);break}}return n.call(this,e,t)}}function Tu(n,e){const t=lo(),r=e??ho(),s=n.extra??{},a=s.metadata;return n.extra={...s,runtime:{...t,...s?.runtime},metadata:{...r,...r.revision_id||"revision_id"in n&&n.revision_id?{revision_id:("revision_id"in n?n.revision_id:void 0)??r.revision_id}:{},...a}},n}const np=n=>{const e=n?.toString()??Te("TRACING_SAMPLING_RATE");if(e===void 0)return;const 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},sp=n=>{const t=n.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return t==="localhost"||t==="127.0.0.1"||t==="::1"};async function ap(n){const e=[];for await(const t of n)e.push(t);return e}function rn(n){if(n!==void 0)return n.trim().replace(/^"(.*)"$/,"$1").replace(/^\'(.*)\'$/,"$1")}const ip=async n=>{if(n?.status===429){const e=parseInt(n.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(t=>setTimeout(t,e)),!0}return!1};function xu(n){return typeof n=="number"?Number(n.toFixed(4)):n}class op{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(e){let t;const r=new Promise(a=>{t=a}),s=Ce(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:r,size:s}),this.sizeBytes+=s,r}pop({upToSizeBytes:e,upToSize:t}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const r=[];let s=0;for(;s+(this.peek()?.size??0)<e&&this.items.length>0&&r.length<t;){const a=this.items.shift();a&&(r.push(a),s+=a.size,this.sizeBytes-=a.size)}if(r.length===0&&this.items.length>0){const a=this.items.shift();r.push(a),s+=a.size,this.sizeBytes-=a.size}return[r.map(a=>({action:a.action,item:a.payload,otelContext:a.otelContext,apiKey:a.apiKey,apiUrl:a.apiUrl})),()=>r.forEach(a=>a.itemPromiseResolve())]}}const up=24*1024*1024,cp=1e4,lp=100,ku="https://api.smith.langchain.com";class ir{get _fetch(){return this.fetchImplementation||Gh(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 op}),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:Xe("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:Xe("LANGSMITH_DEBUG")==="true"});const t=ir.getDefaultClientConfig();if(this.tracingSampleRate=np(e.tracingSamplingRate),this.apiUrl=rn(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=rn(e.apiKey??t.apiKey),this.webUrl=rn(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=rn(e.workspaceId??Te("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new Io({...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 Io({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:ip,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,fo()&&(this.langSmithToOTELTranslator=new cf),this.cachedLSEnvVarsForMetadata=ho()}static getDefaultClientConfig(){const e=Te("API_KEY"),t=Te("ENDPOINT")??ku,r=Te("HIDE_INPUTS")==="true",s=Te("HIDE_OUTPUTS")==="true";return{apiUrl:t,apiKey:e,webUrl:void 0,hideInputs:r,hideOutputs:s}}getHostUrl(){return this.webUrl?this.webUrl:sp(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){const e={"User-Agent":`langsmith-js/${oo}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){const 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){const r=t?.toString()??"",s=`${this.apiUrl}${e}?${r}`;return await this.caller.call(async()=>{const i=await this._fetch(s,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(i,`fetch ${e}`),i})}async _get(e,t){return(await this._getResponse(e,t)).json()}async*_getPaginated(e,t=new URLSearchParams,r){let s=Number(t.get("offset"))||0;const a=Number(t.get("limit"))||100;for(;;){t.set("offset",String(s)),t.set("limit",String(a));const i=`${this.apiUrl}${e}?${t}`,o=await this.caller.call(async()=>{const c=await this._fetch(i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(c,`fetch ${e}`),c}),u=r?r(await o.json()):await o.json();if(u.length===0||(yield u,u.length<a))break;s+=u.length}}async*_getCursorPaginatedList(e,t=null,r="POST",s="runs"){const a=t?{...t}:{};for(;;){const i=JSON.stringify(a),u=await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}${e}`,{method:r,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await $(l,`fetch ${e}`),l})).json();if(!u||!u[s])break;yield u[s];const 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){const r=[];for(const s of e)this.filteredPostUuids.has(s.trace_id)?s.id===s.trace_id&&this.filteredPostUuids.delete(s.trace_id):r.push(s);return r}else{const r=[];for(const s of e){const a=s.trace_id??s.id;this.filteredPostUuids.has(a)||(s.id===a?this._shouldSample()?r.push(s):this.filteredPostUuids.add(a):r.push(s))}return r}}async _getBatchSizeLimitBytes(){const e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e.batch_ingest_config?.size_limit_bytes??up}async _getBatchSizeLimit(){const e=await this._ensureServerInfo();return this.batchSizeLimit??e.batch_ingest_config?.size_limit??lp}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t}){const r=[];for(;this.autoBatchQueue.items.length>0;){const[s,a]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:t});if(!s.length){a();break}const i=s.reduce((c,l)=>{const d=l.apiUrl??this.apiUrl,h=l.apiKey??this.apiKey,p=l.apiKey===this.apiKey&&l.apiUrl===this.apiUrl?"default":`${d}|${h}`;return c[p]||(c[p]=[]),c[p].push(l),c},{}),o=[];for(const[c,l]of Object.entries(i)){const d=this._processBatch(l,{apiUrl:c==="default"?void 0:c.split("|")[0],apiKey:c==="default"?void 0:c.split("|")[1]});o.push(d)}const u=Promise.all(o).finally(a);r.push(u)}return Promise.all(r)}async _processBatch(e,t){if(e.length)try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{const r={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){const a=s?.instance_flags?.gzip_body_enabled;await this.multipartIngestRuns(r,{...t,useGzip:a})}else await this.batchIngestRuns(r,t)}}catch(r){console.error("Error exporting batch:",r)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){const t=new Map,r=[];for(const s of e)s.item.id&&s.otelContext&&(t.set(s.item.id,s.otelContext),s.action==="create"?r.push({operation:"post",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}):r.push({operation:"patch",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}));this.langSmithToOTELTranslator.exportBatch(r,t)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=Tu(e.item,this.cachedLSEnvVarsForMetadata);const t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;const r=await this._getBatchSizeLimitBytes(),s=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>r||this.autoBatchQueue.items.length>s)&&this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:s}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:s})},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){const t=await(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(cp),...this.fetchOptions});return await $(r,"get server info"),r})).json();return this.debug&&console.log(`\n=== LangSmith Server Configuration ===\n`+JSON.stringify(t,null,2)+`\n`),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(){const e=await this._getBatchSizeLimitBytes(),t=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t})}_cloneCurrentOTELContext(){const e=mo(),t=sf();if(this.langSmithToOTELTranslator!==void 0){const r=e.getActiveSpan();if(r)return e.setSpan(t.active(),r)}}async createRun(e,t){if(!this._filterForSampling([e]).length)return;const r={...this.headers,"Content-Type":"application/json"},s=e.project_name;delete e.project_name;const 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){const u=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:a,otelContext:u,apiKey:t?.apiKey,apiUrl:t?.apiUrl}).catch(console.error);return}const i=Tu(a,this.cachedLSEnvVarsForMetadata);t?.apiKey!==void 0&&(r["x-api-key"]=t.apiKey),t?.workspaceId!==void 0&&(r["x-tenant-id"]=t.workspaceId);const o=Ce(i,`Creating run with id: ${i.id}`);await this.caller.call(async()=>{const u=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await $(u,"create run",!0),u})}async batchIngestRuns({runCreates:e,runUpdates:t},r){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){const u=s.reduce((l,d)=>(d.id&&(l[d.id]=d),l),{}),c=[];for(const 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}const i={post:s,patch:a};if(!i.post.length&&!i.patch.length)return;const o={post:[],patch:[]};for(const u of["post","patch"]){const c=u,l=i[c].reverse();let d=l.pop();for(;d!==void 0;)o[c].push(d),d=l.pop()}if(o.post.length>0||o.patch.length>0){const u=o.post.map(c=>c.id).concat(o.patch.map(c=>c.id)).join(",");await this._postBatchIngestRuns(Ce(o,`Ingesting runs with ids: ${u}`),r)}}async _postBatchIngestRuns(e,t){const r={...this.headers,"Content-Type":"application/json",Accept:"application/json"};t?.apiKey!==void 0&&(r["x-api-key"]=t.apiKey),await this.batchIngestCaller.call(async()=>{const s=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await $(s,"batch create run",!0),s})}async multipartIngestRuns({runCreates:e,runUpdates:t},r){if(e===void 0&&t===void 0)return;const s={};let a=[];for(const d of e??[]){const h=await this.prepareRunCreateOrUpdateInputs(d);h.id!==void 0&&h.attachments!==void 0&&(s[h.id]=h.attachments),delete h.attachments,a.push(h)}let i=[];for(const 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){const d=a.reduce((f,p)=>(p.id&&(f[p.id]=p),f),{}),h=[];for(const f of i)f.id!==void 0&&d[f.id]?d[f.id]={...d[f.id],...f}:h.push(f);a=Object.values(d),i=h}if(a.length===0&&i.length===0)return;const c=[],l=[];for(const[d,h]of[["post",a],["patch",i]])for(const f of h){const{inputs:p,outputs:m,events:g,extra:y,error:_,serialized:b,attachments:E,...v}=f,x={inputs:p,outputs:m,events:g,extra:y,error:_,serialized:b},P=Ce(v,`Serializing for multipart ingestion of run with id: ${v.id}`);l.push({name:`${d}.${v.id}`,payload:new Blob([P],{type:`application/json; length=${P.length}`})});for(const[O,J]of Object.entries(x)){if(J===void 0)continue;const K=Ce(J,`Serializing ${O} for multipart ingestion of run with id: ${v.id}`);l.push({name:`${d}.${v.id}.${O}`,payload:new Blob([K],{type:`application/json; length=${K.length}`})})}if(v.id!==void 0){const O=s[v.id];if(O){delete s[v.id];for(const[J,K]of Object.entries(O)){let ne,Je;if(Array.isArray(K)?[ne,Je]=K:(ne=K.mimeType,Je=K.data),J.includes(".")){console.warn(`Skipping attachment \'${J}\' for run ${v.id}: Invalid attachment name. Attachment names must not contain periods (\'.\'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${v.id}.${J}`,payload:new Blob([Je],{type:`${ne}; length=${Je.byteLength}`})})}}}c.push(`trace=${v.trace_id},id=${v.id}`)}await this._sendMultipartRequest(l,c.join("; "),r)}async _createNodeFetchBody(e,t){const r=[];for(const i of e)r.push(new Blob([`--${t}\\r\n`])),r.push(new Blob([`Content-Disposition: form-data; name="${i.name}"\\r\n`,`Content-Type: ${i.payload.type}\\r\n\\r\n`])),r.push(i.payload),r.push(new Blob([`\\r\n`]));return r.push(new Blob([`--${t}--\\r\n`])),await new Blob(r).arrayBuffer()}async _createMultipartStream(e,t){const r=new TextEncoder;return new ReadableStream({async start(a){const i=async o=>{typeof o=="string"?a.enqueue(r.encode(o)):a.enqueue(o)};for(const o of e){await i(`--${t}\\r\n`),await i(`Content-Disposition: form-data; name="${o.name}"\\r\n`),await i(`Content-Type: ${o.payload.type}\\r\n\\r\n`);const c=o.payload.stream().getReader();try{let l;for(;!(l=await c.read()).done;)a.enqueue(l.value)}finally{c.releaseLock()}await i(`\\r\n`)}await i(`--${t}--\\r\n`),a.close()}})}async _sendMultipartRequest(e,t,r){const s="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),a=Hh(),i=()=>this._createNodeFetchBody(e,s),o=()=>this._createMultipartStream(e,s),u=async c=>this.batchIngestCaller.call(async()=>{const l=await c(),d={...this.headers,"Content-Type":`multipart/form-data; boundary=${s}`};r?.apiKey!==void 0&&(d["x-api-key"]=r.apiKey);let h=l;r?.useGzip&&typeof l=="object"&&"pipeThrough"in l&&(h=l.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");const f=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:h,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(f,"Failed to send multipart request",!0),f});try{let c,l=!1;!a&&!this.multipartStreamingDisabled&&co()!=="bun"?(l=!0,c=await u(o)):c=await u(i),(!this.multipartStreamingDisabled||l)&&c.status===422&&(r?.apiUrl??this.apiUrl)!==ku&&(console.warn(`Streaming multipart upload to ${r?.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()}\n\nContext: ${t}`)}}async updateRun(e,t,r){H(e),t.inputs&&(t.inputs=await this.processInputs(t.inputs)),t.outputs&&(t.outputs=await this.processOutputs(t.outputs));const s={...t,id:e};if(!this._filterForSampling([s],!0).length)return;if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){const 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:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:s,otelContext:o,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}const a={...this.headers,"Content-Type":"application/json"};r?.apiKey!==void 0&&(a["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(a["x-tenant-id"]=r.workspaceId);const i=Ce(t,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{const o=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await $(o,"update run",!0),o})}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){H(e);let r=await this._get(`/runs/${e}`);return t&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:t,projectOpts:r}){if(t!==void 0){let s;t.session_id?s=t.session_id:r?.projectName?s=(await this.readProject({projectName:r?.projectName})).id:r?.projectId?s=r?.projectId:s=(await this.readProject({projectName:Te("PROJECT")||"default"})).id;const a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${s}/r/${t.id}?poll=true`}else if(e!==void 0){const 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){const t=await ap(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),r={},s={};t.sort((a,i)=>(a?.dotted_order??"").localeCompare(i?.dotted_order??""));for(const 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 r||(r[a.parent_run_id]=[]),r[a.parent_run_id].push(a),s[a.id]=a)}e.child_runs=r[e.id]||[];for(const a in r)a!==e.id&&(s[a].child_runs=r[a]);return e}async*listRuns(e){const{projectId:t,projectName:r,parentRunId:s,traceId:a,referenceExampleId:i,startTime:o,executionOrder:u,isRoot:c,runType:l,error:d,id:h,query:f,filter:p,traceFilter:m,treeFilter:g,limit:y,select:_,order:b}=e;let E=[];if(t&&(E=Array.isArray(t)?t:[t]),r){const O=Array.isArray(r)?r:[r],J=await Promise.all(O.map(K=>this.readProject({projectName:K}).then(ne=>ne.id)));E.push(...J)}const v=["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"],x={session:E.length?E:null,run_type:l,reference_example:i,query:f,filter:p,trace_filter:m,tree_filter:g,execution_order:u,parent_run:s,start_time:o?o.toISOString():null,error:d,id:h,limit:y,trace:a,select:_||v,is_root:c,order:b};x.select.includes("child_run_ids")&&Os("Deprecated: \'child_run_ids\' in the listRuns select parameter is deprecated and will be removed in a future version.");let P=0;for await(const O of this._getCursorPaginatedList("/runs/query",x))if(y){if(P>=y)break;if(O.length+P>y){yield*O.slice(0,y-P);break}P+=O.length,yield*O}else yield*O}async*listGroupRuns(e){const{projectId:t,projectName:r,groupBy:s,filter:a,startTime:i,endTime:o,limit:u,offset:c}=e,d={session_id:t||(await this.readProject({projectName:r})).id,group_by:s,filter:a,start_time:i?i.toISOString():null,end_time:o?o.toISOString():null,limit:Number(u)||100};let h=Number(c)||0;const f="/runs/group",p=`${this.apiUrl}${f}`;for(;;){const m={...d,offset:h},g=Object.fromEntries(Object.entries(m).filter(([x,P])=>P!==void 0)),y=JSON.stringify(g),b=await(await this.caller.call(async()=>{const x=await this._fetch(p,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:y});return await $(x,`Failed to fetch ${f}`),x})).json(),{groups:E,total:v}=b;if(E.length===0)break;for(const x of E)yield x;if(h+=E.length,h>=v)break}}async getRunStats({id:e,trace:t,parentRun:r,runType:s,projectNames:a,projectIds:i,referenceExampleIds:o,startTime:u,endTime:c,error:l,query:d,filter:h,traceFilter:f,treeFilter:p,isRoot:m,dataSourceType:g}){let y=i||[];a&&(y=[...i||[],...await Promise.all(a.map(P=>this.readProject({projectName:P}).then(O=>O.id)))]);const b=Object.fromEntries(Object.entries({id:e,trace:t,parent_run:r,run_type:s,session:y,reference_example:o,start_time:u,end_time:c,error:l,query:d,filter:h,trace_filter:f,tree_filter:p,is_root:m,data_source_type:g}).filter(([P,O])=>O!==void 0)),E=JSON.stringify(b);return await(await this.caller.call(async()=>{const P=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:E});return await $(P,"get run stats"),P})).json()}async shareRun(e,{shareId:t}={}){const r={run_id:e,share_token:t||we()};H(e);const s=JSON.stringify(r),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await $(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){H(e),await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(t,"unshare run",!0),t})}async readRunSharedLink(e){H(e);const r=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(s,"read run shared link"),s})).json();if(!(r===null||!("share_token"in r)))return`${this.getHostUrl()}/public/${r.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){const r=new URLSearchParams({share_token:e});if(t!==void 0)for(const i of t)r.append("id",i);return H(e),await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(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),H(e);const s=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(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);const r={dataset_id:e};H(e);const s=JSON.stringify(r),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await $(o,"share dataset"),o})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){H(e),await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(t,"unshare dataset",!0),t})}async readSharedDataset(e){return H(e),await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(s,"read shared dataset"),s})).json()}async listSharedExamples(e,t){const r={};t?.exampleIds&&(r.id=t.exampleIds);const s=new URLSearchParams;Object.entries(r).forEach(([o,u])=>{Array.isArray(u)?u.forEach(c=>s.append(o,c)):s.append(o,u)});const a=await this.caller.call(async()=>{const 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 $(o,"list shared examples"),o}),i=await a.json();if(!a.ok)throw"detail"in i?new Error(`Failed to list shared examples.\nStatus: ${a.status}\nMessage: ${Array.isArray(i.detail)?i.detail.join(`\n`):"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:r=null,upsert:s=!1,projectExtra:a=null,referenceDatasetId:i=null}){const o=s?"?upsert=true":"",u=`${this.apiUrl}/sessions${o}`,c=a||{};r&&(c.metadata=r);const l={name:e,extra:c,description:t};i!==null&&(l.reference_dataset_id=i);const d=JSON.stringify(l);return await(await this.caller.call(async()=>{const p=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 $(p,"create project"),p})).json()}async updateProject(e,{name:t=null,description:r=null,metadata:s=null,projectExtra:a=null,endTime:i=null}){const o=`${this.apiUrl}/sessions/${e}`;let u=a;s&&(u={...u||{},metadata:s});const c=JSON.stringify({name:t,extra:u,description:r,end_time:i?new Date(i).toISOString():null});return await(await this.caller.call(async()=>{const h=await this._fetch(o,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await $(h,"update project"),h})).json()}async hasProject({projectId:e,projectName:t}){let r="/sessions";const 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)H(e),r+=`/${e}`;else if(t!==void 0)s.append("name",t);else throw new Error("Must provide projectName or projectId");const a=await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${r}?${s}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(i,"has project"),i});try{const 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:r}){let s="/sessions";const 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)H(e),s+=`/${e}`;else if(t!==void 0)a.append("name",t);else throw new Error("Must provide projectName or projectId");r!==void 0&&a.append("include_stats",r.toString());const i=await this._get(s,a);let 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");const r=await this.readProject({projectId:e,projectName:t}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(e===void 0&&t===void 0)throw new Error("Must provide either datasetName or datasetId");const r=await this.readDataset({datasetId:e,datasetName:t}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/datasets/${r.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;const e=new URLSearchParams({limit:"1"});for await(const t of this._getPaginated("/sessions",e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:t,nameContains:r,referenceDatasetId:s,referenceDatasetName:a,includeStats:i,datasetVersion:o,referenceFree:u,metadata:c}={}){const l=new URLSearchParams;if(e!==void 0)for(const d of e)l.append("id",d);if(t!==void 0&&l.append("name",t),r!==void 0&&l.append("name_contains",r),s!==void 0)l.append("reference_dataset",s);else if(a!==void 0){const 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(const d of this._getPaginated("/sessions",l))yield*d}async deleteProject({projectId:e,projectName:t}){let r;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?r=(await this.readProject({projectName:t})).id:r=e,H(r),await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(s,`delete session ${r} (${t})`,!0),s})}async uploadCsv({csvFile:e,fileName:t,inputKeys:r,outputKeys:s,description:a,dataType:i,name:o}){const u=`${this.apiUrl}/datasets/upload`,c=new FormData;return c.append("file",e,t),r.forEach(h=>{c.append("input_keys",h)}),s.forEach(h=>{c.append("output_keys",h)}),a&&c.append("description",a),i&&c.append("data_type",i),o&&c.append("name",o),await(await this.caller.call(async()=>{const h=await this._fetch(u,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await $(h,"upload CSV"),h})).json()}async createDataset(e,{description:t,dataType:r,inputsSchema:s,outputsSchema:a,metadata:i}={}){const o={name:e,description:t,extra:i?{metadata:i}:void 0};r&&(o.data_type=r),s&&(o.inputs_schema_definition=s),a&&(o.outputs_schema_definition=a);const u=JSON.stringify(o);return await(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await $(d,"create dataset"),d})).json()}async readDataset({datasetId:e,datasetName:t}){let r="/datasets";const s=new URLSearchParams({limit:"1"});if(e&&t)throw new Error("Must provide either datasetName or datasetId, not both");if(e)H(e),r+=`/${e}`;else if(t)s.append("name",t);else throw new Error("Must provide datasetName or datasetId");const a=await this._get(r,s);let 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(r){if(r instanceof Error&&r.message.toLocaleLowerCase().includes("not found"))return!1;throw r}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:r,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);const i=new URLSearchParams({from_version:typeof r=="string"?r:r.toISOString(),to_version:typeof s=="string"?s:s.toISOString()});return await this._get(`/datasets/${a}/versions/diff`,i)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){const r="/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(`${r}/${e}/openai_ft`)).text()).trim().split(`\n`).map(o=>JSON.parse(o))}async*listDatasets({limit:e=100,offset:t=0,datasetIds:r,datasetName:s,datasetNameContains:a,metadata:i}={}){const o="/datasets",u=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(r!==void 0)for(const c of r)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(const c of this._getPaginated(o,u))yield*c}async updateDataset(e){const{datasetId:t,datasetName:r,...s}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const a=t??(await this.readDataset({datasetName:r})).id;H(a);const i=JSON.stringify(s);return await(await this.caller.call(async()=>{const 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 $(u,"update dataset"),u})).json()}async updateDatasetTag(e){const{datasetId:t,datasetName:r,asOf:s,tag:a}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const i=t??(await this.readDataset({datasetName:r})).id;H(i);const o=JSON.stringify({as_of:typeof s=="string"?s:s.toISOString(),tag:a});await this.caller.call(async()=>{const 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 $(u,"update dataset tags",!0),u})}async deleteDataset({datasetId:e,datasetName:t}){let r="/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)H(s),r+=`/${s}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{const a=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(a,`delete ${r}`,!0),a})}async indexDataset({datasetId:e,datasetName:t,tag:r}){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),H(s);const i=JSON.stringify({tag:r});await(await this.caller.call(async()=>{const 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 $(u,"index dataset"),u})).json()}async similarExamples(e,t,r,{filter:s}={}){const a={limit:r,inputs:e};s!==void 0&&(a.filter=s),H(t);const i=JSON.stringify(a);return(await(await this.caller.call(async()=>{const 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 $(c,"fetch similar examples"),c})).json()).examples}async createExample(e,t,r){if(Pu(e)&&(t!==void 0||r!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let s=t?r?.datasetId:e.dataset_id;const a=t?r?.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);const i=(t?r?.createdAt:e.created_at)||new Date;let o;Pu(e)?o=e:o={inputs:e,outputs:t,created_at:i?.toISOString(),id:r?.exampleId,metadata:r?.metadata,split:r?.split,source_run_id:r?.sourceRunId,use_source_run_io:r?.useSourceRunIO,use_source_run_attachments:r?.useSourceRunAttachments,attachments:r?.attachments};const u=await this._uploadExamplesMultipart(s,[o]);return await this.readExample(u.example_ids?.[0]??we())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];const _=e;let b=_[0].dataset_id;const E=_[0].dataset_name;if(b===void 0&&E===void 0)throw new Error("Must provide either datasetName or datasetId");if(b!==void 0&&E!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");b===void 0&&(b=(await this.readDataset({datasetName:E})).id);const v=await this._uploadExamplesMultipart(b,_);return await Promise.all(v.example_ids.map(P=>this.readExample(P)))}const{inputs:t,outputs:r,metadata:s,splits:a,sourceRunIds:i,useSourceRunIOs:o,useSourceRunAttachments:u,attachments:c,exampleIds:l,datasetId:d,datasetName:h}=e;if(t===void 0)throw new Error("Must provide inputs when using legacy parameters");let f=d;const p=h;if(f===void 0&&p===void 0)throw new Error("Must provide either datasetName or datasetId");if(f!==void 0&&p!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");f===void 0&&(f=(await this.readDataset({datasetName:p})).id);const m=t.map((_,b)=>({dataset_id:f,inputs:_,outputs:r?.[b],metadata:s?.[b],split:a?.[b],id:l?.[b],attachments:c?.[b],source_run_id:i?.[b],use_source_run_io:o?.[b],use_source_run_attachments:u?.[b]})),g=await this._uploadExamplesMultipart(f,m);return await Promise.all(g.example_ids.map(_=>this.readExample(_)))}async createLLMExample(e,t,r){return this.createExample({input:e},{output:t},r)}async createChatExample(e,t,r){const s=e.map(i=>Ro(i)?To(i):i),a=Ro(t)?To(t):t;return this.createExample({input:s},{output:a},r)}async readExample(e){H(e);const t=`/examples/${e}`,r=await this._get(t),{attachment_urls:s,...a}=r,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:r,asOf:s,splits:a,inlineS3Urls:i,metadata:o,limit:u,offset:c,filter:l,includeAttachments:d}={}){let h;if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)h=e;else if(t!==void 0)h=(await this.readDataset({datasetName:t})).id;else throw new Error("Must provide a datasetName or datasetId");const f=new URLSearchParams({dataset:h}),p=s?typeof s=="string"?s:s?.toISOString():void 0;p&&f.append("as_of",p);const m=i??!0;if(f.append("inline_s3_urls",m.toString()),r!==void 0)for(const y of r)f.append("id",y);if(a!==void 0)for(const y of a)f.append("splits",y);if(o!==void 0){const y=JSON.stringify(o);f.append("metadata",y)}u!==void 0&&f.append("limit",u.toString()),c!==void 0&&f.append("offset",c.toString()),l!==void 0&&f.append("filter",l),d===!0&&["attachment_urls","outputs","metadata"].forEach(y=>f.append("select",y));let g=0;for await(const y of this._getPaginated("/examples",f)){for(const _ of y){const{attachment_urls:b,...E}=_,v=E;b&&(v.attachments=Object.entries(b).reduce((x,[P,O])=>(x[P.slice(11)]={presigned_url:O.presigned_url,mime_type:O.mime_type||void 0},x),{})),yield v,g++}if(u!==void 0&&g>=u)break}}async deleteExample(e){H(e);const t=`/examples/${e}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(r,`delete ${t}`,!0),r})}async updateExample(e,t){let r;t?r=e:r=e.id,H(r);let s;t?s={id:r,...t}:s=e;let a;return s.dataset_id!==void 0?a=s.dataset_id:a=(await this.readExample(r)).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:r,tag:s}){let a;if(e?a=e:a=(await this.readDataset({datasetName:t})).id,H(a),r&&s||!r&&!s)throw new Error("Exactly one of asOf and tag must be specified.");const i=new URLSearchParams;return r!==void 0&&i.append("as_of",typeof r=="string"?r:r.toISOString()),s!==void 0&&i.append("tag",s),await(await this.caller.call(async()=>{const 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 $(u,"read dataset version"),u})).json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:r}){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,H(s);const a=new URLSearchParams,i=r?typeof r=="string"?r:r?.toISOString():void 0;return i&&a.append("as_of",i),await this._get(`/datasets/${s}/splits`,a)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:r,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,H(i);const o={split_name:r,examples:s.map(c=>(H(c),c)),remove:a},u=JSON.stringify(o);await this.caller.call(async()=>{const 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 $(c,"update dataset splits",!0),c})}async evaluateRun(e,t,{sourceInfo:r,loadChildRuns:s,referenceExample:a}={loadChildRuns:!1}){Os("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));const o=await t.evaluateRun(i,a),[u,c]=await this._logEvaluationFeedback(o,i,r);return c[0]}async createFeedback(e,t,{score:r,value:s,correction:a,comment:i,sourceInfo:o,feedbackSourceType:u="api",sourceRunId:c,feedbackId:l,feedbackConfig:d,projectId:h,comparativeExperimentId:f}){if(!e&&!h)throw new Error("One of runId or projectId must be provided");if(e&&h)throw new Error("Only one of runId or projectId can be provided");const p={type:u??"api",metadata:o??{}};c!==void 0&&p?.metadata!==void 0&&!p.metadata.__run&&(p.metadata.__run={run_id:c}),p?.metadata!==void 0&&p.metadata.__run?.run_id!==void 0&&H(p.metadata.__run.run_id);const m={id:l??we(),run_id:e,key:t,score:xu(r),value:s,correction:a,comment:i,feedback_source:p,comparative_experiment_id:f,feedbackConfig:d,session_id:h},g=JSON.stringify(m),y=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const _=await this._fetch(y,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:g});return await $(_,"create feedback",!0),_}),m}async updateFeedback(e,{score:t,value:r,correction:s,comment:a}){const i={};t!=null&&(i.score=xu(t)),r!=null&&(i.value=r),s!=null&&(i.correction=s),a!=null&&(i.comment=a),H(e);const o=JSON.stringify(i);await this.caller.call(async()=>{const 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 $(u,"update feedback",!0),u})}async readFeedback(e){H(e);const t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){H(e);const t=`/feedback/${e}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(r,`delete ${t}`,!0),r})}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:r}={}){const s=new URLSearchParams;if(e)for(const a of e)H(a),s.append("run",a);if(t)for(const a of t)s.append("key",a);if(r)for(const a of r)s.append("source",a);for await(const a of this._getPaginated("/feedback",s))yield*a}async createPresignedFeedbackToken(e,t,{expiration:r,feedbackConfig:s}={}){const a={run_id:e,feedback_key:t,feedback_config:s};r?typeof r=="string"?a.expires_at=r:(r?.hours||r?.minutes||r?.days)&&(a.expires_in=r):a.expires_in={hours:3};const i=JSON.stringify(a);return await(await this.caller.call(async()=>{const 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 $(u,"create presigned feedback token"),u})).json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:r,createdAt:s,description:a,metadata:i,id:o}){if(t.length===0)throw new Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:t[0]})).reference_dataset_id),!r==null)throw new Error("A reference dataset is required");const u={id:o,name:e,experiment_ids:t,reference_dataset_id:r,description:a,created_at:(s??new Date)?.toISOString(),extra:{}};i&&(u.extra.metadata=i);const c=JSON.stringify(u);return(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await $(d,"create comparative experiment"),d})).json()}async*listPresignedFeedbackTokens(e){H(e);const t=new URLSearchParams({run_id:e});for await(const r of this._getPaginated("/feedback/tokens",t))yield*r}_selectEvalResults(e){let t;return"results"in e?t=e.results:Array.isArray(e)?t=e:t=[e],t}async _logEvaluationFeedback(e,t,r){const s=this._selectEvalResults(e),a=[];for(const i of s){let o=r||{};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,r){const[s]=await this._logEvaluationFeedback(e,t,r);return s}async*listAnnotationQueues(e={}){const{queueIds:t,name:r,nameContains:s,limit:a}=e,i=new URLSearchParams;t&&t.forEach((u,c)=>{H(u,`queueIds[${c}]`),i.append("ids",u)}),r&&i.append("name",r),s&&i.append("name_contains",s),i.append("limit",(a!==void 0?Math.min(a,100):100).toString());let o=0;for await(const u of this._getPaginated("/annotation-queues",i))if(yield*u,o++,a!==void 0&&o>=a)break}async createAnnotationQueue(e){const{name:t,description:r,queueId:s,rubricInstructions:a}=e,i={name:t,description:r,id:s||we(),rubric_instructions:a},o=JSON.stringify(Object.fromEntries(Object.entries(i).filter(([c,l])=>l!==void 0)));return(await this.caller.call(async()=>{const 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 $(c,"create annotation queue"),c})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${H(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(r,"read annotation queue"),r})).json()}async updateAnnotationQueue(e,t){const{name:r,description:s,rubricInstructions:a}=t,i=JSON.stringify({name:r,description:s,rubric_instructions:a});await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/annotation-queues/${H(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await $(o,"update annotation queue",!0),o})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/annotation-queues/${H(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(t,"delete annotation queue",!0),t})}async addRunsToAnnotationQueue(e,t){const r=JSON.stringify(t.map((s,a)=>H(s,`runIds[${a}]`).toString()));await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/annotation-queues/${H(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await $(s,"add runs to annotation queue",!0),s})}async getRunFromAnnotationQueue(e,t){const r=`/annotation-queues/${H(e,"queueId")}/run`;return(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}${r}/${t}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(a,"get run from annotation queue"),a})).json()}async deleteRunFromAnnotationQueue(e,t){await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${H(e,"queueId")}/runs/${H(t,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(r,"delete run from annotation queue",!0),r})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${H(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(r,"get size from annotation queue"),r})).json()}async _currentTenantIsOwner(e){const t=await this._getSettings();return e=="-"||t.tenant_handle===e}async _ownerConflictError(e,t){const r=await this._getSettings();return new Error(`Cannot ${e} for another tenant.\n\n Current tenant: ${r.tenant_handle}\n\n Requested tenant: ${t}`)}async _getLatestCommitHash(e){const r=await(await this.caller.call(async()=>{const 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 $(s,"get latest commit hash"),s})).json();if(r.commits.length!==0)return r.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){const[r,s,a]=ut(e),i=JSON.stringify({like:t});return(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/likes/${r}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await $(u,`${t?"like":"unlike"} prompt`),u})).json()}async _getPromptUrl(e){const[t,r,s]=ut(e);if(await this._currentTenantIsOwner(t)){const a=await this._getSettings();return s!=="latest"?`${this.getHostUrl()}/prompts/${r}/${s.substring(0,8)}?organizationId=${a.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${a.id}`}else return s!=="latest"?`${this.getHostUrl()}/hub/${t}/${r}/${s.substring(0,8)}`:`${this.getHostUrl()}/hub/${t}/${r}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){for await(const t of this._getPaginated(`/commits/${e}/`,new URLSearchParams,r=>r.commits))yield*t}async*listPrompts(e){const t=new URLSearchParams;t.append("sort_field",e?.sortField??"updated_at"),t.append("sort_direction","desc"),t.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&t.append("is_public",e.isPublic.toString()),e?.query&&t.append("query",e.query);for await(const r of this._getPaginated("/repos",t,s=>s.repos))yield*r}async getPrompt(e){const[t,r,s]=ut(e),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/repos/${t}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return o?.status===404?null:(await $(o,"get prompt"),o)}))?.json();return i?.repo?i.repo:null}async createPrompt(e,t){const r=await this._getSettings();if(t?.isPublic&&!r.tenant_handle)throw new Error(`Cannot create a public prompt without first\n\n creating a LangChain Hub handle.\n You can add a handle by creating a public prompt at:\n\n https://smith.langchain.com/prompts`);const[s,a,i]=ut(e);if(!await this._currentTenantIsOwner(s))throw await this._ownerConflictError("create a prompt",s);const 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()=>{const d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await $(d,"create prompt"),d}),{repo:l}=await c.json();return l}async createCommit(e,t,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[s,a,i]=ut(e),o=r?.parentCommitHash==="latest"||!r?.parentCommitHash?await this._getLatestCommitHash(`${s}/${a}`):r?.parentCommitHash,u={manifest:JSON.parse(JSON.stringify(t)),parent_commit:o},c=JSON.stringify(u),d=await(await this.caller.call(async()=>{const h=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 $(h,"create commit"),h})).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.");const r=new FormData;for(const i of t){const o=i.id,u={...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split}},c=Ce(u,`Serializing body for example with id: ${o}`),l=new Blob([c],{type:"application/json"});if(r.append(o,l),i.inputs){const d=Ce(i.inputs,`Serializing inputs for example with id: ${o}`),h=new Blob([d],{type:"application/json"});r.append(`${o}.inputs`,h)}if(i.outputs){const d=Ce(i.outputs,`Serializing outputs whle updating example with id: ${o}`),h=new Blob([d],{type:"application/json"});r.append(`${o}.outputs`,h)}if(i.attachments)for(const[d,h]of Object.entries(i.attachments)){let f,p;Array.isArray(h)?[f,p]=h:(f=h.mimeType,p=h.data);const m=new Blob([p],{type:`${f}; length=${p.byteLength}`});r.append(`${o}.attachment.${d}`,m)}if(i.attachments_operations){const d=Ce(i.attachments_operations,`Serializing attachments while updating example with id: ${o}`),h=new Blob([d],{type:"application/json"});r.append(`${o}.attachments_operations`,h)}}const s=e??t[0]?.dataset_id;return(await this.caller.call(async()=>{const 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:r});return await $(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.");const r=new FormData;for(const a of t){const i=(a.id??we()).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=Ce(o,`Serializing body for uploaded example with id: ${i}`),c=new Blob([u],{type:"application/json"});if(r.append(i,c),a.inputs){const l=Ce(a.inputs,`Serializing inputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});r.append(`${i}.inputs`,d)}if(a.outputs){const l=Ce(a.outputs,`Serializing outputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});r.append(`${i}.outputs`,d)}if(a.attachments)for(const[l,d]of Object.entries(a.attachments)){let h,f;Array.isArray(d)?[h,f]=d:(h=d.mimeType,f=d.data);const p=new Blob([f],{type:`${h}; length=${f.byteLength}`});r.append(`${i}.attachment.${l}`,p)}}return(await this.caller.call(async()=>{const 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:r});return await $(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.");const[r,s]=ut(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);const 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");const i=JSON.stringify(a);return(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/repos/${r}/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await $(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.");const[t,r,s]=ut(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/repos/${t}/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(i,"delete prompt"),i})).json()}async pullPromptCommit(e,t){const[r,s,a]=ut(e),o=await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/commits/${r}/${s}/${a}${t?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $(u,"pull prompt commit"),u})).json();return{owner:r,repo:s,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async _pullPrompt(e,t){const r=await this.pullPromptCommit(e,{includeModel:t?.includeModel});return JSON.stringify(r.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={}){const{sourceApiUrl:r=this.apiUrl,datasetName:s}=t,[a,i]=this.parseTokenOrUrl(e,r),o=new ir({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{}const 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(h=>h.inputs),outputs:l.flatMap(h=>h.outputs?[h.outputs]:[]),datasetId:d.id})}catch(h){throw console.error(`An error occurred while creating dataset ${c}. You should delete it manually.`),h}}parseTokenOrUrl(e,t,r=2,s="dataset"){try{return H(e),[t,e]}catch{}try{const i=new URL(e).pathname.split("/").filter(o=>o!=="");if(i.length>=r){const o=i[i.length-r];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 af()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function Pu(n){return"dataset_id"in n||"dataset_name"in n}const dp=n=>!!["TRACING_V2","TRACING"].find(t=>Te(t)==="true"),Aa=Symbol.for("lc:context_variables");function hp(n){return n.replace(/[-:.]/g,"")}function Cu(n,e,t=1){const r=t.toFixed(0).slice(0,3).padStart(3,"0"),s=`${new Date(n).toISOString().slice(0,-1)}${r}Z`;return{dottedOrder:hp(s)+e,microsecondPrecisionDatestring:s}}class nn{constructor(e,t,r,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=r,this.replicas=s}static fromHeader(e){const t=e.split(",");let r={},s=[],a,i;for(const o of t){const[u,c]=o.split("="),l=decodeURIComponent(c);u==="langsmith-metadata"?r=JSON.parse(l):u==="langsmith-tags"?s=l.split(","):u==="langsmith-project"?a=l:u==="langsmith-replicas"&&(i=JSON.parse(l))}return new nn(r,s,a,i)}toHeader(){const e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}}class xe{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}),fp(e)){Object.assign(this,{...e});return}const t=xe.getDefaultConfig(),{metadata:r,...s}=e,a=s.client??xe.getSharedClient(),i={...r,...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=yp(this.replicas),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){const{dottedOrder:o,microsecondPrecisionDatestring:u}=Cu(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:we(),run_type:"chain",project_name:io(),child_runs:[],api_url:Xe("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Xe("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return xe.sharedClient||(xe.sharedClient=new ir),xe.sharedClient}createChild(e){const t=this.child_execution_order+1,r=new xe({...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});Aa in this&&(r[Aa]=this[Aa]);const s=Symbol.for("lc:child_config"),a=e.extra?.[s]??this.extra[s];if(mp(a)){const u={...a},c=pp(u.callbacks)?u.callbacks.copy?.():void 0;c&&(Object.assign(c,{_parentRunId:r.id}),c.handlers?.find(Nu)?.updateFromRunTree?.(r),u.callbacks=c),r.extra[s]=u}const i=new Set;let o=this;for(;o!=null&&!i.has(o.id);)i.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,t),o=o.parent_run;return this.child_runs.push(r),r}async end(e,t,r=Date.now(),s){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??r,s&&Object.keys(s).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...s}}:{metadata:s})}_convertToCreate(e,t,r=!0){const s=e.extra??{};if(s?.runtime?.library===void 0&&(s.runtime||(s.runtime={}),t))for(const[o,u]of Object.entries(t))s.runtime[o]||(s.runtime[o]=u);let a,i;return r?(i=e.parent_run?.id??e.parent_run_id,a=[]):(a=e.child_runs.map(o=>this._convertToCreate(o,t,r)),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,r=!0){const s=this._convertToCreate(this,t,r);if(e===this.project_name)return s;const a=d=>Vi(`${d}:${e}`,Vi.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;let c;if(s.dotted_order){const d=gp(s.dotted_order),h=[];for(let p=0;p<d.length-1;p++){const[m,g]=d[p],y=a(g);h.push(m.toISOString().replace(/[-:]/g,"").replace(".","")+y)}const[f]=d[d.length-1];h.push(f.toISOString().replace(/[-:]/g,"").replace(".","")+i),c=h.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{const t=lo();if(this.replicas&&this.replicas.length>0)for(const{projectName:r,apiKey:s,apiUrl:a,workspaceId:i}of this.replicas){const o=this._remapForProject(r??this.project_name,t,!0);await this.client.createRun(o,{apiKey:s,apiUrl:a,workspaceId:i})}else{const r=this._convertToCreate(this,t,e);await this.client.createRun(r)}if(!e){Os("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const r of this.child_runs)await r.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(const{projectName:t,apiKey:r,apiUrl:s,workspaceId:a,updates:i}of this.replicas){const 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:r,apiUrl:s,workspaceId:a})}else try{const 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){const r=e?.callbacks;let s,a,i,o=dp();if(r){const c=r?.getParentRunId?.()??"",l=r?.handlers?.find(d=>d?.name=="langchain_tracer");s=l?.getRun?.(c),a=l?.projectName,i=l?.client,o=o||!!l}return s?new xe({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 xe({...t,client:i,tracingEnabled:o,project_name:a})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){const r="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,s=r["langsmith-trace"];if(!s||typeof s!="string")return;const a=s.trim(),i=a.split(".").map(c=>{const[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(r.baggage&&typeof r.baggage=="string"){const c=nn.fromHeader(r.baggage);u.metadata=c.metadata,u.tags=c.tags,u.project_name=c.project_name,u.replicas=c.replicas}return new xe(u)}toHeaders(e){const t={"langsmith-trace":this.dotted_order,baggage:new nn(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(const[r,s]of Object.entries(t))e.set(r,s);return t}}Object.defineProperty(xe,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function fp(n){return n!=null&&typeof n.createChild=="function"&&typeof n.postRun=="function"}function Nu(n){return typeof n=="object"&&n!=null&&typeof n.name=="string"&&n.name==="langchain_tracer"}function $u(n){return Array.isArray(n)&&n.some(e=>Nu(e))}function pp(n){return typeof n=="object"&&n!=null&&Array.isArray(n.handlers)}function mp(n){return n!=null&&typeof n.callbacks=="object"&&($u(n.callbacks?.handlers)||$u(n.callbacks))}function gp(n){return n.split(".").map(t=>{const r=t.slice(0,-36),s=t.slice(-36),a=parseInt(r.slice(0,4)),i=parseInt(r.slice(4,6))-1,o=parseInt(r.slice(6,8)),u=parseInt(r.slice(9,11)),c=parseInt(r.slice(11,13)),l=parseInt(r.slice(13,15)),d=parseInt(r.slice(15,21));return[new Date(a,i,o,u,c,l,d/1e3),s]})}function _p(){const n=Xe("LANGSMITH_RUNS_ENDPOINTS");if(!n)return[];try{const e=JSON.parse(n);if(Array.isArray(e)){const t=[];for(const r of e){if(typeof r!="object"||r===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof r}`);continue}if(typeof r.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_url}`);continue}if(typeof r.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_key}`);continue}t.push({apiUrl:r.api_url.replace(/\\/$/,""),apiKey:r.api_key})}return t}else if(typeof e=="object"&&e!==null){bp(e);const t=[];for(const[r,s]of Object.entries(e)){const a=r.replace(/\\/$/,"");if(typeof s=="string")t.push({apiUrl:a,apiKey:s});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${r}: expected string, got ${typeof s}`);continue}}return t}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof e}`),[]}catch(e){if(Xf(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function yp(n){return n?n.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):_p()}function bp(n){if(Object.keys(n).length>0&&Te("ENDPOINT"))throw new Kf}const wp=n=>{if(n)return n.events=n.events??[],n.child_runs=n.child_runs??[],n};function Oa(n,e){if(n)return new xe({...n,start_time:n._serialized_start_time??n.start_time,parent_run:Oa(e),child_runs:n.child_runs.map(t=>Oa(t)).filter(t=>t!==void 0),extra:{...n.extra,runtime:lh()},tracingEnabled:!1})}function Ia(n,e){return n&&!Array.isArray(n)&&typeof n=="object"?n:{[e]:n}}function or(n){return typeof n._addRunToRunMap=="function"}class ur extends rr{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?wp(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`\n\n${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){const{dottedOrder:t,microsecondPrecisionDatestring:r}=Cu(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=r)):(s.trace_id=s.id,s.dotted_order=t,s._serialized_start_time=r),this.usesRunTreeMap){const i=Oa(s,a);i!==void 0&&this.runTreeMap.set(s.id,i)}else this.runMap.set(s.id,s);return s}async _endTrace(e){const 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){const t=e!==void 0&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,r,s,a,i,o,u){const c=this._getExecutionOrder(s),l=Date.now(),d=o?{...a,metadata:o}:a,h={id:r,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(h)}async handleLLMStart(e,t,r,s,a,i,o,u){const c=this.getRunById(r)??this._createRunForLLMStart(e,t,r,s,a,i,o,u);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,t,r,s,a,i,o,u){const c=this._getExecutionOrder(s),l=Date.now(),d=o?{...a,metadata:o}:a,h={id:r,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(h)}async handleChatModelStart(e,t,r,s,a,i,o,u){const c=this.getRunById(r)??this._createRunForChatModelStart(e,t,r,s,a,i,o,u);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,t,r,s,a){const 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,r,s,a){const 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,r,s,a,i,o,u){const c=this._getExecutionOrder(s),l=Date.now(),d={id:r,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,r,s,a,i,o,u){const c=this.getRunById(r)??this._createRunForChainStart(e,t,r,s,a,i,o,u);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,t,r,s,a){const i=this.getRunById(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=Ia(e,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),a?.inputs!==void 0&&(i.inputs=Ia(a.inputs,"input")),await this.onChainEnd?.(i),await this._endTrace(i),i}async handleChainError(e,t,r,s,a){const 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=Ia(a.inputs,"input")),await this.onChainError?.(i),await this._endTrace(i),i}_createRunForToolStart(e,t,r,s,a,i,o){const u=this._getExecutionOrder(s),c=Date.now(),l={id:r,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,r,s,a,i,o){const u=this.getRunById(r)??this._createRunForToolStart(e,t,r,s,a,i,o);return await this.onRunCreate?.(u),await this.onToolStart?.(u),u}async handleToolEnd(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="chain")return;const s=r;s.actions=s.actions||[],s.actions.push(e),s.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(r)}async handleAgentEnd(e,t){const r=this.getRunById(t);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(e,t,r,s,a,i,o){const u=this._getExecutionOrder(s),c=Date.now(),l={id:r,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,r,s,a,i,o){const u=this.getRunById(r)??this._createRunForRetrieverStart(e,t,r,s,a,i,o);return await this.onRunCreate?.(u),await this.onRetrieverStart?.(u),u}async handleRetrieverEnd(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(e,t){const r=this.getRunById(t);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(r))}async handleLLMNewToken(e,t,r,s,a,i){const o=this.getRunById(r);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}}function Ee(n,e){return`${n.open}${e}${n.close}`}function Fe(n,e){try{return JSON.stringify(n,null,2)}catch{return e}}function Lu(n){return typeof n=="string"?n.trim():n==null?n:Fe(n,n.toString())}function ct(n){if(!n.end_time)return"";const e=n.end_time-n.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}const{color:ke}=Yi;class ju extends ur{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"console_callback_handler"})}persistRun(e){return Promise.resolve()}getParents(e){const t=[];let r=e;for(;r.parent_run_id;){const s=this.runMap.get(r.parent_run_id);if(s)t.push(s),r=s;else break}return t}getBreadcrumbs(e){const r=[...this.getParents(e).reverse(),e].map((s,a,i)=>{const o=`${s.execution_order}:${s.run_type}:${s.name}`;return a===i.length-1?Ee(Yi.bold,o):o}).join(" > ");return Ee(ke.grey,r)}onChainStart(e){const t=this.getBreadcrumbs(e);console.log(`${Ee(ke.green,"[chain/start]")} [${t}] Entering Chain run with input: ${Fe(e.inputs,"[inputs]")}`)}onChainEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Ee(ke.cyan,"[chain/end]")} [${t}] [${ct(e)}] Exiting Chain run with output: ${Fe(e.outputs,"[outputs]")}`)}onChainError(e){const t=this.getBreadcrumbs(e);console.log(`${Ee(ke.red,"[chain/error]")} [${t}] [${ct(e)}] Chain run errored with error: ${Fe(e.error,"[error]")}`)}onLLMStart(e){const t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(s=>s.trim())}:e.inputs;console.log(`${Ee(ke.green,"[llm/start]")} [${t}] Entering LLM run with input: ${Fe(r,"[inputs]")}`)}onLLMEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Ee(ke.cyan,"[llm/end]")} [${t}] [${ct(e)}] Exiting LLM run with output: ${Fe(e.outputs,"[response]")}`)}onLLMError(e){const t=this.getBreadcrumbs(e);console.log(`${Ee(ke.red,"[llm/error]")} [${t}] [${ct(e)}] LLM run errored with error: ${Fe(e.error,"[error]")}`)}onToolStart(e){const t=this.getBreadcrumbs(e);console.log(`${Ee(ke.green,"[tool/start]")} [${t}] Entering Tool run with input: "${Lu(e.inputs.input)}"`)}onToolEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Ee(ke.cyan,"[tool/end]")} [${t}] [${ct(e)}] Exiting Tool run with output: "${Lu(e.outputs?.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${Ee(ke.red,"[tool/error]")} [${t}] [${ct(e)}] Tool run errored with error: ${Fe(e.error,"[error]")}`)}onRetrieverStart(e){const t=this.getBreadcrumbs(e);console.log(`${Ee(ke.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${Fe(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Ee(ke.cyan,"[retriever/end]")} [${t}] [${ct(e)}] Exiting Retriever run with output: ${Fe(e.outputs,"[outputs]")}`)}onRetrieverError(e){const t=this.getBreadcrumbs(e);console.log(`${Ee(ke.red,"[retriever/error]")} [${t}] [${ct(e)}] Retriever run errored with error: ${Fe(e.error,"[error]")}`)}onAgentAction(e){const t=e,r=this.getBreadcrumbs(e);console.log(`${Ee(ke.blue,"[agent/action]")} [${r}] Agent selected action: ${Fe(t.actions[t.actions.length-1],"[action]")}`)}}function vp(n){return!!(n&&typeof n=="object"&&"type"in n&&n.type==="tool_call")}class Ep extends Error{constructor(e,t){super(e),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=t}}function Sp(n){if(typeof n>"u")return null;try{return JSON.parse(n)}catch{}let e="";const t=[];let r=!1,s=!1;for(let a of n){if(r)a===\'"\'&&!s?r=!1:a===`\n`&&!s?a="\\\\n":a==="\\\\"?s=!s:s=!1;else if(a===\'"\')r=!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}r&&(e+=\'"\');for(let a=t.length-1;a>=0;a-=1)e+=t[a];try{return JSON.parse(e)}catch{return null}}function Mu(n){return typeof n=="object"&&n!==null&&"type"in n&&typeof n.type=="string"&&"source_type"in n&&(n.source_type==="url"||n.source_type==="base64"||n.source_type==="text"||n.source_type==="id")}function Ap(n,e){return typeof n=="string"?n===""?e:typeof e=="string"?n+e:Array.isArray(e)&&e.some(t=>Mu(t))?[{type:"text",source_type:"text",text:n},...e]:[{type:"text",text:n},...e]:Array.isArray(e)?Ra(n,e)??[...n,...e]:e===""?n:Array.isArray(n)&&n.some(t=>Mu(t))?[...n,{type:"file",source_type:"text",text:e}]:[...n,{type:"text",text:e}]}function Op(n,e){function t(r,s){if(typeof r!="object"||r===null||r===void 0)return r;if(s>=e)return Array.isArray(r)?"[Array]":"[Object]";if(Array.isArray(r))return r.map(i=>t(i,s+1));const a={};for(const i of Object.keys(r))a[i]=t(r[i],s+1);return a}return JSON.stringify(t(n,0),null,2)}class Ip extends Et{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;const t=Op(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}}function sn(n,e){const t={...n};for(const[r,s]of Object.entries(e))if(t[r]==null)t[r]=s;else{if(s==null)continue;if(typeof t[r]!=typeof s||Array.isArray(t[r])!==Array.isArray(s))throw new Error(`field[${r}] already exists in the message chunk, but with a different type.`);if(typeof t[r]=="string"){if(r==="type")continue;["id","name","output_version","model_provider"].includes(r)?t[r]=s:t[r]+=s}else if(typeof t[r]=="object"&&!Array.isArray(t[r]))t[r]=sn(t[r],s);else if(Array.isArray(t[r]))t[r]=Ra(t[r],s);else{if(t[r]===s)continue;console.warn(`field[${r}] already exists in this message chunk and value has unsupported type.`)}}return t}function Ra(n,e){if(!(n===void 0&&e===void 0)){if(n===void 0||e===void 0)return n||e;{const t=[...n];for(const r of e)if(typeof r=="object"&&r!==null&&"index"in r&&typeof r.index=="number"){const s=t.findIndex(a=>{const i=typeof a=="object",o="index"in a&&a.index===r.index,u="id"in a&&"id"in r&&a?.id===r?.id,c=!("id"in a)||!a?.id||!("id"in r)||!r?.id;return i&&o&&(u||c)});s!==-1&&typeof t[s]=="object"&&t[s]!==null?t[s]=sn(t[s],r):t.push(r)}else{if(typeof r=="object"&&r!==null&&"text"in r&&r.text==="")continue;t.push(r)}return t}}}class Rp extends Ip{}class an extends Rp{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||e.tool_call_chunks.length===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{const s=(e.tool_call_chunks??[]).reduce((o,u)=>{const c=o.findIndex(([l])=>"id"in u&&u.id&&"index"in u&&u.index!==void 0?u.id===l.id&&u.index===l.index:"id"in u&&u.id?u.id===l.id:"index"in u&&u.index!==void 0?u.index===l.index:!1);return c!==-1?o[c].push(u):o.push([u]),o},[]),a=[],i=[];for(const o of s){let u={};const c=o[0]?.name??"",l=o.map(f=>f.args||"").join(""),d=l.length?l:"{}",h=o[0]?.id;try{if(u=Sp(d),!h||u===null||typeof u!="object"||Array.isArray(u))throw new Error("Malformed tool call chunk args.");a.push({name:c,args:u,id:h,type:"tool_call"})}catch{i.push({name:c,args:d,id:h,error:"Malformed args.",type:"invalid_tool_call"})}}t={...e,tool_calls:a,invalid_tool_calls:i,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){const t={content:Ap(this.content,e.content),additional_kwargs:sn(this.additional_kwargs,e.additional_kwargs),response_metadata:sn(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){const r=Ra(this.tool_call_chunks,e.tool_call_chunks);r!==void 0&&r.length>0&&(t.tool_call_chunks=r)}if(this.usage_metadata!==void 0||e.usage_metadata!==void 0){const r={...(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(r).length>0&&{input_token_details:r},...Object.keys(s).length>0&&{output_token_details:s}};t.usage_metadata=o}return new an(t)}}function Tp(n,e="Human",t="AI"){const r=[];for(const s of n){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()}`);const i=s.name?`${s.name}, `:"",o=typeof s.content=="string"?s.content:JSON.stringify(s.content,null,2);r.push(`${a}: ${i}${o}`)}return r.join(`\n`)}let xp=class{getStore(){}run(e,t){return t()}};const Ta=Symbol.for("ls:tracing_async_local_storage"),kp=new xp;let Pp=class{getInstance(){return globalThis[Ta]??kp}initializeGlobalInstance(e){globalThis[Ta]===void 0&&(globalThis[Ta]=e)}};const Cp=new Pp;function Np(n=!1){const e=Cp.getInstance().getStore();if(!n&&e===void 0)throw new Error(`Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function xa(n){return typeof n=="function"&&"langsmith:traceable"in n}let ka;const $p=()=>{if(ka===void 0){const n=Re("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};ka=new ir(n)}return ka};class cr extends ur{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});const{exampleId:t,projectName:r,client:s,replicas:a}=e;this.projectName=r??io(),this.replicas=a,this.exampleId=t,this.client=s??$p();const i=cr.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;const r=new Set;for(;t.parent_run&&!(r.has(t.id)||(r.add(t.id),!t.parent_run));)t=t.parent_run;r.clear();const s=[t];for(;s.length>0;){const a=s.shift();!a||r.has(a.id)||(r.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){const t=this.runTreeMap.get(e);if(t)return new xe({...t,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return Np(!0)}catch{return}}}const Du=Symbol.for("ls:tracing_async_local_storage"),on=Symbol.for("lc:context_variables"),Lp=n=>{globalThis[Du]=n},lr=()=>globalThis[Du];let dr;function jp(){const n="default"in rt?rt.default:rt;return new n({autoStart:!0,concurrency:1})}function Mp(){return typeof dr>"u"&&(dr=jp()),dr}async function ce(n,e){if(e===!0){const t=lr();t!==void 0?await t.run(void 0,async()=>n()):await n()}else dr=Mp(),dr.add(async()=>{const t=lr();t!==void 0?await t.run(void 0,async()=>n()):await n()})}const Dp=n=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(t=>Re(t)==="true");function Uu(n){const e=lr();return e===void 0?void 0:e.getStore()?.[on]?.[n]}const Up=Symbol("lc:configure_hooks"),Fp=()=>Uu(Up)||[];function Bp(n){return n?Array.isArray(n)||"name"in n?{callbacks:n}:n:{}}class zp{setHandler(e){return this.setHandlers([e])}}class un{constructor(e,t,r,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:r}),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=>ce(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleCustomEvent(e,t,r,s,a){await Promise.all(this.handlers.map(i=>ce(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)))}}class qp extends un{getChild(e){const t=new Be(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=>ce(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw r}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>ce(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${r}`),t.raiseError)throw e}},t.awaitHandlers)))}}class Fu extends un{async handleLLMNewToken(e,t,r,s,a,i){await Promise.all(this.handlers.map(o=>ce(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,r,s,a){await Promise.all(this.handlers.map(i=>ce(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,r,s,a){await Promise.all(this.handlers.map(i=>ce(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)))}}class Hp extends un{getChild(e){const t=new Be(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,r,s,a){await Promise.all(this.handlers.map(i=>ce(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,r,s,a){await Promise.all(this.handlers.map(i=>ce(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=>ce(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>ce(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}}class Gp extends un{getChild(e){const t=new Be(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=>ce(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>ce(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}}class Be extends zp{constructor(e,t){super(),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"callback_manager"}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.handlers=t?.handlers??this.handlers,this.inheritableHandlers=t?.inheritableHandlers??this.inheritableHandlers,this.tags=t?.tags??this.tags,this.inheritableTags=t?.inheritableTags??this.inheritableTags,this.metadata=t?.metadata??this.metadata,this.inheritableMetadata=t?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,t,r=void 0,s=void 0,a=void 0,i=void 0,o=void 0,u=void 0){return Promise.all(t.map(async(c,l)=>{const d=l===0&&r?r:we();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return or(h)&&h._createRunForLLMStart(e,[c],d,this._parentRunId,a,this.tags,this.metadata,u),ce(async()=>{try{await h.handleLLMStart?.(e,[c],d,this._parentRunId,a,this.tags,this.metadata,u)}catch(f){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${f}`),h.raiseError)throw f}},h.awaitHandlers)})),new Fu(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,r=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)=>{const d=l===0&&r?r:we();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return or(h)&&h._createRunForChatModelStart(e,[c],d,this._parentRunId,a,this.tags,this.metadata,u),ce(async()=>{try{if(h.handleChatModelStart)await h.handleChatModelStart?.(e,[c],d,this._parentRunId,a,this.tags,this.metadata,u);else if(h.handleLLMStart){const f=Tp(c);await h.handleLLMStart?.(e,[f],d,this._parentRunId,a,this.tags,this.metadata,u)}}catch(f){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${f}`),h.raiseError)throw f}},h.awaitHandlers)})),new Fu(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,r=we(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreChain)return or(u)&&u._createRunForChainStart(e,t,r,this._parentRunId,this.tags,this.metadata,s,o),ce(async()=>{try{await u.handleChainStart?.(e,t,r,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 Hp(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,r=we(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreAgent)return or(u)&&u._createRunForToolStart(e,t,r,this._parentRunId,this.tags,this.metadata,o),ce(async()=>{try{await u.handleToolStart?.(e,t,r,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 Gp(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,r=we(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreRetriever)return or(u)&&u._createRunForRetrieverStart(e,t,r,this._parentRunId,this.tags,this.metadata,o),ce(async()=>{try{await u.handleRetrieverStart?.(e,t,r,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 qp(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,r,s,a){await Promise.all(this.handlers.map(i=>ce(async()=>{if(!i.ignoreCustomEvent)try{await i.handleCustomEvent?.(e,t,r,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(const r of e)this.addHandler(r,t)}addTags(e,t=!0){this.removeTags(e),this.tags.push(...e),t&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(t=>!e.includes(t)),this.inheritableTags=this.inheritableTags.filter(t=>!e.includes(t))}addMetadata(e,t=!0){this.metadata={...this.metadata,...e},t&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(const t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(e=[],t=!0){const r=new Be(this._parentRunId);for(const s of this.handlers){const a=this.inheritableHandlers.includes(s);r.addHandler(s,a)}for(const s of this.tags){const a=this.inheritableTags.includes(s);r.addTags([s],a)}for(const s of Object.keys(this.metadata)){const a=Object.keys(this.inheritableMetadata).includes(s);r.addMetadata({[s]:this.metadata[s]},a)}for(const s of e)r.handlers.filter(a=>a.name==="console_callback_handler").some(a=>a.name===s.name)||r.addHandler(s,t);return r}static fromHandlers(e){class t extends rr{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:we()}),Object.assign(this,e)}}const r=new this;return r.addHandler(new t),r}static configure(e,t,r,s,a,i,o){return this._configureSync(e,t,r,s,a,i,o)}static _configureSync(e,t,r,s,a,i,o){let u;(e||t)&&(Array.isArray(e)||!e?(u=new Be,u.setHandlers(e?.map(cn)??[],!0)):u=e,u=u.copy(Array.isArray(t)?t.map(cn):t?.handlers,!1));const c=Re("LANGCHAIN_VERBOSE")==="true"||o?.verbose,l=cr.getTraceableRunTree()?.tracingEnabled||Dp(),d=l||(Re("LANGCHAIN_TRACING")??!1);if(c||d){if(u||(u=new Be),c&&!u.handlers.some(h=>h.name===ju.prototype.name)){const h=new ju;u.addHandler(h,!0)}if(d&&!u.handlers.some(h=>h.name==="langchain_tracer")&&l){const h=new cr;u.addHandler(h,!0)}if(l){const h=cr.getTraceableRunTree();h&&u._parentRunId===void 0&&(u._parentRunId=h.id,u.handlers.find(p=>p.name==="langchain_tracer")?.updateFromRunTree(h))}}for(const{contextVar:h,inheritable:f=!0,handlerClass:p,envVar:m}of Fp()){const g=m&&Re(m)==="true"&&p;let y;const _=h!==void 0?Uu(h):void 0;_&&hh(_)?y=_:g&&(y=new p({})),y!==void 0&&(u||(u=new Be),u.handlers.some(b=>b.name===y.name)||u.addHandler(y,f))}return(r||s)&&u&&(u.addTags(r??[]),u.addTags(s??[],!1)),(a||i)&&u&&(u.addMetadata(a??{}),u.addMetadata(i??{},!1)),u}}function cn(n){return"name"in n?n:rr.fromMethods(n)}var Q;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{const a={};for(const i of s)a[i]=i;return a},n.getValidEnumValues=s=>{const a=n.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(const o of a)i[o]=s[o];return n.objectValues(i)},n.objectValues=s=>n.objectKeys(s).map(function(a){return s[a]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const a=[];for(const i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},n.find=(s,a)=>{for(const i of s)if(a(i))return i},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,a=" | "){return s.map(i=>typeof i=="string"?`\'${i}\'`:i).join(a)}n.joinValues=r,n.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(Q||(Q={}));var Bu;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(Bu||(Bu={}));const C=Q.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),lt=n=>{switch(typeof n){case"undefined":return C.undefined;case"string":return C.string;case"number":return Number.isNaN(n)?C.nan:C.number;case"boolean":return C.boolean;case"function":return C.function;case"bigint":return C.bigint;case"symbol":return C.symbol;case"object":return Array.isArray(n)?C.array:n===null?C.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?C.promise:typeof Map<"u"&&n instanceof Map?C.map:typeof Set<"u"&&n instanceof Set?C.set:typeof Date<"u"&&n instanceof Date?C.date:C.object;default:return C.unknown}},S=Q.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class nt extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(a){return a.message},r={_errors:[]},s=a=>{for(const 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)r._errors.push(t(i));else{let o=r,u=0;for(;u<i.path.length;){const 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),r}static assert(e){if(!(e instanceof nt))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Q.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},r=[];for(const s of this.issues)if(s.path.length>0){const a=s.path[0];t[a]=t[a]||[],t[a].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}nt.create=n=>new nt(n);const Pa=(n,e)=>{let t;switch(n.code){case S.invalid_type:n.received===C.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case S.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,Q.jsonStringifyReplacer)}`;break;case S.unrecognized_keys:t=`Unrecognized key(s) in object: ${Q.joinValues(n.keys,", ")}`;break;case S.invalid_union:t="Invalid input";break;case S.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Q.joinValues(n.options)}`;break;case S.invalid_enum_value:t=`Invalid enum value. Expected ${Q.joinValues(n.options)}, received \'${n.received}\'`;break;case S.invalid_arguments:t="Invalid function arguments";break;case S.invalid_return_type:t="Invalid function return type";break;case S.invalid_date:t="Invalid date";break;case S.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:Q.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case S.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case S.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case S.custom:t="Invalid input";break;case S.invalid_intersection_types:t="Intersection results could not be merged";break;case S.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case S.not_finite:t="Number must be finite";break;default:t=e.defaultError,Q.assertNever(n)}return{message:t}};let Vp=Pa;function Zp(){return Vp}const Wp=n=>{const{data:e,path:t,errorMaps:r,issueData:s}=n,a=[...t,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="";const u=r.filter(c=>!!c).slice().reverse();for(const c of u)o=c(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}};function T(n,e){const t=Zp(),r=Wp({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===Pa?void 0:Pa].filter(s=>!!s)});n.common.issues.push(r)}class Ne{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const s of t){if(s.status==="aborted")return q;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const s of t){const a=await s.key,i=await s.value;r.push({key:a,value:i})}return Ne.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const s of t){const{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)&&(r[a.value]=i.value)}return{status:e.value,value:r}}}const q=Object.freeze({status:"aborted"}),hr=n=>({status:"dirty",value:n}),ze=n=>({status:"valid",value:n}),zu=n=>n.status==="aborted",qu=n=>n.status==="dirty",Mt=n=>n.status==="valid",ln=n=>typeof Promise<"u"&&n instanceof Promise;var N;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(N||(N={}));class dt{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,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}}const Hu=(n,e)=>{if(Mt(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new nt(n.common.issues);return this._error=t,this._error}}};function V(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))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)=>{const{message:u}=n;return i.code==="invalid_enum_value"?{message:u??o.defaultError}:typeof o.data>"u"?{message:u??r??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:u??t??o.defaultError}},description:s}}class X{get description(){return this._def.description}_getType(e){return lt(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:lt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ne,ctx:{common:e.parent.common,data:e.data,parsedType:lt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ln(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:lt(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Hu(r,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:lt(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return Mt(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>Mt(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:lt(e)},s=this._parse({data:e,path:r.path,parent:r}),a=await(ln(s)?s:Promise.resolve(s));return Hu(r,a)}refine(e,t){const r=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,a)=>{const i=e(s),o=()=>a.addIssue({code:S.custom,...r(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((r,s)=>e(r)?!0:(s.addIssue(typeof t=="function"?t(r,s):t),!1))}_refinement(e){return new Ft({schema:this,typeName:A.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return pt.create(this,this._def)}nullable(){return Bt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Qe.create(this)}promise(){return pn.create(this,this._def)}or(e){return hn.create([this,e],this._def)}and(e){return fn.create(this,e,this._def)}transform(e){return new Ft({...V(this._def),schema:this,typeName:A.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new La({...V(this._def),innerType:this,defaultValue:t,typeName:A.ZodDefault})}brand(){return new _m({typeName:A.ZodBranded,type:this,...V(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new ja({...V(this._def),innerType:this,catchValue:t,typeName:A.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Ma.create(this,e)}readonly(){return Da.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Jp=/^c[^\\s-]{8,}$/i,Kp=/^[0-9a-z]+$/,Xp=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Qp=/^[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,Yp=/^[a-z0-9_-]{21}$/i,em=/^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/,tm=/^[-+]?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)?)??$/,rm=/^(?!\\.)(?!.*\\.\\.)([A-Z0-9_\'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i,nm="^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$";let Ca;const sm=/^(?:(?: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])$/,am=/^(?:(?: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])$/,im=/^(([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]))$/,om=/^(([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])$/,um=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,cm=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Gu="((\\\\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])))",lm=new RegExp(`^${Gu}$`);function Vu(n){let e="[0-5]\\\\d";n.precision?e=`${e}\\\\.\\\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\\\.\\\\d+)?`);const t=n.precision?"+":"?";return`([01]\\\\d|2[0-3]):[0-5]\\\\d(:${e})${t}`}function dm(n){return new RegExp(`^${Vu(n)}$`)}function hm(n){let e=`${Gu}T${Vu(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\\\d{2}:?\\\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function fm(n,e){return!!((e==="v4"||!e)&&sm.test(n)||(e==="v6"||!e)&&im.test(n))}function pm(n,e){if(!em.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function mm(n,e){return!!((e==="v4"||!e)&&am.test(n)||(e==="v6"||!e)&&om.test(n))}class ht extends X{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==C.string){const a=this._getOrReturnCtx(e);return T(a,{code:S.invalid_type,expected:C.string,received:a.parsedType}),q}const r=new Ne;let s;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),T(s,{code:S.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),T(s,{code:S.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="length"){const i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(s=this._getOrReturnCtx(e,s),i?T(s,{code:S.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&T(s,{code:S.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),r.dirty())}else if(a.kind==="email")rm.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"email",code:S.invalid_string,message:a.message}),r.dirty());else if(a.kind==="emoji")Ca||(Ca=new RegExp(nm,"u")),Ca.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"emoji",code:S.invalid_string,message:a.message}),r.dirty());else if(a.kind==="uuid")Qp.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"uuid",code:S.invalid_string,message:a.message}),r.dirty());else if(a.kind==="nanoid")Yp.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"nanoid",code:S.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid")Jp.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"cuid",code:S.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid2")Kp.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"cuid2",code:S.invalid_string,message:a.message}),r.dirty());else if(a.kind==="ulid")Xp.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"ulid",code:S.invalid_string,message:a.message}),r.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),T(s,{validation:"url",code:S.invalid_string,message:a.message}),r.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"regex",code:S.invalid_string,message:a.message}),r.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:S.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),r.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:S.invalid_string,validation:{startsWith:a.value},message:a.message}),r.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),T(s,{code:S.invalid_string,validation:{endsWith:a.value},message:a.message}),r.dirty()):a.kind==="datetime"?hm(a).test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{code:S.invalid_string,validation:"datetime",message:a.message}),r.dirty()):a.kind==="date"?lm.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{code:S.invalid_string,validation:"date",message:a.message}),r.dirty()):a.kind==="time"?dm(a).test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{code:S.invalid_string,validation:"time",message:a.message}),r.dirty()):a.kind==="duration"?tm.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"duration",code:S.invalid_string,message:a.message}),r.dirty()):a.kind==="ip"?fm(e.data,a.version)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"ip",code:S.invalid_string,message:a.message}),r.dirty()):a.kind==="jwt"?pm(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"jwt",code:S.invalid_string,message:a.message}),r.dirty()):a.kind==="cidr"?mm(e.data,a.version)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"cidr",code:S.invalid_string,message:a.message}),r.dirty()):a.kind==="base64"?um.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"base64",code:S.invalid_string,message:a.message}),r.dirty()):a.kind==="base64url"?cm.test(e.data)||(s=this._getOrReturnCtx(e,s),T(s,{validation:"base64url",code:S.invalid_string,message:a.message}),r.dirty()):Q.assertNever(a);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(s=>e.test(s),{validation:t,code:S.invalid_string,...N.errToObj(r)})}_addCheck(e){return new ht({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...N.errToObj(e)})}url(e){return this._addCheck({kind:"url",...N.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...N.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...N.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...N.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...N.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...N.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...N.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...N.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...N.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...N.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...N.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...N.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...N.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...N.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...N.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...N.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...N.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...N.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...N.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...N.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...N.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...N.errToObj(t)})}nonempty(e){return this.min(1,N.errToObj(e))}trim(){return new ht({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ht({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ht({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ht.create=n=>new ht({checks:[],typeName:A.ZodString,coerce:n?.coerce??!1,...V(n)});function gm(n,e){const t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=t>r?t:r,a=Number.parseInt(n.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return a%i/10**s}class fr extends X{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)!==C.number){const a=this._getOrReturnCtx(e);return T(a,{code:S.invalid_type,expected:C.number,received:a.parsedType}),q}let r;const s=new Ne;for(const a of this._def.checks)a.kind==="int"?Q.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),T(r,{code:S.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),T(r,{code:S.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)&&(r=this._getOrReturnCtx(e,r),T(r,{code:S.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?gm(e.data,a.value)!==0&&(r=this._getOrReturnCtx(e,r),T(r,{code:S.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),T(r,{code:S.not_finite,message:a.message}),s.dirty()):Q.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,N.toString(t))}gt(e,t){return this.setLimit("min",e,!1,N.toString(t))}lte(e,t){return this.setLimit("max",e,!0,N.toString(t))}lt(e,t){return this.setLimit("max",e,!1,N.toString(t))}setLimit(e,t,r,s){return new fr({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:N.toString(s)}]})}_addCheck(e){return new fr({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:N.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:N.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const 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"&&Q.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}fr.create=n=>new fr({checks:[],typeName:A.ZodNumber,coerce:n?.coerce||!1,...V(n)});class pr extends X{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)!==C.bigint)return this._getInvalidInput(e);let r;const s=new Ne;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),T(r,{code:S.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)&&(r=this._getOrReturnCtx(e,r),T(r,{code:S.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),T(r,{code:S.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):Q.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return T(t,{code:S.invalid_type,expected:C.bigint,received:t.parsedType}),q}gte(e,t){return this.setLimit("min",e,!0,N.toString(t))}gt(e,t){return this.setLimit("min",e,!1,N.toString(t))}lte(e,t){return this.setLimit("max",e,!0,N.toString(t))}lt(e,t){return this.setLimit("max",e,!1,N.toString(t))}setLimit(e,t,r,s){return new pr({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:N.toString(s)}]})}_addCheck(e){return new pr({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}pr.create=n=>new pr({checks:[],typeName:A.ZodBigInt,coerce:n?.coerce??!1,...V(n)});class Zu extends X{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==C.boolean){const r=this._getOrReturnCtx(e);return T(r,{code:S.invalid_type,expected:C.boolean,received:r.parsedType}),q}return ze(e.data)}}Zu.create=n=>new Zu({typeName:A.ZodBoolean,coerce:n?.coerce||!1,...V(n)});class dn extends X{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==C.date){const a=this._getOrReturnCtx(e);return T(a,{code:S.invalid_type,expected:C.date,received:a.parsedType}),q}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return T(a,{code:S.invalid_date}),q}const r=new Ne;let s;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),T(s,{code:S.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),r.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),T(s,{code:S.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),r.dirty()):Q.assertNever(a);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new dn({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:N.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:N.toString(t)})}get minDate(){let e=null;for(const 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(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}dn.create=n=>new dn({checks:[],coerce:n?.coerce||!1,typeName:A.ZodDate,...V(n)});class Wu extends X{_parse(e){if(this._getType(e)!==C.symbol){const r=this._getOrReturnCtx(e);return T(r,{code:S.invalid_type,expected:C.symbol,received:r.parsedType}),q}return ze(e.data)}}Wu.create=n=>new Wu({typeName:A.ZodSymbol,...V(n)});class Ju extends X{_parse(e){if(this._getType(e)!==C.undefined){const r=this._getOrReturnCtx(e);return T(r,{code:S.invalid_type,expected:C.undefined,received:r.parsedType}),q}return ze(e.data)}}Ju.create=n=>new Ju({typeName:A.ZodUndefined,...V(n)});class Ku extends X{_parse(e){if(this._getType(e)!==C.null){const r=this._getOrReturnCtx(e);return T(r,{code:S.invalid_type,expected:C.null,received:r.parsedType}),q}return ze(e.data)}}Ku.create=n=>new Ku({typeName:A.ZodNull,...V(n)});class Na extends X{constructor(){super(...arguments),this._any=!0}_parse(e){return ze(e.data)}}Na.create=n=>new Na({typeName:A.ZodAny,...V(n)});class Xu extends X{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ze(e.data)}}Xu.create=n=>new Xu({typeName:A.ZodUnknown,...V(n)});class ft extends X{_parse(e){const t=this._getOrReturnCtx(e);return T(t,{code:S.invalid_type,expected:C.never,received:t.parsedType}),q}}ft.create=n=>new ft({typeName:A.ZodNever,...V(n)});class Qu extends X{_parse(e){if(this._getType(e)!==C.undefined){const r=this._getOrReturnCtx(e);return T(r,{code:S.invalid_type,expected:C.void,received:r.parsedType}),q}return ze(e.data)}}Qu.create=n=>new Qu({typeName:A.ZodVoid,...V(n)});class Qe extends X{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==C.array)return T(t,{code:S.invalid_type,expected:C.array,received:t.parsedType}),q;if(s.exactLength!==null){const i=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(i||o)&&(T(t,{code:i?S.too_big:S.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}),r.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(T(t,{code:S.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(T(t,{code:S.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>s.type._parseAsync(new dt(t,i,t.path,o)))).then(i=>Ne.mergeArray(r,i));const a=[...t.data].map((i,o)=>s.type._parseSync(new dt(t,i,t.path,o)));return Ne.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new Qe({...this._def,minLength:{value:e,message:N.toString(t)}})}max(e,t){return new Qe({...this._def,maxLength:{value:e,message:N.toString(t)}})}length(e,t){return new Qe({...this._def,exactLength:{value:e,message:N.toString(t)}})}nonempty(e){return this.min(1,e)}}Qe.create=(n,e)=>new Qe({type:n,minLength:null,maxLength:null,exactLength:null,typeName:A.ZodArray,...V(e)});function Dt(n){if(n instanceof ae){const e={};for(const t in n.shape){const r=n.shape[t];e[t]=pt.create(Dt(r))}return new ae({...n._def,shape:()=>e})}else return n instanceof Qe?new Qe({...n._def,type:Dt(n.element)}):n instanceof pt?pt.create(Dt(n.unwrap())):n instanceof Bt?Bt.create(Dt(n.unwrap())):n instanceof St?St.create(n.items.map(e=>Dt(e))):n}class ae extends X{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=Q.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==C.object){const c=this._getOrReturnCtx(e);return T(c,{code:S.invalid_type,expected:C.object,received:c.parsedType}),q}const{status:r,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof ft&&this._def.unknownKeys==="strip"))for(const c in s.data)i.includes(c)||o.push(c);const u=[];for(const c of i){const l=a[c],d=s.data[c];u.push({key:{status:"valid",value:c},value:l._parse(new dt(s,d,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof ft){const c=this._def.unknownKeys;if(c==="passthrough")for(const 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:S.unrecognized_keys,keys:o}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const l of o){const d=s.data[l];u.push({key:{status:"valid",value:l},value:c._parse(new dt(s,d,s.path,l)),alwaysSet:l in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const c=[];for(const l of u){const d=await l.key,h=await l.value;c.push({key:d,value:h,alwaysSet:l.alwaysSet})}return c}).then(c=>Ne.mergeObjectSync(r,c)):Ne.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return N.errToObj,new ae({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{const s=this._def.errorMap?.(t,r).message??r.defaultError;return t.code==="unrecognized_keys"?{message:N.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new ae({...this._def,unknownKeys:"strip"})}passthrough(){return new ae({...this._def,unknownKeys:"passthrough"})}extend(e){return new ae({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ae({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:A.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ae({...this._def,catchall:e})}pick(e){const t={};for(const r of Q.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new ae({...this._def,shape:()=>t})}omit(e){const t={};for(const r of Q.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new ae({...this._def,shape:()=>t})}deepPartial(){return Dt(this)}partial(e){const t={};for(const r of Q.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new ae({...this._def,shape:()=>t})}required(e){const t={};for(const r of Q.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let a=this.shape[r];for(;a instanceof pt;)a=a._def.innerType;t[r]=a}return new ae({...this._def,shape:()=>t})}keyof(){return rc(Q.objectKeys(this.shape))}}ae.create=(n,e)=>new ae({shape:()=>n,unknownKeys:"strip",catchall:ft.create(),typeName:A.ZodObject,...V(e)}),ae.strictCreate=(n,e)=>new ae({shape:()=>n,unknownKeys:"strict",catchall:ft.create(),typeName:A.ZodObject,...V(e)}),ae.lazycreate=(n,e)=>new ae({shape:n,unknownKeys:"strip",catchall:ft.create(),typeName:A.ZodObject,...V(e)});class hn extends X{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;function s(a){for(const o of a)if(o.result.status==="valid")return o.result;for(const o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(o=>new nt(o.ctx.common.issues));return T(t,{code:S.invalid_union,unionErrors:i}),q}if(t.common.async)return Promise.all(r.map(async a=>{const 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;const i=[];for(const u of r){const 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;const o=i.map(u=>new nt(u));return T(t,{code:S.invalid_union,unionErrors:o}),q}}get options(){return this._def.options}}hn.create=(n,e)=>new hn({options:n,typeName:A.ZodUnion,...V(e)});function $a(n,e){const t=lt(n),r=lt(e);if(n===e)return{valid:!0,data:n};if(t===C.object&&r===C.object){const s=Q.objectKeys(e),a=Q.objectKeys(n).filter(o=>s.indexOf(o)!==-1),i={...n,...e};for(const o of a){const u=$a(n[o],e[o]);if(!u.valid)return{valid:!1};i[o]=u.data}return{valid:!0,data:i}}else if(t===C.array&&r===C.array){if(n.length!==e.length)return{valid:!1};const s=[];for(let a=0;a<n.length;a++){const i=n[a],o=e[a],u=$a(i,o);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===C.date&&r===C.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class fn extends X{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(a,i)=>{if(zu(a)||zu(i))return q;const o=$a(a.value,i.value);return o.valid?((qu(a)||qu(i))&&t.dirty(),{status:t.value,value:o.data}):(T(r,{code:S.invalid_intersection_types}),q)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([a,i])=>s(a,i)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}fn.create=(n,e,t)=>new fn({left:n,right:e,typeName:A.ZodIntersection,...V(t)});class St extends X{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==C.array)return T(r,{code:S.invalid_type,expected:C.array,received:r.parsedType}),q;if(r.data.length<this._def.items.length)return T(r,{code:S.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),q;!this._def.rest&&r.data.length>this._def.items.length&&(T(r,{code:S.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...r.data].map((i,o)=>{const u=this._def.items[o]||this._def.rest;return u?u._parse(new dt(r,i,r.path,o)):null}).filter(i=>!!i);return r.common.async?Promise.all(a).then(i=>Ne.mergeArray(t,i)):Ne.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new St({...this._def,rest:e})}}St.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new St({items:n,typeName:A.ZodTuple,rest:null,...V(e)})};class Yu extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==C.map)return T(r,{code:S.invalid_type,expected:C.map,received:r.parsedType}),q;const s=this._def.keyType,a=this._def.valueType,i=[...r.data.entries()].map(([o,u],c)=>({key:s._parse(new dt(r,o,r.path,[c,"key"])),value:a._parse(new dt(r,u,r.path,[c,"value"]))}));if(r.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const u of i){const 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{const o=new Map;for(const u of i){const 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}}}}Yu.create=(n,e,t)=>new Yu({valueType:e,keyType:n,typeName:A.ZodMap,...V(t)});class mr extends X{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==C.set)return T(r,{code:S.invalid_type,expected:C.set,received:r.parsedType}),q;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(T(r,{code:S.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(T(r,{code:S.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const a=this._def.valueType;function i(u){const c=new Set;for(const l of u){if(l.status==="aborted")return q;l.status==="dirty"&&t.dirty(),c.add(l.value)}return{status:t.value,value:c}}const o=[...r.data.values()].map((u,c)=>a._parse(new dt(r,u,r.path,c)));return r.common.async?Promise.all(o).then(u=>i(u)):i(o)}min(e,t){return new mr({...this._def,minSize:{value:e,message:N.toString(t)}})}max(e,t){return new mr({...this._def,maxSize:{value:e,message:N.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}mr.create=(n,e)=>new mr({valueType:n,minSize:null,maxSize:null,typeName:A.ZodSet,...V(e)});class ec extends X{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ec.create=(n,e)=>new ec({getter:n,typeName:A.ZodLazy,...V(e)});class tc extends X{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return T(t,{received:t.data,code:S.invalid_literal,expected:this._def.value}),q}return{status:"valid",value:e.data}}get value(){return this._def.value}}tc.create=(n,e)=>new tc({value:n,typeName:A.ZodLiteral,...V(e)});function rc(n,e){return new Ut({values:n,typeName:A.ZodEnum,...V(e)})}class Ut extends X{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),r=this._def.values;return T(t,{expected:Q.joinValues(r),received:t.parsedType,code:S.invalid_type}),q}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return T(t,{received:t.data,code:S.invalid_enum_value,options:r}),q}return ze(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Ut.create(e,{...this._def,...t})}exclude(e,t=this._def){return Ut.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}}Ut.create=rc;class nc extends X{_parse(e){const t=Q.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==C.string&&r.parsedType!==C.number){const s=Q.objectValues(t);return T(r,{expected:Q.joinValues(s),received:r.parsedType,code:S.invalid_type}),q}if(this._cache||(this._cache=new Set(Q.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=Q.objectValues(t);return T(r,{received:r.data,code:S.invalid_enum_value,options:s}),q}return ze(e.data)}get enum(){return this._def.values}}nc.create=(n,e)=>new nc({values:n,typeName:A.ZodNativeEnum,...V(e)});class pn extends X{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==C.promise&&t.common.async===!1)return T(t,{code:S.invalid_type,expected:C.promise,received:t.parsedType}),q;const r=t.parsedType===C.promise?t.data:Promise.resolve(t.data);return ze(r.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}pn.create=(n,e)=>new pn({type:n,typeName:A.ZodPromise,...V(e)});class Ft extends X{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===A.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:i=>{T(r,i),i.fatal?t.abort():t.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){const i=s.transform(r.data,a);if(r.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return q;const u=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return u.status==="aborted"?q:u.status==="dirty"||t.value==="dirty"?hr(u.value):u});{if(t.value==="aborted")return q;const o=this._def.schema._parseSync({data:i,path:r.path,parent:r});return o.status==="aborted"?q:o.status==="dirty"||t.value==="dirty"?hr(o.value):o}}if(s.type==="refinement"){const i=o=>{const u=s.refinement(o,a);if(r.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(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});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:r.data,path:r.path,parent:r}).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(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Mt(i))return q;const 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:r.data,path:r.path,parent:r}).then(i=>Mt(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:t.value,value:o})):q);Q.assertNever(s)}}Ft.create=(n,e,t)=>new Ft({schema:n,typeName:A.ZodEffects,effect:e,...V(t)}),Ft.createWithPreprocess=(n,e,t)=>new Ft({schema:e,effect:{type:"preprocess",transform:n},typeName:A.ZodEffects,...V(t)});class pt extends X{_parse(e){return this._getType(e)===C.undefined?ze(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}pt.create=(n,e)=>new pt({innerType:n,typeName:A.ZodOptional,...V(e)});class Bt extends X{_parse(e){return this._getType(e)===C.null?ze(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Bt.create=(n,e)=>new Bt({innerType:n,typeName:A.ZodNullable,...V(e)});class La extends X{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===C.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}La.create=(n,e)=>new La({innerType:n,typeName:A.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...V(e)});class ja extends X{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return ln(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new nt(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new nt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ja.create=(n,e)=>new ja({innerType:n,typeName:A.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...V(e)});class sc extends X{_parse(e){if(this._getType(e)!==C.nan){const r=this._getOrReturnCtx(e);return T(r,{code:S.invalid_type,expected:C.nan,received:r.parsedType}),q}return{status:"valid",value:e.data}}}sc.create=n=>new sc({typeName:A.ZodNaN,...V(n)});class _m extends X{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ma extends X{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?q:a.status==="dirty"?(t.dirty(),hr(a.value)):this._def.out._parseAsync({data:a.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?q:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,t){return new Ma({in:e,out:t,typeName:A.ZodPipeline})}}class Da extends X{_parse(e){const t=this._def.innerType._parse(e),r=s=>(Mt(s)&&(s.value=Object.freeze(s.value)),s);return ln(t)?t.then(s=>r(s)):r(t)}unwrap(){return this._def.innerType}}Da.create=(n,e)=>new Da({innerType:n,typeName:A.ZodReadonly,...V(e)});var A;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(A||(A={}));const ym=ht.create,ac=Na.create;ft.create,Qe.create;const bm=ae.create;hn.create,fn.create,St.create,Ut.create,pn.create,pt.create,Bt.create;const wm=Object.prototype.hasOwnProperty;function vm(n,e){return wm.call(n,e)}function Em(n){if(Array.isArray(n)){const t=new Array(n.length);for(let r=0;r<t.length;r++)t[r]=""+r;return t}if(Object.keys)return Object.keys(n);let e=[];for(let t in n)vm(n,t)&&e.push(t);return e}function zt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}function Ua(n){let e=0;const t=n.length;let r;for(;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}function Sm(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}function Fa(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(let t=0,r=n.length;t<r;t++)if(Fa(n[t]))return!0}else if(typeof n=="object"){const t=Em(n),r=t.length;for(var e=0;e<r;e++)if(Fa(n[t[e]]))return!0}}return!1}function ic(n,e){const t=[n];for(const r in e){const s=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof s<"u"&&t.push(`${r}: ${s}`)}return t.join(`\n`)}class Am extends Error{constructor(e,t,r,s,a){super(ic(e,{name:t,index:r,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:r}),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=ic(e,{name:t,index:r,operation:s,tree:a})}}const ie=Am,qt={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){let r=Ba(t,this.path);r&&(r=zt(r));const s=gr(t,{op:"remove",path:this.from}).removed;return gr(t,{op:"add",path:this.path,value:s}),{newDocument:t,removed:r}},copy:function(n,e,t){const r=Ba(t,this.from);return gr(t,{op:"add",path:this.path,value:zt(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:gn(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}};var Om={add:function(n,e,t){return Ua(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:qt.move,copy:qt.copy,test:qt.test,_get:qt._get};function Ba(n,e){if(e=="")return n;var t={op:"_get",path:e};return gr(n,t),t.value}function gr(n,e,t=!1,r=!0,s=!0,a=0){if(t&&(typeof t=="function"?t(e,0,n,e.path):za(e,0)),e.path===""){let i={newDocument:n};if(e.op==="add")return i.newDocument=e.value,i;if(e.op==="replace")return i.newDocument=e.value,i.removed=n,i;if(e.op==="move"||e.op==="copy")return i.newDocument=Ba(n,e.from),e.op==="move"&&(i.removed=n),i;if(e.op==="test"){if(i.test=gn(n,e.value),i.test===!1)throw new ie("Test operation failed","TEST_OPERATION_FAILED",a,e,n);return i.newDocument=n,i}else{if(e.op==="remove")return i.removed=n,i.newDocument=null,i;if(e.op==="_get")return e.value=n,i;if(t)throw new ie("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",a,e,n);return i}}else{r||(n=zt(n));const o=(e.path||"").split("/");let u=n,c=1,l=o.length,d,h,f;for(typeof t=="function"?f=t:f=za;;){if(h=o[c],h&&h.indexOf("~")!=-1&&(h=Sm(h)),s&&(h=="__proto__"||h=="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[h]===void 0?d=o.slice(0,c).join("/"):c==l-1&&(d=e.path),d!==void 0&&f(e,0,n,d)),c++,Array.isArray(u)){if(h==="-")h=u.length;else{if(t&&!Ua(h))throw new ie("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,n);Ua(h)&&(h=~~h)}if(c>=l){if(t&&e.op==="add"&&h>u.length)throw new ie("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",a,e,n);const p=Om[e.op].call(e,u,h,n);if(p.test===!1)throw new ie("Test operation failed","TEST_OPERATION_FAILED",a,e,n);return p}}else if(c>=l){const p=qt[e.op].call(e,u,h,n);if(p.test===!1)throw new ie("Test operation failed","TEST_OPERATION_FAILED",a,e,n);return p}if(u=u[h],t&&c<l&&(!u||typeof u!="object"))throw new ie("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",a,e,n)}}}function mn(n,e,t,r=!0,s=!0){if(t&&!Array.isArray(e))throw new ie("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=zt(n));const a=new Array(e.length);for(let i=0,o=e.length;i<o;i++)a[i]=gr(n,e[i],t,!0,s,i),n=a[i].newDocument;return a.newDocument=n,a}function za(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new ie("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(qt[n.op]){if(typeof n.path!="string")throw new ie("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new ie(\'Operation `path` property must start with "/"\',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new ie("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new ie("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&Fa(n.value))throw new ie("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var s=n.path.split("/").length,a=r.split("/").length;if(s!==a+1&&s!==a)throw new ie("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new ie("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var i={op:"_get",path:n.from,value:void 0},o=Im([i],t);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new ie("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new ie("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}function Im(n,e,t){try{if(!Array.isArray(n))throw new ie("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)mn(zt(e),zt(n),t||!0);else{t=t||za;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(s){if(s instanceof ie)return s;throw s}}function gn(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),s,a,i;if(t&&r){if(a=n.length,a!=e.length)return!1;for(s=a;s--!==0;)if(!gn(n[s],e[s]))return!1;return!0}if(t!=r)return!1;var o=Object.keys(n);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],!gn(n[i],e[i]))return!1;return!0}return n!==n&&e!==e}class Rm{getStore(){}run(e,t){return t()}enterWith(e){}}const Tm=new Rm,oc=Symbol.for("lc:child_config");class xm{getInstance(){return lr()??Tm}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[oc]}runWithConfig(e,t,r){const s=Be._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");let c;return u&&o?c=u.getRunTreeWithTracingConfig(o):r||(c=new xe({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[oc]:e}),i!==void 0&&i[on]!==void 0&&(c===void 0&&(c={}),c[on]=i[on]),a.run(c,t)}initializeGlobalInstance(e){lr()===void 0&&Lp(e)}}const mt=new xm,qa=25;async function Ge(n){return Be._configureSync(n?.callbacks,void 0,n?.tags,void 0,n?.metadata)}function uc(...n){const e={};for(const t of n.filter(r=>!!r))for(const r of Object.keys(t))if(r==="metadata")e[r]={...e[r],...t[r]};else if(r==="tags"){const s=e[r]??[];e[r]=[...new Set(s.concat(t[r]??[]))]}else if(r==="configurable")e[r]={...e[r],...t[r]};else if(r==="timeout")e.timeout===void 0?e.timeout=t.timeout:t.timeout!==void 0&&(e.timeout=Math.min(e.timeout,t.timeout));else if(r==="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(r==="callbacks"){const 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{const i=s.copy();for(const o of a)i.addHandler(cn(o),!0);e.callbacks=i}else if(a)if(!s)e.callbacks=a;else if(Array.isArray(s)){const i=a.copy();for(const o of s)i.addHandler(cn(o),!0);e.callbacks=i}else e.callbacks=new Be(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{const s=r;e[s]=t[s]??e[s]}return e}const km=new Set(["string","number","boolean"]);function Y(n){const e=mt.getRunnableConfig();let t={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){const{runId:r,runName:s,...a}=e;t=Object.entries(a).reduce((i,[o,u])=>(u!==void 0&&(i[o]=u),i),t)}if(n&&(t=Object.entries(n).reduce((r,[s,a])=>(a!==void 0&&(r[s]=a),r),t)),t?.configurable)for(const r of Object.keys(t.configurable))km.has(typeof t.configurable[r])&&!t.metadata?.[r]&&(t.metadata||(t.metadata={}),t.metadata[r]=t.configurable[r]);if(t.timeout!==void 0){if(t.timeout<=0)throw new Error("Timeout must be a positive number");const r=AbortSignal.timeout(t.timeout);t.signal!==void 0?"any"in AbortSignal&&(t.signal=AbortSignal.any([t.signal,r])):t.signal=r,delete t.timeout}return t}function be(n={},{callbacks:e,maxConcurrency:t,recursionLimit:r,runName:s,configurable:a,runId:i}={}){const o=Y(n);return e!==void 0&&(delete o.runName,o.callbacks=e),r!==void 0&&(o.recursionLimit=r),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 Ht(n){return n?{configurable:n.configurable,recursionLimit:n.recursionLimit,callbacks:n.callbacks,tags:n.tags,metadata:n.metadata,maxConcurrency:n.maxConcurrency,timeout:n.timeout,signal:n.signal}:void 0}async function gt(n,e){if(e===void 0)return n;let t;return Promise.race([n.catch(r=>{if(!e?.aborted)throw r}),new Promise((r,s)=>{t=()=>{s(new Error("Aborted"))},e.addEventListener("abort",t),e.aborted&&s(new Error("Aborted"))})]).finally(()=>e.removeEventListener("abort",t))}class $e extends ReadableStream{constructor(){super(...arguments),Object.defineProperty(this,"reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){const t=this.reader.cancel();this.reader.releaseLock(),await t}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){const t=e.getReader();return new $e({start(r){return s();function s(){return t.read().then(({done:a,value:i})=>{if(a){r.close();return}return r.enqueue(i),s()})}},cancel(){t.releaseLock()}})}static fromAsyncGenerator(e){return new $e({async pull(t){const{value:r,done:s}=await e.next();s&&t.close(),t.enqueue(r)},async cancel(t){await e.return(t)}})}}function cc(n,e=2){const t=Array.from({length:e},()=>[]);return t.map(async function*(s){for(;;)if(s.length===0){const a=await n.next();for(const i of t)i.push(a)}else{if(s[0].done)return;yield s.shift().value}})}function lc(n,e){if(Array.isArray(n)&&Array.isArray(e))return n.concat(e);if(typeof n=="string"&&typeof e=="string")return n+e;if(typeof n=="number"&&typeof e=="number")return n+e;if("concat"in n&&typeof n.concat=="function")return n.concat(e);if(typeof n=="object"&&typeof e=="object"){const t={...n};for(const[r,s]of Object.entries(e))r in t&&!Array.isArray(t[r])?t[r]=lc(t[r],s):t[r]=s;return t}else throw new Error(`Cannot concat ${typeof n} and ${typeof e}`)}class Gt{constructor(e){Object.defineProperty(this,"generator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"setup",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signal",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResult",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResultUsed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,r)=>{mt.runWithConfig(Ht(e.config),async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then(s=>t(void 0),r)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?mt.runWithConfig(Ht(this.config),this.signal?async()=>gt(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 Pm(n,e,t,r,...s){const a=new Gt({generator:e,startSetup:t,signal:r}),i=await a.setup;return{output:n(a,i,...s),setup:i}}class _t{constructor(e){Object.defineProperty(this,"ops",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),r=mn({},t);return new _r({ops:t,state:r[r.length-1].newDocument})}}class _r extends _t{constructor(e){super(e),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.state=e.state}concat(e){const t=this.ops.concat(e.ops),r=mn(this.state,e.ops);return new _r({ops:t,state:r[r.length-1].newDocument})}static fromRunLogPatch(e){const t=mn({},e.ops);return new _r({ops:e.ops,state:t[t.length-1].newDocument})}}const Cm=n=>n.name==="log_stream_tracer";async function dc(n,e){if(e==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:t}=n;if(["retriever","llm","prompt"].includes(n.run_type))return t;if(!(Object.keys(t).length===1&&t?.input===""))return t.input}async function hc(n,e){const{outputs:t}=n;return e==="original"||["retriever","llm","prompt"].includes(n.run_type)?t:t!==void 0&&Object.keys(t).length===1&&t?.output!==void 0?t.output:t}function Nm(n){return n!==void 0&&n.message!==void 0}class fc extends ur{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=$e.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;const t=e.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(r=r||t.find(s=>this.includeTags?.includes(s))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(r=r&&t.every(s=>!this.excludeTags?.includes(s))),r}async*tapOutputIterable(e,t){for await(const r of t){if(e!==this.rootId){const s=this.keyMapByRunId[e];s&&await this.writer.write(new _t({ops:[{op:"add",path:`/logs/${s}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new _t({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;const t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;const r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(r.inputs=await dc(e,this._schemaFormat)),await this.writer.write(new _t({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{const t=this.keyMapByRunId[e.id];if(t===void 0)return;const r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await dc(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await hc(e,this._schemaFormat)}),e.end_time!==void 0&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});const s=new _t({ops:r});await this.writer.write(s)}finally{if(e.id===this.rootId){const t=new _t({ops:[{op:"replace",path:"/final_output",value:await hc(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){const s=this.keyMapByRunId[e.id];if(s===void 0)return;const a=e.inputs.messages!==void 0;let i;a?Nm(r?.chunk)?i=r?.chunk:i=new an({id:`run-${e.id}`,content:t}):i=t;const o=new _t({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)}}class _n{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 _n({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}}function yn({name:n,serialized:e}){return n!==void 0?n:e?.name!==void 0?e.name:e?.id!==void 0&&Array.isArray(e?.id)?e.id[e.id.length-1]:"Unnamed"}const $m=n=>n.name==="event_stream_tracer";class Lm extends ur{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=$e.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const t=e.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(r=r||t.find(s=>this.includeTags?.includes(s))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(r=r&&t.every(s=>!this.excludeTags?.includes(s))),r}async*tapOutputIterable(e,t){const r=await t.next();if(r.done)return;const s=this.runInfoMap.get(e);if(s===void 0){yield r.value;return}function a(o,u){return o==="llm"&&typeof u=="string"?new _n({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{const 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,r.value)}},s),yield r.value;for await(const 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 r.value;for await(const o of t)yield o}}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){const r=this.tappedPromises.get(e.run_id);r!==void 0?r.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){const t=yn(e),r=e.inputs.messages!==void 0?"chat_model":"llm",s={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,s);const a=`on_${r}_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,r){const s=this.runInfoMap.get(e.id);let 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",r?.chunk===void 0?a=new an({content:t,id:`run-${e.id}`}):a=r.chunk.message;else if(s.runType==="llm")i="on_llm_stream",r?.chunk===void 0?a=new _n({text:t}):a=r.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){const t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let r;if(t===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const s=e.outputs?.generations;let a;if(t.runType==="chat_model"){for(const i of s??[]){if(a!==void 0)break;a=i[0]?.message}r="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??{}},r="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:r,data:{output:a,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){const t=yn(e),r=e.run_type??"chain",s={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type};let 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_${r}_start`,data:a,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},s)}async onChainEnd(e){const 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.`);const r=`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:r,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){const t=yn(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},r)}async onToolEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),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.`);const r=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){const t=yn(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){const 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,r){const s=this.runInfoMap.get(r);if(s===void 0)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:s.tags,metadata:s.metadata,data:t},s)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}}const jm=[400,401,402,403,404,405,406,407,409],Mm=n=>{if(n.message.startsWith("Cancel")||n.message.startsWith("AbortError")||n.name==="AbortError"||n?.code==="ECONNABORTED")throw n;const e=n?.response?.status??n?.status;if(e&&jm.includes(+e))throw n;if(n?.error?.code==="insufficient_quota"){const t=new Error(n?.message);throw t.name="InsufficientQuotaError",t}};class pc{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??Mm;const t="default"in rt?rt.default:rt;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>Hr(()=>e(...t).catch(r=>{throw r instanceof Error?r:new Error(r)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise((s,a)=>{e.signal?.addEventListener("abort",()=>{a(new Error("AbortError"))})})]):this.call(t,...r)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}}class mc extends ur{constructor({config:e,onStart:t,onEnd:r,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=r,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 Ha(n){return n?n.lc_runnable:!1}class Dm{constructor(e){Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let r=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0;const s=e.tags??[];return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(t)),this.includeTags!==void 0&&(r=r||s.some(a=>this.includeTags?.includes(a))),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(r=r&&s.every(a=>!this.excludeTags?.includes(a))),r}}function Ga(n){return n.replace(/[^a-zA-Z-_0-9]/g,"_")}const Um=["*","_","`"];function Fm(n){let e="";for(const[t,r]of Object.entries(n))e+=` classDef ${t} ${r};\n`;return e}function Bm(n,e,t){const{firstNode:r,lastNode:s,nodeColors:a,withStyles:i=!0,curveStyle:o="linear",wrapLabelNWords:u=9}=t??{};let c=i?`%%{init: {\'flowchart\': {\'curve\': \'${o}\'}}}%%\ngraph TD;\n`:`graph TD;\n`;if(i){const f="default",p={[f]:"{0}({1})"};r!==void 0&&(p[r]="{0}([{1}]):::first"),s!==void 0&&(p[s]="{0}([{1}]):::last");for(const[m,g]of Object.entries(n)){const y=g.name.split(":").pop()??"";let b=Um.some(v=>y.startsWith(v)&&y.endsWith(v))?`<p>${y}</p>`:y;Object.keys(g.metadata??{}).length&&(b+=`<hr/><small><em>${Object.entries(g.metadata??{}).map(([v,x])=>`${v} = ${x}`).join(`\n`)}</em></small>`);const E=(p[m]??p[f]).replace("{0}",Ga(m)).replace("{1}",b);c+=` ${E}\n`}}const l={};for(const f of e){const p=f.source.split(":"),m=f.target.split(":"),g=p.filter((y,_)=>y===m[_]).join(":");l[g]||(l[g]=[]),l[g].push(f)}const d=new Set;function h(f,p){const m=f.length===1&&f[0].source===f[0].target;if(p&&!m){const g=p.split(":").pop();if(d.has(g))throw new Error(`Found duplicate subgraph \'${g}\' -- this likely means that you\'re reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(g),c+=` subgraph ${g}\n`}for(const g of f){const{source:y,target:_,data:b,conditional:E}=g;let v="";if(b!==void 0){let x=b;const P=x.split(" ");P.length>u&&(x=Array.from({length:Math.ceil(P.length/u)},(O,J)=>P.slice(J*u,(J+1)*u).join(" ")).join(" <br> ")),v=E?` -. ${x} .-> `:` -- ${x} --> `}else v=E?" -.-> ":" --> ";c+=` ${Ga(y)}${v}${Ga(_)};\n`}for(const g in l)g.startsWith(`${p}:`)&&g!==p&&h(l[g],g);p&&!m&&(c+=` end\n`)}h(l[""]??[],"");for(const f in l)!f.includes(":")&&f!==""&&h(l[f],f);return i&&(c+=Fm(a??{})),c}async function zm(n,e){return qm(n,{...e,imageType:"png"})}async function qm(n,e){let t=e?.backgroundColor??"white";const r=e?.imageType,s=btoa(n);t!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(t)||(t=`!${t}`));const a=`https://mermaid.ink/img/${s}?bgColor=${t}&type=${r}`,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(`\n`));return await i.blob()}function bn(n,e,t){function r(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(n),e(o,u);for(const 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}const s=t?.Parent??Object;class a extends s{}Object.defineProperty(a,"name",{value:n});function i(o){var u;const c=t?.Parent?new a:this;r(c,o),(u=c._zod).deferred??(u.deferred=[]);for(const l of c._zod.deferred)l();return c}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:o=>t?.Parent&&o instanceof t.Parent?!0:o?._zod?.traits?.has(n)}),Object.defineProperty(i,"name",{value:n}),i}class wn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Hm={};function Va(n){return Hm}function Gm(n){const e=Object.values(n).filter(r=>typeof r=="number");return Object.entries(n).filter(([r,s])=>e.indexOf(+r)===-1).map(([r,s])=>s)}function Vm(n,e){return typeof e=="bigint"?e.toString():e}const Zm=Error.captureStackTrace?Error.captureStackTrace:(...n)=>{};function vn(n,e,t){const r=new n._zod.constr(e??n._zod.def);return(!e||t?.parent)&&(r._zod.parent=n),r}function Wm(n){return{}}function Za(n,e=0){for(let t=e;t<n.issues.length;t++)if(n.issues[t]?.continue!==!0)return!0;return!1}function En(n){return typeof n=="string"?n:n?.message}function Wa(n,e,t){const r={...n,path:n.path??[]};if(!n.message){const s=En(n.inst?._zod.def?.error?.(n))??En(e?.error?.(n))??En(t.customError?.(n))??En(t.localeError?.(n))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}const gc=(n,e)=>{n.name="$ZodError",Object.defineProperty(n,"_zod",{value:n._zod,enumerable:!1}),Object.defineProperty(n,"issues",{value:e,enumerable:!1}),Object.defineProperty(n,"message",{get(){return JSON.stringify(e,Vm,2)},enumerable:!0}),Object.defineProperty(n,"toString",{value:()=>n.message,enumerable:!1})},Jm=bn("$ZodError",gc),Ja=bn("$ZodError",gc,{Parent:Error}),Km=(n=>(e,t,r,s)=>{const a=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:t,issues:[]},a);if(i instanceof Promise)throw new wn;if(i.issues.length){const o=new(s?.Err??n)(i.issues.map(u=>Wa(u,a,Va())));throw Zm(o,s?.callee),o}return i.value})(Ja),Xm=(n=>(e,t,r)=>{const s=r?{...r,async:!1}:{async:!1},a=e._zod.run({value:t,issues:[]},s);if(a instanceof Promise)throw new wn;return a.issues.length?{success:!1,error:new(n??Jm)(a.issues.map(i=>Wa(i,s,Va())))}:{success:!0,data:a.value}})(Ja),Qm=(n=>async(e,t,r)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let a=e._zod.run({value:t,issues:[]},s);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new n(a.issues.map(i=>Wa(i,s,Va())))}:{success:!0,data:a.value}})(Ja),Ym={major:4,minor:0,patch:0},eg=bn("$ZodType",(n,e)=>{var t;n??(n={}),n._zod.def=e,n._zod.bag=n._zod.bag||{},n._zod.version=Ym;const r=[...n._zod.def.checks??[]];n._zod.traits.has("$ZodCheck")&&r.unshift(n);for(const s of r)for(const a of s._zod.onattach)a(n);if(r.length===0)(t=n._zod).deferred??(t.deferred=[]),n._zod.deferred?.push(()=>{n._zod.run=n._zod.parse});else{const s=(a,i,o)=>{let u=Za(a),c;for(const l of i){if(l._zod.def.when){if(!l._zod.def.when(a))continue}else if(u)continue;const d=a.issues.length,h=l._zod.check(a);if(h instanceof Promise&&o?.async===!1)throw new wn;if(c||h instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await h,a.issues.length!==d&&(u||(u=Za(a,d)))});else{if(a.issues.length===d)continue;u||(u=Za(a,d))}}return c?c.then(()=>a):a};n._zod.run=(a,i)=>{const o=n._zod.parse(a,i);if(o instanceof Promise){if(i.async===!1)throw new wn;return o.then(u=>s(u,r,i))}return s(o,r,i)}}n["~standard"]={validate:s=>{try{const a=Xm(n,s);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return Qm(n,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),tg=bn("$ZodNever",(n,e)=>{eg.init(n,e),n._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:n}),t)});class _c{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const r=t[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const 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){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function rg(){return new _c}const yt=rg();function ng(n,e){return new n({type:"never",...Wm()})}class yc{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??yt,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 r;const 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;const o={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,o);const u=e._zod.toJSONSchema?.();if(u)o.schema=u;else{const d={...t,schemaPath:[...t.schemaPath,e],path:t.path},h=e._zod.parent;if(h)o.ref=h,this.process(h,d),this.seen.get(h).isParent=!0;else{const f=o.schema;switch(s.type){case"string":{const p=f;p.type="string";const{minimum:m,maximum:g,format:y,patterns:_,contentEncoding:b}=e._zod.bag;if(typeof m=="number"&&(p.minLength=m),typeof g=="number"&&(p.maxLength=g),y&&(p.format=a[y]??y,p.format===""&&delete p.format),b&&(p.contentEncoding=b),_&&_.size>0){const E=[..._];E.length===1?p.pattern=E[0].source:E.length>1&&(o.schema.allOf=[...E.map(v=>({...this.target==="draft-7"?{type:"string"}:{},pattern:v.source}))])}break}case"number":{const p=f,{minimum:m,maximum:g,format:y,multipleOf:_,exclusiveMaximum:b,exclusiveMinimum:E}=e._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof E=="number"&&(p.exclusiveMinimum=E),typeof m=="number"&&(p.minimum=m,typeof E=="number"&&(E>=m?delete p.minimum:delete p.exclusiveMinimum)),typeof b=="number"&&(p.exclusiveMaximum=b),typeof g=="number"&&(p.maximum=g,typeof b=="number"&&(b<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof _=="number"&&(p.multipleOf=_);break}case"boolean":{const p=f;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const p=f,{minimum:m,maximum:g}=e._zod.bag;typeof m=="number"&&(p.minItems=m),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(s.element,{...d,path:[...d.path,"items"]});break}case"object":{const p=f;p.type="object",p.properties={};const m=s.shape;for(const _ in m)p.properties[_]=this.process(m[_],{...d,path:[...d.path,"properties",_]});const g=new Set(Object.keys(m)),y=new Set([...g].filter(_=>{const b=s.shape[_]._zod;return this.io==="input"?b.optin===void 0:b.optout===void 0}));y.size>0&&(p.required=Array.from(y)),s.catchall?._zod.def.type==="never"?p.additionalProperties=!1:s.catchall?s.catchall&&(p.additionalProperties=this.process(s.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{const p=f;p.anyOf=s.options.map((m,g)=>this.process(m,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{const p=f,m=this.process(s.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(s.right,{...d,path:[...d.path,"allOf",1]}),y=b=>"allOf"in b&&Object.keys(b).length===1,_=[...y(m)?m.allOf:[m],...y(g)?g.allOf:[g]];p.allOf=_;break}case"tuple":{const p=f;p.type="array";const m=s.items.map((_,b)=>this.process(_,{...d,path:[...d.path,"prefixItems",b]}));if(this.target==="draft-2020-12"?p.prefixItems=m:p.items=m,s.rest){const _=this.process(s.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?p.items=_:p.additionalItems=_}s.rest&&(p.items=this.process(s.rest,{...d,path:[...d.path,"items"]}));const{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(p.minItems=g),typeof y=="number"&&(p.maxItems=y);break}case"record":{const p=f;p.type="object",p.propertyNames=this.process(s.keyType,{...d,path:[...d.path,"propertyNames"]}),p.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":{const p=f,m=Gm(s.entries);m.every(g=>typeof g=="number")&&(p.type="number"),m.every(g=>typeof g=="string")&&(p.type="string"),p.enum=m;break}case"literal":{const p=f,m=[];for(const 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");m.push(Number(g))}else m.push(g);if(m.length!==0)if(m.length===1){const g=m[0];p.type=g===null?"null":typeof g,p.const=g}else m.every(g=>typeof g=="number")&&(p.type="number"),m.every(g=>typeof g=="string")&&(p.type="string"),m.every(g=>typeof g=="boolean")&&(p.type="string"),m.every(g=>g===null)&&(p.type="null"),p.enum=m;break}case"file":{const p=f,m={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:_}=e._zod.bag;g!==void 0&&(m.minLength=g),y!==void 0&&(m.maxLength=y),_?_.length===1?(m.contentMediaType=_[0],Object.assign(p,m)):p.anyOf=_.map(b=>({...m,contentMediaType:b})):Object.assign(p,m);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const p=this.process(s.innerType,d);f.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,d),o.ref=s.innerType;break}case"success":{const p=f;p.type="boolean";break}case"default":{this.process(s.innerType,d),o.ref=s.innerType,f.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,d),o.ref=s.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,d),o.ref=s.innerType;let p;try{p=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const p=f,m=e._zod.pattern;if(!m)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=m.source;break}case"pipe":{const p=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(p,d),o.ref=p;break}case"readonly":{this.process(s.innerType,d),o.ref=s.innerType,f.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":{const p=e._zod.innerType;this.process(p,d),o.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),this.io==="input"&&le(e)&&(delete o.schema.examples,delete o.schema.default),this.io==="input"&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,this.seen.get(e).schema}emit(e,t){const r={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.");const a=l=>{const d=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const m=r.external.registry.get(l[0])?.id,g=r.external.uri??(_=>_);if(m)return{ref:g(m)};const y=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=y,{defId:y,ref:`${g("__shared")}#/${d}/${y}`}}if(l[1]===s)return{ref:"#"};const f=`#/${d}/`,p=l[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:f+p}},i=l=>{if(l[1].schema.$ref)return;const d=l[1],{ref:h,defId:f}=a(l);d.def={...d.schema},f&&(d.defId=f);const p=d.schema;for(const m in p)delete p[m];p.$ref=h};if(r.cycles==="throw")for(const l of this.seen.entries()){const d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>\n\nSet the \\`cycles\\` parameter to \\`"ref"\\` to resolve cyclical schemas with defs.`)}for(const l of this.seen.entries()){const d=l[1];if(e===l[0]){i(l);continue}if(r.external){const f=r.external.registry.get(l[0])?.id;if(e!==l[0]&&f){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&r.reused==="ref"){i(l);continue}}const o=(l,d)=>{const h=this.seen.get(l),f=h.def??h.schema,p={...f};if(h.ref===null)return;const m=h.ref;if(h.ref=null,m){o(m,d);const g=this.seen.get(m).schema;g.$ref&&d.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(g)):(Object.assign(f,g),Object.assign(f,p))}h.isParent||this.override({zodSchema:l,jsonSchema:f,path:h.path??[]})};for(const l of[...this.seen.entries()].reverse())o(l[0],{target:this.target});const 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}`),r.external?.uri){const l=r.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");u.$id=r.external.uri(l)}Object.assign(u,s.def);const c=r.external?.defs??{};for(const l of this.seen.entries()){const d=l[1];d.def&&d.defId&&(c[d.defId]=d.def)}r.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.")}}}function bc(n,e){if(n instanceof _c){const r=new yc(e),s={};for(const o of n._idmap.entries()){const[u,c]=o;r.process(c)}const a={},i={registry:n,uri:e?.uri,defs:s};for(const o of n._idmap.entries()){const[u,c]=o;a[u]=r.emit(c,{...e,external:i})}if(Object.keys(s).length>0){const o=r.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[o]:s}}return{schemas:a}}const t=new yc(e);return t.process(n),t.emit(n,e)}function le(n,e){const t=e??{seen:new Set};if(t.seen.has(n))return!1;t.seen.add(n);const s=n._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 le(s.element,t);case"object":{for(const a in s.shape)if(le(s.shape[a],t))return!0;return!1}case"union":{for(const a of s.options)if(le(a,t))return!0;return!1}case"intersection":return le(s.left,t)||le(s.right,t);case"tuple":{for(const a of s.items)if(le(a,t))return!0;return!!(s.rest&&le(s.rest,t))}case"record":return le(s.keyType,t)||le(s.valueType,t);case"map":return le(s.keyType,t)||le(s.valueType,t);case"set":return le(s.valueType,t);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return le(s.innerType,t);case"lazy":return le(s.getter(),t);case"default":return le(s.innerType,t);case"prefault":return le(s.innerType,t);case"custom":return!1;case"transform":return!0;case"pipe":return le(s.in,t)||le(s.out,t);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${s.type}`)}const sg=Symbol("Let zodToJsonSchema decide on which parser to use"),ag={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"},ig=n=>({...ag,...n}),og=n=>{const e=ig(n),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(([r,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function wc(n,e,t,r){r?.errorMessages&&t&&(n.errorMessage={...n.errorMessage,[e]:t})}function re(n,e,t,r,s){n[e]=t,wc(n,e,r,s)}const vc=(n,e)=>{let t=0;for(;t<n.length&&t<e.length&&n[t]===e[t];t++);return[(n.length-t).toString(),...e.slice(t)].join("/")};function Le(n){if(n.target!=="openAi")return{};const e=[...n.basePath,n.definitionPath,n.openAiAnyTypeName];return n.flags.hasReferencedOpenAiAnyType=!0,{$ref:n.$refStrategy==="relative"?vc(e,n.currentPath):e.join("/")}}function ug(n,e){const t={type:"array"};return n.type?._def&&n.type?._def?.typeName!==A.ZodAny&&(t.items=ee(n.type._def,{...e,currentPath:[...e.currentPath,"items"]})),n.minLength&&re(t,"minItems",n.minLength.value,n.minLength.message,e),n.maxLength&&re(t,"maxItems",n.maxLength.value,n.maxLength.message,e),n.exactLength&&(re(t,"minItems",n.exactLength.value,n.exactLength.message,e),re(t,"maxItems",n.exactLength.value,n.exactLength.message,e)),t}function cg(n,e){const t={type:"integer",format:"int64"};if(!n.checks)return t;for(const r of n.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?re(t,"minimum",r.value,r.message,e):re(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),re(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?re(t,"maximum",r.value,r.message,e):re(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),re(t,"maximum",r.value,r.message,e));break;case"multipleOf":re(t,"multipleOf",r.value,r.message,e);break}return t}function lg(){return{type:"boolean"}}function Ec(n,e){return ee(n.type._def,e)}const dg=(n,e)=>ee(n.innerType._def,e);function Sc(n,e,t){const r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,a)=>Sc(n,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return hg(n,e)}}const hg=(n,e)=>{const t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(const r of n.checks)switch(r.kind){case"min":re(t,"minimum",r.value,r.message,e);break;case"max":re(t,"maximum",r.value,r.message,e);break}return t};function fg(n,e){return{...ee(n.innerType._def,e),default:n.defaultValue()}}function pg(n,e){return e.effectStrategy==="input"?ee(n.schema._def,e):Le(e)}function mg(n){return{type:"string",enum:Array.from(n.values)}}const gg=n=>"type"in n&&n.type==="string"?!1:"allOf"in n;function _g(n,e){const t=[ee(n.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ee(n.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a);let r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return t.forEach(a=>{if(gg(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(r=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...u}=a;i=u}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}function yg(n,e){const t=typeof n.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(n.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[n.value]}:{type:t==="bigint"?"integer":t,const:n.value}}let Ka;const Ve={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:()=>(Ka===void 0&&(Ka=RegExp("^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$","u")),Ka),uuid:/^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/};function Ac(n,e){const t={type:"string"};if(n.checks)for(const r of n.checks)switch(r.kind){case"min":re(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e);break;case"max":re(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Ze(t,"email",r.message,e);break;case"format:idn-email":Ze(t,"idn-email",r.message,e);break;case"pattern:zod":Se(t,Ve.email,r.message,e);break}break;case"url":Ze(t,"uri",r.message,e);break;case"uuid":Ze(t,"uuid",r.message,e);break;case"regex":Se(t,r.regex,r.message,e);break;case"cuid":Se(t,Ve.cuid,r.message,e);break;case"cuid2":Se(t,Ve.cuid2,r.message,e);break;case"startsWith":Se(t,RegExp(`^${Xa(r.value,e)}`),r.message,e);break;case"endsWith":Se(t,RegExp(`${Xa(r.value,e)}$`),r.message,e);break;case"datetime":Ze(t,"date-time",r.message,e);break;case"date":Ze(t,"date",r.message,e);break;case"time":Ze(t,"time",r.message,e);break;case"duration":Ze(t,"duration",r.message,e);break;case"length":re(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e),re(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"includes":{Se(t,RegExp(Xa(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&Ze(t,"ipv4",r.message,e),r.version!=="v4"&&Ze(t,"ipv6",r.message,e);break}case"base64url":Se(t,Ve.base64url,r.message,e);break;case"jwt":Se(t,Ve.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&Se(t,Ve.ipv4Cidr,r.message,e),r.version!=="v4"&&Se(t,Ve.ipv6Cidr,r.message,e);break}case"emoji":Se(t,Ve.emoji(),r.message,e);break;case"ulid":{Se(t,Ve.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ze(t,"binary",r.message,e);break}case"contentEncoding:base64":{re(t,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{Se(t,Ve.base64,r.message,e);break}}break}case"nanoid":Se(t,Ve.nanoid,r.message,e)}return t}function Xa(n,e){return e.patternStrategy==="escape"?wg(n):n}const bg=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function wg(n){let e="";for(let t=0;t<n.length;t++)bg.has(n[t])||(e+="\\\\"),e+=n[t];return e}function Ze(n,e,t,r){n.format||n.anyOf?.some(s=>s.format)?(n.anyOf||(n.anyOf=[]),n.format&&(n.anyOf.push({format:n.format,...n.errorMessage&&r.errorMessages&&{errorMessage:{format:n.errorMessage.format}}}),delete n.format,n.errorMessage&&(delete n.errorMessage.format,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):re(n,"format",e,t,r)}function Se(n,e,t,r){n.pattern||n.allOf?.some(s=>s.pattern)?(n.allOf||(n.allOf=[]),n.pattern&&(n.allOf.push({pattern:n.pattern,...n.errorMessage&&r.errorMessages&&{errorMessage:{pattern:n.errorMessage.pattern}}}),delete n.pattern,n.errorMessage&&(delete n.errorMessage.pattern,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.allOf.push({pattern:Oc(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):re(n,"pattern",Oc(e,r),t,r)}function Oc(n,e){if(!e.applyRegexFlags||!n.flags)return n.source;const t={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},r=t.i?n.source.toLowerCase():n.source;let s="",a=!1,i=!1,o=!1;for(let u=0;u<r.length;u++){if(a){s+=r[u],a=!1;continue}if(t.i){if(i){if(r[u].match(/[a-z]/)){o?(s+=r[u],s+=`${r[u-2]}-${r[u]}`.toUpperCase(),o=!1):r[u+1]==="-"&&r[u+2]?.match(/[a-z]/)?(s+=r[u],o=!0):s+=`${r[u]}${r[u].toUpperCase()}`;continue}}else if(r[u].match(/[a-z]/)){s+=`[${r[u]}${r[u].toUpperCase()}]`;continue}}if(t.m){if(r[u]==="^"){s+=`(^|(?<=[\\r\n]))`;continue}else if(r[u]==="$"){s+=`($|(?=[\\r\n]))`;continue}}if(t.s&&r[u]==="."){s+=i?`${r[u]}\\r\n`:`[${r[u]}\\r\n]`;continue}s+=r[u],r[u]==="\\\\"?a=!0:i&&r[u]==="]"?i=!1:!i&&r[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`),n.source}return s}function Ic(n,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"&&n.keyType?._def.typeName===A.ZodEnum)return{type:"object",required:n.keyType._def.values,properties:n.keyType._def.values.reduce((r,s)=>({...r,[s]:ee(n.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??Le(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const t={type:"object",additionalProperties:ee(n.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(n.keyType?._def.typeName===A.ZodString&&n.keyType._def.checks?.length){const{type:r,...s}=Ac(n.keyType._def,e);return{...t,propertyNames:s}}else{if(n.keyType?._def.typeName===A.ZodEnum)return{...t,propertyNames:{enum:n.keyType._def.values}};if(n.keyType?._def.typeName===A.ZodBranded&&n.keyType._def.type._def.typeName===A.ZodString&&n.keyType._def.type._def.checks?.length){const{type:r,...s}=Ec(n.keyType._def,e);return{...t,propertyNames:s}}}return t}function vg(n,e){if(e.mapStrategy==="record")return Ic(n,e);const t=ee(n.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Le(e),r=ee(n.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Le(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,r],minItems:2,maxItems:2}}}function Eg(n){const e=n.values,r=Object.keys(n.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),s=Array.from(new Set(r.map(a=>typeof a)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function Sg(n){return n.target==="openAi"?void 0:{not:Le({...n,currentPath:[...n.currentPath,"not"]})}}function Ag(n){return n.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Sn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Og(n,e){if(e.target==="openApi3")return Rc(n,e);const t=n.options instanceof Map?Array.from(n.options.values()):n.options;if(t.every(r=>r._def.typeName in Sn&&(!r._def.checks||!r._def.checks.length))){const r=t.reduce((s,a)=>{const i=Sn[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:r.length>1?r:r[0]}}else if(t.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=t.reduce((s,a)=>{const 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(r.length===t.length){const s=r.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(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((r,s)=>[...r,...s._def.values.filter(a=>!r.includes(a))],[])};return Rc(n,e)}const Rc=(n,e)=>{const t=(n.options instanceof Map?Array.from(n.options.values()):n.options).map((r,s)=>ee(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return t.length?{anyOf:t}:void 0};function Ig(n,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(n.innerType._def.typeName)&&(!n.innerType._def.checks||!n.innerType._def.checks.length))return e.target==="openApi3"?{type:Sn[n.innerType._def.typeName],nullable:!0}:{type:[Sn[n.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const r=ee(n.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const t=ee(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function Rg(n,e){const t={type:"number"};if(!n.checks)return t;for(const r of n.checks)switch(r.kind){case"int":t.type="integer",wc(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?re(t,"minimum",r.value,r.message,e):re(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),re(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?re(t,"maximum",r.value,r.message,e):re(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),re(t,"maximum",r.value,r.message,e));break;case"multipleOf":re(t,"multipleOf",r.value,r.message,e);break}return t}function Tg(n,e){const t=e.target==="openAi",r={type:"object",properties:{}},s=[],a=n.shape();for(const o in a){let u=a[o];if(u===void 0||u._def===void 0)continue;let c=kg(u);c&&t&&(u._def.typeName==="ZodOptional"&&(u=u._def.innerType),u.isNullable()||(u=u.nullable()),c=!1);const l=ee(u._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});l!==void 0&&(r.properties[o]=l,c||s.push(o))}s.length&&(r.required=s);const i=xg(n,e);return i!==void 0&&(r.additionalProperties=i),r}function xg(n,e){if(n.catchall._def.typeName!=="ZodNever")return ee(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(n.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function kg(n){try{return n.isOptional()}catch{return!0}}const Pg=(n,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return ee(n.innerType._def,e);const t=ee(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:Le(e)},t]}:Le(e)},Cg=(n,e)=>{if(e.pipeStrategy==="input")return ee(n.in._def,e);if(e.pipeStrategy==="output")return ee(n.out._def,e);const t=ee(n.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=ee(n.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(s=>s!==void 0)}};function Ng(n,e){return ee(n.type._def,e)}function $g(n,e){const r={type:"array",uniqueItems:!0,items:ee(n.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return n.minSize&&re(r,"minItems",n.minSize.value,n.minSize.message,e),n.maxSize&&re(r,"maxItems",n.maxSize.value,n.maxSize.message,e),r}function Lg(n,e){return n.rest?{type:"array",minItems:n.items.length,items:n.items.map((t,r)=>ee(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:ee(n.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:n.items.length,maxItems:n.items.length,items:n.items.map((t,r)=>ee(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function jg(n){return{not:Le(n)}}function Mg(n){return Le(n)}const Dg=(n,e)=>ee(n.innerType._def,e),Ug=(n,e,t)=>{switch(e){case A.ZodString:return Ac(n,t);case A.ZodNumber:return Rg(n,t);case A.ZodObject:return Tg(n,t);case A.ZodBigInt:return cg(n,t);case A.ZodBoolean:return lg();case A.ZodDate:return Sc(n,t);case A.ZodUndefined:return jg(t);case A.ZodNull:return Ag(t);case A.ZodArray:return ug(n,t);case A.ZodUnion:case A.ZodDiscriminatedUnion:return Og(n,t);case A.ZodIntersection:return _g(n,t);case A.ZodTuple:return Lg(n,t);case A.ZodRecord:return Ic(n,t);case A.ZodLiteral:return yg(n,t);case A.ZodEnum:return mg(n);case A.ZodNativeEnum:return Eg(n);case A.ZodNullable:return Ig(n,t);case A.ZodOptional:return Pg(n,t);case A.ZodMap:return vg(n,t);case A.ZodSet:return $g(n,t);case A.ZodLazy:return()=>n.getter()._def;case A.ZodPromise:return Ng(n,t);case A.ZodNaN:case A.ZodNever:return Sg(t);case A.ZodEffects:return pg(n,t);case A.ZodAny:return Le(t);case A.ZodUnknown:return Mg(t);case A.ZodDefault:return fg(n,t);case A.ZodBranded:return Ec(n,t);case A.ZodReadonly:return Dg(n,t);case A.ZodCatch:return dg(n,t);case A.ZodPipeline:return Cg(n,t);case A.ZodFunction:case A.ZodVoid:case A.ZodSymbol:return;default:return(r=>{})()}};function ee(n,e,t=!1){const r=e.seen.get(n);if(e.override){const o=e.override?.(n,e,r,t);if(o!==sg)return o}if(r&&!t){const o=Fg(r,e);if(o!==void 0)return o}const s={def:n,path:e.currentPath,jsonSchema:void 0};e.seen.set(n,s);const a=Ug(n,n.typeName,e),i=typeof a=="function"?ee(a(),e):a;if(i&&Bg(n,e,i),e.postProcess){const o=e.postProcess(i,n,e);return s.jsonSchema=i,o}return s.jsonSchema=i,i}const Fg=(n,e)=>{switch(e.$refStrategy){case"root":return{$ref:n.path.join("/")};case"relative":return{$ref:vc(e.currentPath,n.path)};case"none":case"seen":return n.path.length<e.currentPath.length&&n.path.every((t,r)=>e.currentPath[r]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Le(e)):e.$refStrategy==="seen"?Le(e):void 0}},Bg=(n,e,t)=>(n.description&&(t.description=n.description,e.markdownDescription&&(t.markdownDescription=n.description)),t),zg=(n,e)=>{const t=og(e);let r;const s=e?.name,a=ee(n._def,t,!1)??Le(t);t.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[t.openAiAnyTypeName]||(r[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}));const i=s===void 0?r?{...a,[t.definitionPath]:r}:a:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,s].join("/"),[t.definitionPath]:{...r,[s]:a}};return t.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};function st(n){if(typeof n!="object"||n===null)return!1;const e=n;if(!("_zod"in e))return!1;const t=e._zod;return typeof t=="object"&&t!==null&&"def"in t}function bt(n){if(typeof n!="object"||n===null)return!1;const e=n;if(!("_def"in e)||"_zod"in e)return!1;const t=e._def;return typeof t=="object"&&t!=null&&"typeName"in t}function qg(n){return!n||typeof n!="object"||Array.isArray(n)?!1:!!(st(n)||bt(n))}async function Hg(n,e){if(st(n))return Km(n,e);if(bt(n))return n.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Gg(n){if(st(n))return yt.get(n)?.description;if(bt(n)||"description"in n&&typeof n.description=="string")return n.description}function Vg(n){return qg(n)?bt(n)?n._def.typeName==="ZodString":st(n)?n._zod.def.type==="string":!1:!1}function yr(n){return st(n)?typeof n=="object"&&n!==null&&"_zod"in n&&typeof n._zod=="object"&&n._zod!==null&&"def"in n._zod&&typeof n._zod.def=="object"&&n._zod.def!==null&&"type"in n._zod.def&&n._zod.def.type==="object":!1}function Tc(n){return st(n)?typeof n=="object"&&n!==null&&"_zod"in n&&typeof n._zod=="object"&&n._zod!==null&&"def"in n._zod&&typeof n._zod.def=="object"&&n._zod.def!==null&&"type"in n._zod.def&&n._zod.def.type==="array":!1}function Qa(n,e=!1){if(bt(n))return n.strict();if(yr(n)){const t=n._zod.def.shape;if(e)for(const[a,i]of Object.entries(n._zod.def.shape)){if(yr(i)){const u=Qa(i,e);t[a]=u}else if(Tc(i)){let u=i._zod.def.element;yr(u)&&(u=Qa(u,e)),t[a]=vn(i,{...i._zod.def,element:u})}else t[a]=i;const o=yt.get(i);o&&yt.add(t[a],o)}const r=vn(n,{...n._zod.def,shape:t,catchall:ng(tg)}),s=yt.get(n);return s&&yt.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Zg(n){return bt(n)&&"typeName"in n._def&&n._def.typeName==="ZodEffects"}function Wg(n){return st(n)&&n._zod.def.type==="pipe"}function br(n,e=!1){if(bt(n))return Zg(n)?br(n._def.schema,e):n;if(st(n)){let t=n;if(Wg(n)&&(t=br(n._zod.def.in,e)),e){if(yr(t)){const s=t._zod.def.shape;for(const[a,i]of Object.entries(t._zod.def.shape))s[a]=br(i,e);t=vn(t,{...t._zod.def,shape:s})}else if(Tc(t)){const s=br(t._zod.def.element,e);t=vn(t,{...t._zod.def,element:s})}}const r=yt.get(n);return r&&yt.add(t,r),t}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Jg(n){if(st(n)){const e=br(n,!0);if(yr(e)){const t=Qa(e,!0);return bc(t)}else return bc(n)}return bt(n)?zg(n):n}function Kg(n,e){if(n!==void 0&&!er(n))return n;if(Ha(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 Xg(n){return Ha(n.data)?{type:"runnable",data:{id:n.data.lc_id,name:n.data.getName()}}:{type:"schema",data:{...Jg(n.data.schema),title:n.data.name}}}class An{constructor(e){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach((t,r)=>{e[t.id]=er(t.id)?r:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...Xg(t)})),edges:this.edges.map(t=>{const r={source:e[t.source],target:e[t.target]};return typeof t.data<"u"&&(r.data=t.data),typeof t.conditional<"u"&&(r.conditional=t.conditional),r})}}addNode(e,t,r){if(t!==void 0&&this.nodes[t]!==void 0)throw new Error(`Node with id ${t} already exists`);const s=t??we(),a={id:s,data:e,name:Kg(t,e),metadata:r};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,r,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`);const a={source:e.id,target:t.id,data:r,conditional:s};return this.edges.push(a),a}firstNode(){return xc(this)}lastNode(){return kc(this)}extend(e,t=""){let r=t;Object.values(e.nodes).map(c=>c.id).every(er)&&(r="");const a=c=>r?`${r}:${c}`:c;Object.entries(e.nodes).forEach(([c,l])=>{this.nodes[a(c)]={...l,id:a(c)}});const i=e.edges.map(c=>({...c,source:a(c.source),target:a(c.target)}));this.edges=[...this.edges,...i];const 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(){const e=this.firstNode();e&&xc(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&kc(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map(s=>[s.id,s.name])),t=new Map;Object.values(e).forEach(s=>{t.set(s,(t.get(s)||0)+1)});const r=s=>{const a=e[s];return er(s)&&t.get(a)===1?a:s};return new An({nodes:Object.fromEntries(Object.entries(this.nodes).map(([s,a])=>[r(s),{...a,id:r(s)}])),edges:this.edges.map(s=>({...s,source:r(s.source),target:r(s.target)}))})}drawMermaid(e){const{withStyles:t,curveStyle:r,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 Bm(i.nodes,i.edges,{firstNode:o?.id,lastNode:u?.id,withStyles:t,curveStyle:r,nodeColors:s,wrapLabelNWords:a})}async drawMermaidPng(e){const t=this.drawMermaid(e);return zm(t,{backgroundColor:e?.backgroundColor})}}function xc(n,e=[]){const t=new Set(n.edges.filter(s=>!e.includes(s.source)).map(s=>s.target)),r=[];for(const s of Object.values(n.nodes))!e.includes(s.id)&&!t.has(s.id)&&r.push(s);return r.length===1?r[0]:void 0}function kc(n,e=[]){const t=new Set(n.edges.filter(s=>!e.includes(s.target)).map(s=>s.source)),r=[];for(const s of Object.values(n.nodes))!e.includes(s.id)&&!t.has(s.id)&&r.push(s);return r.length===1?r[0]:void 0}function Qg(n){const e=new TextEncoder,t=new ReadableStream({async start(r){for await(const s of n)r.enqueue(e.encode(`event: data\ndata: ${JSON.stringify(s)}\n\n`));r.enqueue(e.encode(`event: end\n\n`)),r.close()}});return $e.fromReadableStream(t)}function Pc(n){return typeof n=="object"&&n!==null&&typeof n[Symbol.iterator]=="function"&&typeof n.next=="function"}const Yg=n=>n!=null&&typeof n=="object"&&"next"in n&&typeof n.next=="function";function Ya(n){return typeof n=="object"&&n!==null&&typeof n[Symbol.asyncIterator]=="function"}function*Cc(n,e){for(;;){const{value:t,done:r}=mt.runWithConfig(Ht(n),e.next.bind(e),!0);if(r)break;yield t}}async function*ei(n,e){const t=e[Symbol.asyncIterator]();for(;;){const{value:r,done:s}=await mt.runWithConfig(Ht(n),t.next.bind(e),!0);if(s)break;yield r}}function fe(n,e){return n&&!Array.isArray(n)&&!(n instanceof Date)&&typeof n=="object"?n:{[e]:n}}class Ae extends Et{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(e){const t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}bind(e){return new At({bound:this,kwargs:e,config:{}})}map(){return new On({bound:this})}withRetry(e){return new Nc({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new At({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new t_({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(Y);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");const r=Object.fromEntries(Object.entries(e).filter(([s])=>s!=="runId"));return Array.from({length:t},(s,a)=>Y(a===0?e:r))}return Array.from({length:t},()=>Y(e))}async batch(e,t,r){const s=this._getOptionsList(t??{},e.length),a=s[0]?.maxConcurrency??r?.maxConcurrency,i=new pc({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(r?.returnExceptions)return l;throw l}}));return Promise.all(o)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const r=Y(t),s=new Gt({generator:this._streamIterator(e,r),config:r});return await s.setup,$e.fromAsyncGenerator(s)}_separateRunnableConfigFromCallOptions(e){let t;e===void 0?t=Y(e):t=Y({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});const r={...e};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[t,r]}async _callWithConfig(e,t,r){const s=Y(r),i=await(await Ge(s))?.handleChainStart(this.toJSON(),fe(t,"input"),s.runId,s?.runType,void 0,void 0,s?.runName??this.getName());delete s.runId;let o;try{const u=e.call(this,t,s,i);o=await gt(u,r?.signal)}catch(u){throw await i?.handleChainError(u),u}return await i?.handleChainEnd(fe(o,"output")),o}async _batchWithConfig(e,t,r,s){const a=this._getOptionsList(r??{},t.length),i=await Promise.all(a.map(Ge)),o=await Promise.all(i.map(async(c,l)=>{const d=await c?.handleChainStart(this.toJSON(),fe(t[l],"input"),a[l].runId,a[l].runType,void 0,void 0,a[l].runName??this.getName());return delete a[l].runId,d}));let u;try{const c=e.call(this,t,a,o,s);u=await gt(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(fe(u,"output")))),u}_concatOutputChunks(e,t){return lc(e,t)}async*_transformStreamWithConfig(e,t,r){let s,a=!0,i,o=!0;const u=Y(r),c=await Ge(u),l=this;async function*d(){for await(const f of e){if(a)if(s===void 0)s=f;else try{s=l._concatOutputChunks(s,f)}catch{s=void 0,a=!1}yield f}}let h;try{const f=await Pm(t.bind(this),d(),async()=>c?.handleChainStart(this.toJSON(),{input:""},u.runId,u.runType,void 0,void 0,u.runName??this.getName()),r?.signal,u);delete u.runId,h=f.setup;const p=h?.handlers.find($m);let m=f.output;p!==void 0&&h!==void 0&&(m=p.tapOutputIterable(h.runId,m));const g=h?.handlers.find(Cm);g!==void 0&&h!==void 0&&(m=g.tapOutputIterable(h.runId,m));for await(const y of m)if(yield y,o)if(i===void 0)i=y;else try{i=this._concatOutputChunks(i,y)}catch{i=void 0,o=!1}}catch(f){throw await h?.handleChainError(f,void 0,void 0,void 0,{inputs:fe(s,"input")}),f}await h?.handleChainEnd(i??{},void 0,void 0,void 0,{inputs:fe(s,"input")})}getGraph(e){const t=new An,r=t.addNode({name:`${this.getName()}Input`,schema:ac()}),s=t.addNode(this),a=t.addNode({name:`${this.getName()}Output`,schema:ac()});return t.addEdge(r,s),t.addEdge(s,a),t}pipe(e){return new Ot({first:this,last:It(e)})}pick(e){return this.pipe(new n_(e))}assign(e){return this.pipe(new r_(new wr({steps:e})))}async*transform(e,t){let r;for await(const s of e)r===void 0?r=s:r=this._concatOutputChunks(r,s);yield*this._streamIterator(r,Y(t))}async*streamLog(e,t,r){const s=new fc({...r,autoClose:!1,_schemaFormat:"original"}),a=Y(t);yield*this._streamLog(e,s,a)}async*_streamLog(e,t,r){const{callbacks:s}=r;if(s===void 0)r.callbacks=[t];else if(Array.isArray(s))r.callbacks=s.concat([t]);else{const u=s.copy();u.addHandler(t,!0),r.callbacks=u}const a=this.stream(e,r);async function i(){try{const u=await a;for await(const c of u){const l=new _t({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await t.writer.write(l)}}finally{await t.writer.close()}}const o=i();try{for await(const u of t)yield u}finally{await o}}streamEvents(e,t,r){let s;if(t.version==="v1")s=this._streamEventsV1(e,t,r);else if(t.version==="v2")s=this._streamEventsV2(e,t,r);else throw new Error(\'Only versions "v1" and "v2" of the schema are currently supported.\');return t.encoding==="text/event-stream"?Qg(s):$e.fromAsyncGenerator(s)}async*_streamEventsV2(e,t,r){const s=new Lm({...r,autoClose:!1}),a=Y(t),i=a.runId??we();a.runId=i;const o=a.callbacks;if(o===void 0)a.callbacks=[s];else if(Array.isArray(o))a.callbacks=o.concat(s);else{const p=o.copy();p.addHandler(s,!0),a.callbacks=p}const u=new AbortController,c=this;async function l(){let p,m=null;try{t?.signal?"any"in AbortSignal?p=AbortSignal.any([u.signal,t.signal]):(p=t.signal,m=()=>{u.abort()},t.signal.addEventListener("abort",m,{once:!0})):p=u.signal;const g=await c.stream(e,{...a,signal:p}),y=s.tapOutputIterable(i,g);for await(const _ of y)if(u.signal.aborted)break}finally{await s.finish(),p&&m&&p.removeEventListener("abort",m)}}const d=l();let h=!1,f;try{for await(const p of s){if(!h){p.data.input=e,h=!0,f=p.run_id,yield p;continue}p.run_id===f&&p.event.endsWith("_end")&&p.data?.input&&delete p.data.input,yield p}}finally{u.abort(),await d}}async*_streamEventsV1(e,t,r){let s,a=!1;const i=Y(t),o=i.tags??[],u=i.metadata??{},c=i.runName??this.getName(),l=new fc({...r,autoClose:!1,_schemaFormat:"streaming_events"}),d=new Dm({...r}),h=this._streamLog(e,l,i);for await(const p of h){if(s?s=s.concat(p):s=_r.fromRunLogPatch(p),s.state===void 0)throw new Error(\'Internal error: "streamEvents" state is missing. Please open a bug report.\');if(!a){a=!0;const _={...s.state},b={run_id:_.id,event:`on_${_.type}_start`,name:c,tags:o,metadata:u,data:{input:e}};d.includeEvent(b,_.type)&&(yield b)}const m=p.ops.filter(_=>_.path.startsWith("/logs/")).map(_=>_.path.split("/")[2]),g=[...new Set(m)];for(const _ of g){let b,E={};const v=s.state.logs[_];if(v.end_time===void 0?v.streamed_output.length>0?b="stream":b="start":b="end",b==="start")v.inputs!==void 0&&(E.input=v.inputs);else if(b==="end")v.inputs!==void 0&&(E.input=v.inputs),E.output=v.final_output;else if(b==="stream"){const x=v.streamed_output.length;if(x!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${x} instead. Encountered in: "${v.name}"`);E={chunk:v.streamed_output[0]},v.streamed_output=[]}yield{event:`on_${v.type}_${b}`,name:v.name,run_id:v.id,tags:v.tags,metadata:v.metadata,data:E}}const{state:y}=s;if(y.streamed_output.length>0){const _=y.streamed_output.length;if(_!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${_} instead. Encountered in: "${y.name}"`);const b={chunk:y.streamed_output[0]};y.streamed_output=[];const E={event:`on_${y.type}_stream`,run_id:y.id,tags:o,metadata:u,name:c,data:b};d.includeEvent(E,y.type)&&(yield E)}}const f=s?.state;if(f!==void 0){const p={event:`on_${f.type}_end`,name:c,run_id:f.id,tags:o,metadata:u,data:{output:f.final_output}};d.includeEvent(p,f.type)&&(yield p)}}static isRunnable(e){return Ha(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new At({bound:this,config:{},configFactories:[s=>({callbacks:[new mc({config:s,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return s_(this,e)}}class At extends Ae{static lc_name(){return"RunnableBinding"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"configFactories",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){const t=uc(this.config,...e);return uc(t,...this.configFactories?await Promise.all(this.configFactories.map(async r=>await r(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 Nc({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(Y(t),this.kwargs))}async batch(e,t,r){const s=Array.isArray(t)?await Promise.all(t.map(async a=>this._mergeConfig(Y(a),this.kwargs))):await this._mergeConfig(Y(t),this.kwargs);return this.bound.batch(e,s,r)}_concatOutputChunks(e,t){return this.bound._concatOutputChunks(e,t)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(Y(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(Y(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(Y(t),this.kwargs))}streamEvents(e,t,r){const s=this,a=async function*(){yield*s.bound.streamEvents(e,{...await s._mergeConfig(Y(t),s.kwargs),version:t.version},r)};return $e.fromAsyncGenerator(a())}static isRunnableBinding(e){return e.bound&&Ae.isRunnable(e.bound)}withListeners({onStart:e,onEnd:t,onError:r}){return new At({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[s=>({callbacks:[new mc({config:s,onStart:e,onEnd:t,onError:r})]})]})}}class On extends Ae{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 On({bound:this.bound.bind(e)})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _invoke(e,t,r){return this.bound.batch(e,be(t,{callbacks:r?.getChild()}))}withListeners({onStart:e,onEnd:t,onError:r}){return new On({bound:this.bound.withListeners({onStart:e,onEnd:t,onError:r})})}}class Nc extends At{static lc_name(){return"RunnableRetry"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"maxAttemptNumber",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:()=>{}}),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,r){const s=e>1?`retry:attempt:${e}`:void 0;return be(t,{callbacks:r?.getChild(s)})}async _invoke(e,t,r){return Hr(s=>super.invoke(e,this._patchConfigForRetry(s,t,r)),{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,r,s){const a={};try{await Hr(async i=>{const o=e.map((h,f)=>f).filter(h=>a[h.toString()]===void 0||a[h.toString()]instanceof Error),u=o.map(h=>e[h]),c=o.map(h=>this._patchConfigForRetry(i,t?.[h],r?.[h])),l=await super.batch(u,c,{...s,returnExceptions:!0});let d;for(let h=0;h<l.length;h+=1){const f=l[h],p=o[h];f instanceof Error&&d===void 0&&(d=f,d.input=u[h]),a[p.toString()]=f}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,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}}class Ot extends Ae{static lc_name(){return"RunnableSequence"}constructor(e){super(e),Object.defineProperty(this,"first",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"middle",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"last",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitSequenceTags",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){const r=Y(t),a=await(await Ge(r))?.handleChainStart(this.toJSON(),fe(e,"input"),r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;let i=e,o;try{const u=[this.first,...this.middle];for(let c=0;c<u.length;c+=1){const d=u[c].invoke(i,be(r,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`)}));i=await gt(d,t?.signal)}if(t?.signal?.aborted)throw new Error("Aborted");o=await this.last.invoke(i,be(r,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(u){throw await a?.handleChainError(u),u}return await a?.handleChainEnd(fe(o,"output")),o}async batch(e,t,r){const s=this._getOptionsList(t??{},e.length),a=await Promise.all(s.map(Ge)),i=await Promise.all(a.map(async(u,c)=>{const l=await u?.handleChainStart(this.toJSON(),fe(e[c],"input"),s[c].runId,void 0,void 0,void 0,s[c].runName);return delete s[c].runId,l}));let o=e;try{for(let u=0;u<this.steps.length;u+=1){const l=this.steps[u].batch(o,i.map((d,h)=>{const f=d?.getChild(this.omitSequenceTags?void 0:`seq:step:${u+1}`);return be(s[h],{callbacks:f})}),r);o=await gt(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(fe(o,"output")))),o}_concatOutputChunks(e,t){return this.last._concatOutputChunks(e,t)}async*_streamIterator(e,t){const r=await Ge(t),{runId:s,...a}=t??{},i=await r?.handleChainStart(this.toJSON(),fe(e,"input"),s,void 0,void 0,void 0,a?.runName),o=[this.first,...this.middle,this.last];let u=!0,c;async function*l(){yield e}try{let d=o[0].transform(l(),be(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let h=1;h<o.length;h+=1)d=await o[h].transform(d,be(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${h+1}`)}));for await(const h of d)if(t?.signal?.throwIfAborted(),yield h,u)if(c===void 0)c=h;else try{c=this._concatOutputChunks(c,h)}catch{c=void 0,u=!1}}catch(d){throw await i?.handleChainError(d),d}await i?.handleChainEnd(fe(c,"output"))}getGraph(e){const t=new An;let r=null;return this.steps.forEach((s,a)=>{const i=s.getGraph(e);a!==0&&i.trimFirstNode(),a!==this.steps.length-1&&i.trimLastNode(),t.extend(i);const o=i.firstNode();if(!o)throw new Error(`Runnable ${s} has no first node`);r&&t.addEdge(r,o),r=i.lastNode()}),t}pipe(e){return Ot.isRunnableSequence(e)?new Ot({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new Ot({first:this.first,middle:[...this.middle,this.last],last:It(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&Ae.isRunnable(e)}static from([e,...t],r){let s={};return typeof r=="string"?s.name=r:r!==void 0&&(s=r),new Ot({...s,first:It(e),middle:t.slice(0,-1).map(It),last:It(t[t.length-1])})}}class wr extends Ae{static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"steps",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.steps={};for(const[t,r]of Object.entries(e.steps))this.steps[t]=It(r)}static from(e){return new wr({steps:e})}async invoke(e,t){const r=Y(t),a=await(await Ge(r))?.handleChainStart(this.toJSON(),{input:e},r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;const i={};try{const o=Object.entries(this.steps).map(async([u,c])=>{i[u]=await c.invoke(e,be(r,{callbacks:a?.getChild(`map:key:${u}`)}))});await gt(Promise.all(o),t?.signal)}catch(o){throw await a?.handleChainError(o),o}return await a?.handleChainEnd(i),i}async*_transform(e,t,r){const s={...this.steps},a=cc(e,Object.keys(s).length),i=new Map(Object.entries(s).map(([o,u],c)=>{const l=u.transform(a[c],be(r,{callbacks:t?.getChild(`map:key:${o}`)}));return[o,l.next().then(d=>({key:o,gen:l,result:d}))]}));for(;i.size;){const o=Promise.race(i.values()),{key:u,result:c,gen:l}=await gt(o,r?.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*r(){yield e}const s=Y(t),a=new Gt({generator:this.transform(r(),s),config:s});return await a.setup,$e.fromAsyncGenerator(a)}}class ti extends Ae{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}),!xa(e.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,t){const[r]=this._getOptionsList(t??{},1),s=await Ge(r),a=this.func(be(r,{callbacks:s}),e);return gt(a,r?.signal)}async*_streamIterator(e,t){const[r]=this._getOptionsList(t??{},1),s=await this.invoke(e,t);if(Ya(s)){for await(const a of s)r?.signal?.throwIfAborted(),yield a;return}if(Yg(s)){for(;;){r?.signal?.throwIfAborted();const a=s.next();if(a.done)break;yield a.value}return}yield s}static from(e){return new ti({func:e})}}function e_(n){if(xa(n))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn\'t happen.")}class In extends Ae{static lc_name(){return"RunnableLambda"}constructor(e){if(xa(e.func))return ti.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}),e_(e.func),this.func=e.func}static from(e){return new In({func:e})}async _invoke(e,t,r){return new Promise((s,a)=>{const i=be(t,{callbacks:r?.getChild(),recursionLimit:(t?.recursionLimit??qa)-1});mt.runWithConfig(Ht(i),async()=>{try{let o=await this.func(e,{...i});if(o&&Ae.isRunnable(o)){if(t?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(e,{...i,recursionLimit:(i.recursionLimit??qa)-1})}else if(Ya(o)){let u;for await(const c of ei(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(Pc(o)){let u;for(const c of Cc(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,r){let s;for await(const o of e)if(s===void 0)s=o;else try{s=this._concatOutputChunks(s,o)}catch{s=o}const a=be(r,{callbacks:t?.getChild(),recursionLimit:(r?.recursionLimit??qa)-1}),i=await new Promise((o,u)=>{mt.runWithConfig(Ht(a),async()=>{try{const c=await this.func(s,{...a,config:a});o(c)}catch(c){u(c)}})});if(i&&Ae.isRunnable(i)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");const o=await i.stream(s,a);for await(const u of o)yield u}else if(Ya(i))for await(const o of ei(a,i))r?.signal?.throwIfAborted(),yield o;else if(Pc(i))for(const o of Cc(a,i))r?.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*r(){yield e}const s=Y(t),a=new Gt({generator:this.transform(r(),s),config:s});return await a.setup,$e.fromAsyncGenerator(a)}}class t_ extends Ae{static lc_name(){return"RunnableWithFallbacks"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"runnable",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fallbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,t){const r=Y(t),s=await Ge(r),{runId:a,...i}=r,o=await s?.handleChainStart(this.toJSON(),fe(e,"input"),a,void 0,void 0,void 0,i?.runName),u=be(i,{callbacks:o?.getChild()});return await mt.runWithConfig(u,async()=>{let l;for(const d of this.runnables()){r?.signal?.throwIfAborted();try{const h=await d.invoke(e,u);return await o?.handleChainEnd(fe(h,"output")),h}catch(h){l===void 0&&(l=h)}}throw l===void 0?new Error("No error stored at end of fallback."):(await o?.handleChainError(l),l)})}async*_streamIterator(e,t){const r=Y(t),s=await Ge(r),{runId:a,...i}=r,o=await s?.handleChainStart(this.toJSON(),fe(e,"input"),a,void 0,void 0,void 0,i?.runName);let u,c;for(const d of this.runnables()){r?.signal?.throwIfAborted();const h=be(i,{callbacks:o?.getChild()});try{const f=await d.stream(e,h);c=ei(h,f);break}catch(f){u===void 0&&(u=f)}}if(c===void 0){const d=u??new Error("No error stored at end of fallback.");throw await o?.handleChainError(d),d}let l;try{for await(const 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(fe(l,"output"))}async batch(e,t,r){if(r?.returnExceptions)throw new Error("Not implemented.");const s=this._getOptionsList(t??{},e.length),a=await Promise.all(s.map(u=>Ge(u))),i=await Promise.all(a.map(async(u,c)=>{const l=await u?.handleChainStart(this.toJSON(),fe(e[c],"input"),s[c].runId,void 0,void 0,void 0,s[c].runName);return delete s[c].runId,l}));let o;for(const u of this.runnables()){s[0].signal?.throwIfAborted();try{const c=await u.batch(e,i.map((l,d)=>be(s[d],{callbacks:l?.getChild()})),r);return await Promise.all(i.map((l,d)=>l?.handleChainEnd(fe(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.")}}function It(n){if(typeof n=="function")return new In({func:n});if(Ae.isRunnable(n))return n;if(!Array.isArray(n)&&typeof n=="object"){const e={};for(const[t,r]of Object.entries(n))e[t]=It(r);return new wr({steps:e})}else throw new Error(`Expected a Runnable, function or object.\nInstead got an unsupported type.`)}class r_ extends Ae{static lc_name(){return"RunnableAssign"}constructor(e){e instanceof wr&&(e={mapper:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mapper=e.mapper}async invoke(e,t){const r=await this.mapper.invoke(e,t);return{...e,...r}}async*_transform(e,t,r){const s=this.mapper.getStepsKeys(),[a,i]=cc(e),o=this.mapper.transform(i,be(r,{callbacks:t?.getChild()})),u=o.next();for await(const c of a){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);const l=Object.fromEntries(Object.entries(c).filter(([d])=>!s.includes(d)));Object.keys(l).length>0&&(yield l)}yield(await u).value;for await(const c of o)yield c}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}const s=Y(t),a=new Gt({generator:this.transform(r(),s),config:s});return await a.setup,$e.fromAsyncGenerator(a)}}class n_ extends Ae{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];{const t=this.keys.map(r=>[r,e[r]]).filter(r=>r[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(const t of e){const r=await this._pick(t);r!==void 0&&(yield r)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}const s=Y(t),a=new Gt({generator:this.transform(r(),s),config:s});return await a.setup,$e.fromAsyncGenerator(a)}}class $c extends At{constructor(e){const t=Ot.from([In.from(async r=>{let s;if(vp(r))try{s=await Hg(this.schema,r.args)}catch{throw new Ep("Received tool input did not match expected schema",JSON.stringify(r.args))}else s=r;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"}}function s_(n,e){const t=e.name??n.getName(),r=e.description??Gg(e.schema);return Vg(e.schema)?new $c({name:t,description:r,schema:bm({input:ym()}).transform(s=>s.input),bound:n}):new $c({name:t,description:r,schema:e.schema,bound:n})}class a_ extends Ae{constructor(e){super(e),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}),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw new Error("Not implemented!")}async invoke(e,t){return this.getRelevantDocuments(e,Y(t))}async getRelevantDocuments(e,t){const r=Y(Bp(t)),a=await(await Be.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,r.runId,void 0,void 0,void 0,r.runName);try{const i=await this._getRelevantDocuments(e,a);return await a?.handleRetrieverEnd(i),i}catch(i){throw await a?.handleRetrieverError(i),i}}}class ri extends a_{static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(e){super(e),Object.defineProperty(this,"vectorStore",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"k",{enumerable:!0,configurable:!0,writable:!0,value:4}),Object.defineProperty(this,"searchType",{enumerable:!0,configurable:!0,writable:!0,value:"similarity"}),Object.defineProperty(this,"searchKwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType==="mmr"&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){if(this.searchType==="mmr"){if(typeof this.vectorStore.maxMarginalRelevanceSearch!="function")throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},t?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild("vectorstore"))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}}class i_ extends Et{constructor(e,t){super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","vectorstores",this._vectorstoreType()]}),Object.defineProperty(this,"embeddings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.embeddings=e}async delete(e){throw new Error("Not implemented.")}async similaritySearch(e,t=4,r=void 0,s=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)).map(i=>i[0])}async similaritySearchWithScore(e,t=4,r=void 0,s=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)}static fromTexts(e,t,r,s){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(e,t,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(e,t,r,s,a,i){if(typeof e=="number")return new ri({vectorStore:this,k:e,filter:t,tags:[...s??[],this._vectorstoreType()],metadata:a,verbose:i,callbacks:r});{const o={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return e?.searchType==="mmr"?new ri({...o,searchKwargs:e.searchKwargs}):new ri({...o})}}}class Vt{constructor(e){Object.defineProperty(this,"pageContent",{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,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.pageContent=e.pageContent!==void 0?e.pageContent.toString():"",this.metadata=e.metadata??{},this.id=e.id}}function o_(n,e){let t=0,r=0,s=0;for(let a=0;a<n.length;a++)t+=n[a]*e[a],r+=n[a]*n[a],s+=e[a]*e[a];return t/(Math.sqrt(r)*Math.sqrt(s))}function u_(n,e){let t=0,r=0,s=0;for(let a=0;a<n.length;a++)t+=n[a]*e[a],r+=n[a]*n[a],s+=e[a]*e[a];return t/(Math.sqrt(r)*Math.sqrt(s))}function c_(n,e,t){if(n.length===0||n[0].length===0||e.length===0||e[0].length===0)return[[]];if(n[0].length!==e[0].length)throw new Error(`Number of columns in X and Y must be the same. X has shape ${[n.length,n[0].length]} and Y has shape ${[e.length,e[0].length]}.`);return n.map(r=>e.map(s=>t(r,s)).map(s=>Number.isNaN(s)?0:s))}function Lc(n,e){return c_(n,e,u_)}function l_(n,e,t=.5,r=4){if(Math.min(r,e.length)<=0)return[];const s=Array.isArray(n[0])?n:[n],a=Lc(s,e)[0],i=d_(a).maxIndex,o=[e[i]],u=[i];for(;u.length<Math.min(r,e.length);){let c=-1/0,l=-1;const d=Lc(e,o);a.forEach((h,f)=>{if(u.includes(f))return;const p=Math.max(...d[f]),m=t*h-(1-t)*p;m>c&&(c=m,l=f)}),o.push(e[l]),u.push(l)}return u}function d_(n){if(n.length===0)return{maxIndex:-1,maxValue:NaN};let e=n[0],t=0;for(let r=1;r<n.length;r+=1)n[r]>e&&(t=r,e=n[r]);return{maxIndex:t,maxValue:e}}class Rn extends i_{_vectorstoreType(){return"memory"}constructor(e,{similarity:t,...r}={}){super(e,r),Object.defineProperty(this,"memoryVectors",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"similarity",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.similarity=t??o_}async addDocuments(e){const t=e.map(({pageContent:r})=>r);return this.addVectors(await this.embeddings.embedDocuments(t),e)}async addVectors(e,t){const r=e.map((s,a)=>({content:t[a].pageContent,embedding:s,metadata:t[a].metadata,id:t[a].id}));this.memoryVectors=this.memoryVectors.concat(r)}async _queryVectors(e,t,r){const s=i=>{if(!r)return!0;const o=new Vt({metadata:i.metadata,pageContent:i.content,id:i.id});return r(o)};return this.memoryVectors.filter(s).map((i,o)=>({similarity:this.similarity(e,i.embedding),index:o,metadata:i.metadata,content:i.content,embedding:i.embedding,id:i.id})).sort((i,o)=>i.similarity>o.similarity?-1:0).slice(0,t)}async similaritySearchVectorWithScore(e,t,r){return(await this._queryVectors(e,t,r)).map(i=>[new Vt({metadata:i.metadata,pageContent:i.content,id:i.id}),i.similarity])}async maxMarginalRelevanceSearch(e,t){const r=await this.embeddings.embedQuery(e),s=await this._queryVectors(r,t.fetchK??20,t.filter),a=s.map(o=>o.embedding);return l_(r,a,t.lambda,t.k).map(o=>new Vt({metadata:s[o].metadata,pageContent:s[o].content,id:s[o].id}))}static async fromTexts(e,t,r,s){const a=[];for(let i=0;i<e.length;i+=1){const o=Array.isArray(t)?t[i]:t,u=new Vt({pageContent:e[i],metadata:o});a.push(u)}return Rn.fromDocuments(a,r,s)}static async fromDocuments(e,t,r){const s=new this(t,r);return await s.addDocuments(e),s}static async fromExistingIndex(e,t){return new this(e,t)}}function B(n,e,t,r,s){if(typeof e=="function"?n!==e||!0:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(n,t),t}function w(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}let jc=function(){const{crypto:n}=globalThis;if(n?.randomUUID)return jc=n.randomUUID.bind(n),n.randomUUID();const e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function ni(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}const si=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){const e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};class L extends Error{}class ge extends L{constructor(e,t,r,s){super(`${ge.makeMessage(e,t,r)}`),this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;const a=t;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,r){const s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new Tn({message:r,cause:si(t)});const a=t?.error;return e===400?new Mc(e,a,r,s):e===401?new Dc(e,a,r,s):e===403?new Uc(e,a,r,s):e===404?new Fc(e,a,r,s):e===409?new Bc(e,a,r,s):e===422?new zc(e,a,r,s):e===429?new qc(e,a,r,s):e>=500?new Hc(e,a,r,s):new ge(e,a,r,s)}}class je extends ge{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Tn extends ge{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class xn extends Tn{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Mc extends ge{}class Dc extends ge{}class Uc extends ge{}class Fc extends ge{}class Bc extends ge{}class zc extends ge{}class qc extends ge{}class Hc extends ge{}class Gc extends L{constructor(){super("Could not parse response content as the length limit was reached")}}class Vc extends L{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class vr extends Error{constructor(e){super(e)}}const h_=/^[a-z][a-z0-9+.-]*:/i,f_=n=>h_.test(n);let Pe=n=>(Pe=Array.isArray,Pe(n)),Zc=Pe;function p_(n){return typeof n!="object"?{}:n??{}}function m_(n){if(!n)return!0;for(const e in n)return!1;return!0}function g_(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function kn(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}const __=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new L(`${n} must be an integer`);if(e<0)throw new L(`${n} must be a positive integer`);return e},y_=n=>{try{return JSON.parse(n)}catch{return}},Er=n=>new Promise(e=>setTimeout(e,n)),Zt="5.12.2",b_=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function w_(){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"}const v_=()=>{const n=w_();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zt,"X-Stainless-OS":Jc(Deno.build.os),"X-Stainless-Arch":Wc(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":Zt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zt,"X-Stainless-OS":Jc(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Wc(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=E_();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zt,"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":Zt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function E_(){if(typeof navigator>"u"||!navigator)return null;const n=[{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(const{key:e,pattern:t}of n){const r=t.exec(navigator.userAgent);if(r){const s=r[1]||0,a=r[2]||0,i=r[3]||0;return{browser:e,version:`${s}.${a}.${i}`}}}return null}const Wc=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",Jc=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown");let Kc;const S_=()=>Kc??(Kc=v_());function A_(){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 Xc(...n){const 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(...n)}function Qc(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return Xc({start(){},async pull(t){const{done:r,value:s}=await e.next();r?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function Yc(n){if(n[Symbol.asyncIterator])return n;const e=n.getReader();return{async next(){try{const t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function O_(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}const e=n.getReader(),t=e.cancel();e.releaseLock(),await t}const I_=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),el="RFC3986",tl=n=>String(n),rl={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:tl},R_="RFC1738";let ai=(n,e)=>(ai=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),ai(n,e));const Ye=(()=>{const n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})(),ii=1024,T_=(n,e,t,r,s)=>{if(n.length===0)return n;let a=n;if(typeof n=="symbol"?a=Symbol.prototype.toString.call(n):typeof n!="string"&&(a=String(n)),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+=ii){const u=a.length>=ii?a.slice(o,o+ii):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===R_&&(d===40||d===41)){c[c.length]=u.charAt(l);continue}if(d<128){c[c.length]=Ye[d];continue}if(d<2048){c[c.length]=Ye[192|d>>6]+Ye[128|d&63];continue}if(d<55296||d>=57344){c[c.length]=Ye[224|d>>12]+Ye[128|d>>6&63]+Ye[128|d&63];continue}l+=1,d=65536+((d&1023)<<10|u.charCodeAt(l)&1023),c[c.length]=Ye[240|d>>18]+Ye[128|d>>12&63]+Ye[128|d>>6&63]+Ye[128|d&63]}i+=c.join("")}return i};function x_(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function nl(n,e){if(Pe(n)){const t=[];for(let r=0;r<n.length;r+=1)t.push(e(n[r]));return t}return e(n)}const sl={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},al=function(n,e){Array.prototype.push.apply(n,Pe(e)?e:[e])};let il;const de={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:T_,encodeValuesOnly:!1,format:el,formatter:tl,indices:!1,serializeDate(n){return(il??(il=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function k_(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}const oi={};function ol(n,e,t,r,s,a,i,o,u,c,l,d,h,f,p,m,g,y){let _=n,b=y,E=0,v=!1;for(;(b=b.get(oi))!==void 0&&!v;){const K=b.get(n);if(E+=1,typeof K<"u"){if(K===E)throw new RangeError("Cyclic object value");v=!0}typeof b.get(oi)>"u"&&(E=0)}if(typeof c=="function"?_=c(e,_):_ instanceof Date?_=h?.(_):t==="comma"&&Pe(_)&&(_=nl(_,function(K){return K instanceof Date?h?.(K):K})),_===null){if(a)return u&&!m?u(e,de.encoder,g,"key",f):e;_=""}if(k_(_)||x_(_)){if(u){const K=m?e:u(e,de.encoder,g,"key",f);return[p?.(K)+"="+p?.(u(_,de.encoder,g,"value",f))]}return[p?.(e)+"="+p?.(String(_))]}const x=[];if(typeof _>"u")return x;let P;if(t==="comma"&&Pe(_))m&&u&&(_=nl(_,u)),P=[{value:_.length>0?_.join(",")||null:void 0}];else if(Pe(c))P=c;else{const K=Object.keys(_);P=l?K.sort(l):K}const O=o?String(e).replace(/\\./g,"%2E"):String(e),J=r&&Pe(_)&&_.length===1?O+"[]":O;if(s&&Pe(_)&&_.length===0)return J+"[]";for(let K=0;K<P.length;++K){const ne=P[K],Je=typeof ne=="object"&&typeof ne.value<"u"?ne.value:_[ne];if(i&&Je===null)continue;const $t=d&&o?ne.replace(/\\./g,"%2E"):ne,k=Pe(_)?typeof t=="function"?t(J,$t):J:J+(d?"."+$t:"["+$t+"]");y.set(n,E);const I=new WeakMap;I.set(oi,y),al(x,ol(Je,k,t,r,s,a,i,o,t==="comma"&&m&&Pe(_)?null:u,c,l,d,h,f,p,m,g,I))}return x}function P_(n=de){if(typeof n.allowEmptyArrays<"u"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof n.encodeDotInKeys<"u"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder<"u"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=n.charset||de.charset;if(typeof n.charset<"u"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=el;if(typeof n.format<"u"){if(!ai(rl,n.format))throw new TypeError("Unknown format option provided.");t=n.format}const r=rl[t];let s=de.filter;(typeof n.filter=="function"||Pe(n.filter))&&(s=n.filter);let a;if(n.arrayFormat&&n.arrayFormat in sl?a=n.arrayFormat:"indices"in n?a=n.indices?"indices":"repeat":a=de.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof n.allowDots>"u"?n.encodeDotInKeys?!0:de.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:de.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:de.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:de.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?de.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:de.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:de.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:de.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:de.encodeValuesOnly,filter:s,format:t,formatter:r,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:de.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:de.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:de.strictNullHandling}}function C_(n,e={}){let t=n;const r=P_(e);let s,a;typeof r.filter=="function"?(a=r.filter,t=a("",t)):Pe(r.filter)&&(a=r.filter,s=a);const i=[];if(typeof t!="object"||t===null)return"";const o=sl[r.arrayFormat],u=o==="comma"&&r.commaRoundTrip;s||(s=Object.keys(t)),r.sort&&s.sort(r.sort);const c=new WeakMap;for(let h=0;h<s.length;++h){const f=s[h];r.skipNulls&&t[f]===null||al(i,ol(t[f],f,o,u,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,c))}const l=i.join(r.delimiter);let d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),l.length>0?d+l:""}function N_(n){let e=0;for(const s of n)e+=s.length;const t=new Uint8Array(e);let r=0;for(const s of n)t.set(s,r),r+=s.length;return t}let ul;function ui(n){let e;return(ul??(e=new globalThis.TextEncoder,ul=e.encode.bind(e)))(n)}let cl;function ll(n){let e;return(cl??(e=new globalThis.TextDecoder,cl=e.decode.bind(e)))(n)}var Me,De;class Pn{constructor(){Me.set(this,void 0),De.set(this,void 0),B(this,Me,new Uint8Array),B(this,De,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ui(e):e;B(this,Me,N_([w(this,Me,"f"),t]));const r=[];let s;for(;(s=$_(w(this,Me,"f"),w(this,De,"f")))!=null;){if(s.carriage&&w(this,De,"f")==null){B(this,De,s.index);continue}if(w(this,De,"f")!=null&&(s.index!==w(this,De,"f")+1||s.carriage)){r.push(ll(w(this,Me,"f").subarray(0,w(this,De,"f")-1))),B(this,Me,w(this,Me,"f").subarray(w(this,De,"f"))),B(this,De,null);continue}const a=w(this,De,"f")!==null?s.preceding-1:s.preceding,i=ll(w(this,Me,"f").subarray(0,a));r.push(i),B(this,Me,w(this,Me,"f").subarray(s.index)),B(this,De,null)}return r}flush(){return w(this,Me,"f").length?this.decode(`\n`):[]}}Me=new WeakMap,De=new WeakMap,Pn.NEWLINE_CHARS=new Set([`\n`,"\\r"]),Pn.NEWLINE_REGEXP=/\\r\\n|[\\n\\r]/g;function $_(n,e){for(let s=e??0;s<n.length;s++){if(n[s]===10)return{preceding:s,index:s+1,carriage:!1};if(n[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function L_(n){for(let r=0;r<n.length-1;r++){if(n[r]===10&&n[r+1]===10||n[r]===13&&n[r+1]===13)return r+2;if(n[r]===13&&n[r+1]===10&&r+3<n.length&&n[r+2]===13&&n[r+3]===10)return r+4}return-1}const Cn={off:0,error:200,warn:300,info:400,debug:500},dl=(n,e,t)=>{if(n){if(g_(Cn,n))return n;_e(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Cn))}`)}};function Sr(){}function Nn(n,e,t){return!e||Cn[n]>Cn[t]?Sr:e[n].bind(e)}const j_={error:Sr,warn:Sr,info:Sr,debug:Sr};let hl=new WeakMap;function _e(n){const e=n.logger,t=n.logLevel??"off";if(!e)return j_;const r=hl.get(e);if(r&&r[0]===t)return r[1];const s={error:Nn("error",e,t),warn:Nn("warn",e,t),info:Nn("info",e,t),debug:Nn("debug",e,t)};return hl.set(e,[t,s]),s}const Rt=n=>(n.options&&(n.options={...n.options},delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);var Ar;class et{constructor(e,t,r){this.iterator=e,Ar.set(this,void 0),this.controller=t,B(this,Ar,r)}static fromSSEResponse(e,t,r){let s=!1;const a=r?_e(r):console;async function*i(){if(s)throw new L("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(const u of M_(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 ge(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 ge(void 0,c.error,c.message,void 0);yield{event:u.event,data:c}}}o=!0}catch(u){if(ni(u))return;throw u}finally{o||t.abort()}}return new et(i,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*a(){const o=new Pn,u=Yc(e);for await(const c of u)for(const l of o.decode(c))yield l;for(const c of o.flush())yield c}async function*i(){if(s)throw new L("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(const u of a())o||u&&(yield JSON.parse(u));o=!0}catch(u){if(ni(u))return;throw u}finally{o||t.abort()}}return new et(i,t,r)}[(Ar=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],r=this.iterator(),s=a=>({next:()=>{if(a.length===0){const i=r.next();e.push(i),t.push(i)}return a.shift()}});return[new et(()=>s(e),this.controller,w(this,Ar,"f")),new et(()=>s(t),this.controller,w(this,Ar,"f"))]}toReadableStream(){const e=this;let t;return Xc({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{const{value:s,done:a}=await t.next();if(a)return r.close();const i=ui(JSON.stringify(s)+`\n`);r.enqueue(i)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}}async function*M_(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new L("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 L("Attempted to iterate over a response with no body");const t=new U_,r=new Pn,s=Yc(n.body);for await(const a of D_(s))for(const i of r.decode(a)){const o=t.decode(i);o&&(yield o)}for(const a of r.flush()){const i=t.decode(a);i&&(yield i)}}async function*D_(n){let e=new Uint8Array;for await(const t of n){if(t==null)continue;const r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?ui(t):t;let s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let a;for(;(a=L_(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class U_{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;const a={event:this.event,data:this.data.join(`\n`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=F_(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}}function F_(n,e){const t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}async function fl(n,e){const{response:t,requestLogID:r,retryOfRequestLogID:s,startTime:a}=e,i=await(async()=>{if(e.options.stream)return _e(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n):et.fromSSEResponse(t,e.controller,n);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const u=t.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){const d=await t.json();return pl(d,t)}return await t.text()})();return _e(n).debug(`[${r}] response parsed`,Rt({retryOfRequestLogID:s,url:t.url,status:t.status,body:i,durationMs:Date.now()-a})),i}function pl(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Or;class $n extends Promise{constructor(e,t,r=fl){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=r,Or.set(this,void 0),B(this,Or,e)}_thenUnwrap(e){return new $n(w(this,Or,"f"),this.responsePromise,async(t,r)=>pl(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[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(w(this,Or,"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)}}Or=new WeakMap;var Ln;class ml{constructor(e,t,r,s){Ln.set(this,void 0),B(this,Ln,e),this.options=s,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new L("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await w(this,Ln,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ln=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class B_ extends $n{constructor(e,t,r){super(e,t,async(s,a)=>new r(s,a.response,await fl(s,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class jn extends ml{constructor(e,t,r,s){super(e,t,r,s),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class oe extends ml{constructor(e,t,r,s){super(e,t,r,s),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...p_(this.options.query),after:t}}:null}}const gl=()=>{if(typeof File>"u"){const{process:n}=globalThis,e=typeof n?.versions?.node=="string"&&parseInt(n.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 Ir(n,e,t){return gl(),new File(n,e??"unknown_file",t)}function Mn(n){return(typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\\\/]/).pop()||void 0}const _l=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",Tt=async(n,e)=>({...n,body:await q_(n.body,e)}),yl=new WeakMap;function z_(n){const e=typeof n=="function"?n:n.fetch,t=yl.get(e);if(t)return t;const r=(async()=>{try{const 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 yl.set(e,r),r}const q_=async(n,e)=>{if(!await z_(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(n||{}).map(([r,s])=>ci(t,r,s))),t},H_=n=>n instanceof Blob&&"name"in n,ci=async(n,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")n.append(e,String(t));else if(t instanceof Response)n.append(e,Ir([await t.blob()],Mn(t)));else if(_l(t))n.append(e,Ir([await new Response(Qc(t)).blob()],Mn(t)));else if(H_(t))n.append(e,t,Mn(t));else if(Array.isArray(t))await Promise.all(t.map(r=>ci(n,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,s])=>ci(n,`${e}[${r}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},bl=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",G_=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&bl(n),V_=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function Z_(n,e,t){if(gl(),n=await n,G_(n))return n instanceof File?n:Ir([await n.arrayBuffer()],n.name);if(V_(n)){const s=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\\\/]/).pop()),Ir(await li(s),e,t)}const r=await li(n);if(e||(e=Mn(n)),!t?.type){const s=r.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof s=="string"&&(t={...t,type:s})}return Ir(r,e,t)}async function li(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(bl(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(_l(n))for await(const t of n)e.push(...await li(t));else{const t=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${t?`; constructor: ${t}`:""}${W_(n)}`)}return e}function W_(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}class z{constructor(e){this._client=e}}function wl(n){return n.replace(/[^A-Za-z0-9\\-._~!$&\'()*+,;=:@]+/g,encodeURIComponent)}const vl=Object.freeze(Object.create(null)),R=((n=wl)=>function(t,...r){if(t.length===1)return t[0];let s=!1;const a=[],i=t.reduce((l,d,h)=>{/[?#]/.test(d)&&(s=!0);const f=r[h];let p=(s?encodeURIComponent:n)(""+f);return h!==r.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??vl)??vl)?.toString)&&(p=f+"",a.push({start:l.length+d.length,length:p.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),l+d+(h===r.length?"":p)},""),o=i.split(/[?#]/,1)[0],u=/(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)/gi;let 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;const d=a.reduce((h,f)=>{const p=" ".repeat(f.start-l),m="^".repeat(f.length);return l=f.start+f.length,h+p+m},"");throw new L(`Path parameters result in path with invalid segments:\n${a.map(h=>h.error).join(`\n`)}\n${i}\n${d}`)}return i})(wl);let El=class extends z{list(e,t={},r){return this._client.getAPIList(R`/chat/completions/${e}/messages`,oe,{query:t,...r})}};function Dn(n){return n!==void 0&&"function"in n&&n.function!==void 0}function di(n){return n?.$brand==="auto-parseable-response-format"}function Rr(n){return n?.$brand==="auto-parseable-tool"}function J_(n,e){return!e||!Sl(e)?{...n,choices:n.choices.map(t=>(Al(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:hi(n,e)}function hi(n,e){const t=n.choices.map(r=>{if(r.finish_reason==="length")throw new Gc;if(r.finish_reason==="content_filter")throw new Vc;return Al(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(s=>X_(e,s))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?K_(e,r.message.content):null}}});return{...n,choices:t}}function K_(n,e){return n.response_format?.type!=="json_schema"?null:n.response_format?.type==="json_schema"?"$parseRaw"in n.response_format?n.response_format.$parseRaw(e):JSON.parse(e):null}function X_(n,e){const t=n.tools?.find(r=>Dn(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Rr(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function Q_(n,e){if(!n||!("tools"in n)||!n.tools)return!1;const t=n.tools?.find(r=>Dn(r)&&r.function?.name===e.function.name);return Dn(t)&&(Rr(t)||t?.function.strict||!1)}function Sl(n){return di(n.response_format)?!0:n.tools?.some(e=>Rr(e)||e.type==="function"&&e.function.strict===!0)??!1}function Al(n){for(const e of n||[])if(e.type!=="function")throw new L(`Currently only \\`function\\` tool calls are supported; Received \\`${e.type}\\``)}function Y_(n){for(const e of n??[]){if(e.type!=="function")throw new L(`Currently only \\`function\\` tool types support auto-parsing; Received \\`${e.type}\\``);if(e.function.strict!==!0)throw new L(`The \\`${e.function.name}\\` tool is not marked with \\`strict: true\\`. Only strict function tools can be auto-parsed`)}}const Un=n=>n?.role==="assistant",Ol=n=>n?.role==="tool";var fi,Fn,Bn,Tr,xr,zn,kr,at,Pr,qn,Hn,Wt,Il;class pi{constructor(){fi.add(this),this.controller=new AbortController,Fn.set(this,void 0),Bn.set(this,()=>{}),Tr.set(this,()=>{}),xr.set(this,void 0),zn.set(this,()=>{}),kr.set(this,()=>{}),at.set(this,{}),Pr.set(this,!1),qn.set(this,!1),Hn.set(this,!1),Wt.set(this,!1),B(this,Fn,new Promise((e,t)=>{B(this,Bn,e,"f"),B(this,Tr,t,"f")})),B(this,xr,new Promise((e,t)=>{B(this,zn,e,"f"),B(this,kr,t,"f")})),w(this,Fn,"f").catch(()=>{}),w(this,xr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},w(this,fi,"m",Il).bind(this))},0)}_connected(){this.ended||(w(this,Bn,"f").call(this),this._emit("connect"))}get ended(){return w(this,Pr,"f")}get errored(){return w(this,qn,"f")}get aborted(){return w(this,Hn,"f")}abort(){this.controller.abort()}on(e,t){return(w(this,at,"f")[e]||(w(this,at,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=w(this,at,"f")[e];if(!r)return this;const s=r.findIndex(a=>a.listener===t);return s>=0&&r.splice(s,1),this}once(e,t){return(w(this,at,"f")[e]||(w(this,at,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{B(this,Wt,!0),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){B(this,Wt,!0),await w(this,xr,"f")}_emit(e,...t){if(w(this,Pr,"f"))return;e==="end"&&(B(this,Pr,!0),w(this,zn,"f").call(this));const r=w(this,at,"f")[e];if(r&&(w(this,at,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!w(this,Wt,"f")&&!r?.length&&Promise.reject(s),w(this,Tr,"f").call(this,s),w(this,kr,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!w(this,Wt,"f")&&!r?.length&&Promise.reject(s),w(this,Tr,"f").call(this,s),w(this,kr,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Fn=new WeakMap,Bn=new WeakMap,Tr=new WeakMap,xr=new WeakMap,zn=new WeakMap,kr=new WeakMap,at=new WeakMap,Pr=new WeakMap,qn=new WeakMap,Hn=new WeakMap,Wt=new WeakMap,fi=new WeakSet,Il=function(e){if(B(this,qn,!0),e instanceof Error&&e.name==="AbortError"&&(e=new je),e instanceof je)return B(this,Hn,!0),this._emit("abort",e);if(e instanceof L)return this._emit("error",e);if(e instanceof Error){const t=new L(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new L(String(e)))};function ey(n){return typeof n.parse=="function"}var Oe,mi,Gn,gi,_i,yi,Rl,Tl;const ty=10;class xl extends pi{constructor(){super(...arguments),Oe.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const 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),Ol(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Un(e)&&e.tool_calls)for(const r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new L("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),w(this,Oe,"m",mi).call(this)}async finalMessage(){return await this.done(),w(this,Oe,"m",Gn).call(this)}async finalFunctionToolCall(){return await this.done(),w(this,Oe,"m",gi).call(this)}async finalFunctionToolCallResult(){return await this.done(),w(this,Oe,"m",_i).call(this)}async totalUsage(){return await this.done(),w(this,Oe,"m",yi).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=w(this,Oe,"m",Gn).call(this);t&&this._emit("finalMessage",t);const r=w(this,Oe,"m",mi).call(this);r&&this._emit("finalContent",r);const s=w(this,Oe,"m",gi).call(this);s&&this._emit("finalFunctionToolCall",s);const a=w(this,Oe,"m",_i).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",w(this,Oe,"m",yi).call(this))}async _createChatCompletion(e,t,r){const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),w(this,Oe,"m",Rl).call(this,t);const a=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(hi(a,t))}async _runChatCompletion(e,t,r){for(const s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){const s="tool",{tool_choice:a="auto",stream:i,...o}=t,u=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:c=ty}=r||{},l=t.tools.map(f=>{if(Rr(f)){if(!f.$callback)throw new L("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:f.$callback,name:f.function.name,description:f.function.description||"",parameters:f.function.parameters,parse:f.$parseRaw,strict:!0}}}return f}),d={};for(const f of l)f.type==="function"&&(d[f.function.name||f.function.function.name]=f.function);const h="tools"in t?l.map(f=>f.type==="function"?{type:"function",function:{name:f.function.name||f.function.function.name,parameters:f.function.parameters,description:f.function.description,strict:f.function.strict}}:f):void 0;for(const f of t.messages)this._addMessage(f,!1);for(let f=0;f<c;++f){const m=(await this._createChatCompletion(e,{...o,tool_choice:a,tools:h,messages:[...this.messages]},r)).choices[0]?.message;if(!m)throw new L("missing message in ChatCompletion response");if(!m.tool_calls?.length)return;for(const g of m.tool_calls){if(g.type!=="function")continue;const y=g.id,{name:_,arguments:b}=g.function,E=d[_];if(E){if(u&&u!==_){const O=`Invalid tool_call: ${JSON.stringify(_)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:s,tool_call_id:y,content:O});continue}}else{const O=`Invalid tool_call: ${JSON.stringify(_)}. Available options are: ${Object.keys(d).map(J=>JSON.stringify(J)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:y,content:O});continue}let v;try{v=ey(E)?await E.parse(b):b}catch(O){const J=O instanceof Error?O.message:String(O);this._addMessage({role:s,tool_call_id:y,content:J});continue}const x=await E.function(v,this),P=w(this,Oe,"m",Tl).call(this,x);if(this._addMessage({role:s,tool_call_id:y,content:P}),u)return}}}}Oe=new WeakSet,mi=function(){return w(this,Oe,"m",Gn).call(this).content??null},Gn=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(Un(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new L("stream ended without producing a ChatCompletionMessage with role=assistant")},gi=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Un(t)&&t?.tool_calls?.length)return t.tool_calls.filter(r=>r.type==="function").at(-1)?.function}},_i=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Ol(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(s=>s.type==="function"&&s.id===t.tool_call_id)))return t.content}},yi=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{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},Rl=function(e){if(e.n!=null&&e.n>1)throw new L("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Tl=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class bi extends xl{static runTools(e,t,r){const s=new bi,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,a)),s}_addMessage(e,t=!0){super._addMessage(e,t),Un(e)&&e.content&&this._emit("content",e.content)}}const kl=1,Pl=2,Cl=4,Nl=8,$l=16,Ll=32,jl=64,Ml=128,Dl=256,Ul=Ml|Dl,Fl=$l|Ll|Ul|jl,Bl=kl|Pl|Fl,zl=Cl|Nl,ry=Bl|zl,pe={STR:kl,NUM:Pl,ARR:Cl,OBJ:Nl,NULL:$l,BOOL:Ll,NAN:jl,INFINITY:Ml,MINUS_INFINITY:Dl,INF:Ul,SPECIAL:Fl,ATOM:Bl,COLLECTION:zl,ALL:ry};class ny extends Error{}class sy extends Error{}function ay(n,e=pe.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return iy(n.trim(),e)}const iy=(n,e)=>{const t=n.length;let r=0;const s=h=>{throw new ny(`${h} at position ${r}`)},a=h=>{throw new sy(`${h} at position ${r}`)},i=()=>(d(),r>=t&&s("Unexpected end of input"),n[r]===\'"\'?o():n[r]==="{"?u():n[r]==="["?c():n.substring(r,r+4)==="null"||pe.NULL&e&&t-r<4&&"null".startsWith(n.substring(r))?(r+=4,null):n.substring(r,r+4)==="true"||pe.BOOL&e&&t-r<4&&"true".startsWith(n.substring(r))?(r+=4,!0):n.substring(r,r+5)==="false"||pe.BOOL&e&&t-r<5&&"false".startsWith(n.substring(r))?(r+=5,!1):n.substring(r,r+8)==="Infinity"||pe.INFINITY&e&&t-r<8&&"Infinity".startsWith(n.substring(r))?(r+=8,1/0):n.substring(r,r+9)==="-Infinity"||pe.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(n.substring(r))?(r+=9,-1/0):n.substring(r,r+3)==="NaN"||pe.NAN&e&&t-r<3&&"NaN".startsWith(n.substring(r))?(r+=3,NaN):l()),o=()=>{const h=r;let f=!1;for(r++;r<t&&(n[r]!==\'"\'||f&&n[r-1]==="\\\\");)f=n[r]==="\\\\"?!f:!1,r++;if(n.charAt(r)==\'"\')try{return JSON.parse(n.substring(h,++r-Number(f)))}catch(p){a(String(p))}else if(pe.STR&e)try{return JSON.parse(n.substring(h,r-Number(f))+\'"\')}catch{return JSON.parse(n.substring(h,n.lastIndexOf("\\\\"))+\'"\')}s("Unterminated string literal")},u=()=>{r++,d();const h={};try{for(;n[r]!=="}";){if(d(),r>=t&&pe.OBJ&e)return h;const f=o();d(),r++;try{const p=i();Object.defineProperty(h,f,{value:p,writable:!0,enumerable:!0,configurable:!0})}catch(p){if(pe.OBJ&e)return h;throw p}d(),n[r]===","&&r++}}catch{if(pe.OBJ&e)return h;s("Expected \'}\' at end of object")}return r++,h},c=()=>{r++;const h=[];try{for(;n[r]!=="]";)h.push(i()),d(),n[r]===","&&r++}catch{if(pe.ARR&e)return h;s("Expected \']\' at end of array")}return r++,h},l=()=>{if(r===0){n==="-"&&pe.NUM&e&&s("Not sure what \'-\' is");try{return JSON.parse(n)}catch(f){if(pe.NUM&e)try{return n[n.length-1]==="."?JSON.parse(n.substring(0,n.lastIndexOf("."))):JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch{}a(String(f))}}const h=r;for(n[r]==="-"&&r++;n[r]&&!",]}".includes(n[r]);)r++;r==t&&!(pe.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(n.substring(h,r))}catch{n.substring(h,r)==="-"&&pe.NUM&e&&s("Not sure what \'-\' is");try{return JSON.parse(n.substring(h,n.lastIndexOf("e")))}catch(p){a(String(p))}}},d=()=>{for(;r<t&&` \n\\r `.includes(n[r]);)r++};return i()},ql=n=>ay(n,pe.ALL^pe.NUM);var he,it,Jt,wt,wi,Vn,vi,Ei,Si,Zn,Ai,Hl;class Cr extends xl{constructor(e){super(),he.add(this),it.set(this,void 0),Jt.set(this,void 0),wt.set(this,void 0),B(this,it,e),B(this,Jt,[])}get currentChatCompletionSnapshot(){return w(this,wt,"f")}static fromReadableStream(e){const t=new Cr(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){const s=new Cr(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,r){super._createChatCompletion;const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),w(this,he,"m",wi).call(this);const a=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const i of a)w(this,he,"m",vi).call(this,i);if(a.controller.signal?.aborted)throw new je;return this._addChatCompletion(w(this,he,"m",Zn).call(this))}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),w(this,he,"m",wi).call(this),this._connected();const s=et.fromReadableStream(e,this.controller);let a;for await(const i of s)a&&a!==i.id&&this._addChatCompletion(w(this,he,"m",Zn).call(this)),w(this,he,"m",vi).call(this,i),a=i.id;if(s.controller.signal?.aborted)throw new je;return this._addChatCompletion(w(this,he,"m",Zn).call(this))}[(it=new WeakMap,Jt=new WeakMap,wt=new WeakMap,he=new WeakSet,wi=function(){this.ended||B(this,wt,void 0)},Vn=function(t){let r=w(this,Jt,"f")[t.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},w(this,Jt,"f")[t.index]=r,r)},vi=function(t){if(this.ended)return;const r=w(this,he,"m",Hl).call(this,t);this._emit("chunk",t,r);for(const s of t.choices){const a=r.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??[]});const i=w(this,he,"m",Vn).call(this,a);a.finish_reason&&(w(this,he,"m",Si).call(this,a),i.current_tool_call_index!=null&&w(this,he,"m",Ei).call(this,a,i.current_tool_call_index));for(const o of s.delta.tool_calls??[])i.current_tool_call_index!==o.index&&(w(this,he,"m",Si).call(this,a),i.current_tool_call_index!=null&&w(this,he,"m",Ei).call(this,a,i.current_tool_call_index)),i.current_tool_call_index=o.index;for(const o of s.delta.tool_calls??[]){const 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))}}},Ei=function(t,r){if(w(this,he,"m",Vn).call(this,t).done_tool_calls.has(r))return;const a=t.message.tool_calls?.[r];if(!a)throw new Error("no tool call snapshot");if(!a.type)throw new Error("tool call snapshot missing `type`");if(a.type==="function"){const i=w(this,it,"f")?.tools?.find(o=>Dn(o)&&o.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:r,arguments:a.function.arguments,parsed_arguments:Rr(i)?i.$parseRaw(a.function.arguments):i?.function.strict?JSON.parse(a.function.arguments):null})}else a.type},Si=function(t){const r=w(this,he,"m",Vn).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;const s=w(this,he,"m",Ai).call(this);this._emit("content.done",{content:t.message.content,parsed:s?s.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Zn=function(){if(this.ended)throw new L("stream has ended, this shouldn\'t happen");const t=w(this,wt,"f");if(!t)throw new L("request ended without sending any chunks");return B(this,wt,void 0),B(this,Jt,[]),oy(t,w(this,it,"f"))},Ai=function(){const t=w(this,it,"f")?.response_format;return di(t)?t:null},Hl=function(t){var r,s,a,i;let o=w(this,wt,"f");const{choices:u,...c}=t;o?Object.assign(o,c):o=B(this,wt,{...c,choices:[]});for(const{delta:l,finish_reason:d,index:h,logprobs:f=null,...p}of t.choices){let m=o.choices[h];if(m||(m=o.choices[h]={finish_reason:d,index:h,message:{},logprobs:f,...p}),f)if(!m.logprobs)m.logprobs=Object.assign({},f);else{const{content:x,refusal:P,...O}=f;Object.assign(m.logprobs,O),x&&((r=m.logprobs).content??(r.content=[]),m.logprobs.content.push(...x)),P&&((s=m.logprobs).refusal??(s.refusal=[]),m.logprobs.refusal.push(...P))}if(d&&(m.finish_reason=d,w(this,it,"f")&&Sl(w(this,it,"f")))){if(d==="length")throw new Gc;if(d==="content_filter")throw new Vc}if(Object.assign(m,p),!l)continue;const{content:g,refusal:y,function_call:_,role:b,tool_calls:E,...v}=l;if(Object.assign(m.message,v),y&&(m.message.refusal=(m.message.refusal||"")+y),b&&(m.message.role=b),_&&(m.message.function_call?(_.name&&(m.message.function_call.name=_.name),_.arguments&&((a=m.message.function_call).arguments??(a.arguments=""),m.message.function_call.arguments+=_.arguments)):m.message.function_call=_),g&&(m.message.content=(m.message.content||"")+g,!m.message.refusal&&w(this,he,"m",Ai).call(this)&&(m.message.parsed=ql(m.message.content))),E){m.message.tool_calls||(m.message.tool_calls=[]);for(const{index:x,id:P,type:O,function:J,...K}of E){const ne=(i=m.message.tool_calls)[x]??(i[x]={});Object.assign(ne,K),P&&(ne.id=P),O&&(ne.type=O),J&&(ne.function??(ne.function={name:J.name??"",arguments:""})),J?.name&&(ne.function.name=J.name),J?.arguments&&(ne.function.arguments+=J.arguments,Q_(w(this,it,"f"),ne)&&(ne.function.parsed_arguments=ql(ne.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("chunk",s=>{const a=t.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(const a of t)a.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{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 et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function oy(n,e){const{id:t,choices:r,created:s,model:a,system_fingerprint:i,...o}=n,u={...o,id:t,choices:r.map(({message:c,finish_reason:l,index:d,logprobs:h,...f})=>{if(!l)throw new L(`missing finish_reason for choice ${d}`);const{content:p=null,function_call:m,tool_calls:g,...y}=c,_=c.role;if(!_)throw new L(`missing role for choice ${d}`);if(m){const{arguments:b,name:E}=m;if(b==null)throw new L(`missing function_call.arguments for choice ${d}`);if(!E)throw new L(`missing function_call.name for choice ${d}`);return{...f,message:{content:p,function_call:{arguments:b,name:E},role:_,refusal:c.refusal??null},finish_reason:l,index:d,logprobs:h}}return g?{...f,index:d,finish_reason:l,logprobs:h,message:{...y,role:_,content:p,refusal:c.refusal??null,tool_calls:g.map((b,E)=>{const{function:v,type:x,id:P,...O}=b,{arguments:J,name:K,...ne}=v||{};if(P==null)throw new L(`missing choices[${d}].tool_calls[${E}].id\n${Wn(n)}`);if(x==null)throw new L(`missing choices[${d}].tool_calls[${E}].type\n${Wn(n)}`);if(K==null)throw new L(`missing choices[${d}].tool_calls[${E}].function.name\n${Wn(n)}`);if(J==null)throw new L(`missing choices[${d}].tool_calls[${E}].function.arguments\n${Wn(n)}`);return{...O,id:P,type:x,function:{...ne,name:K,arguments:J}}})}}:{...f,message:{...y,content:p,role:_,refusal:c.refusal??null},finish_reason:l,index:d,logprobs:h}}),created:s,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return J_(u,e)}function Wn(n){return JSON.stringify(n)}function Wy(n){}class Jn extends Cr{static fromReadableStream(e){const t=new Jn(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){const s=new Jn(t),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,a)),s}}let Oi=class extends z{constructor(){super(...arguments),this.messages=new El(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(R`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(R`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",oe,{query:e,...t})}delete(e,t){return this._client.delete(R`/chat/completions/${e}`,t)}parse(e,t){return Y_(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>hi(r,e))}runTools(e,t){return e.stream?Jn.runTools(this._client,e,t):bi.runTools(this._client,e,t)}stream(e,t){return Cr.createChatCompletion(this._client,e,t)}};Oi.Messages=El;class Ii extends z{constructor(){super(...arguments),this.completions=new Oi(this._client)}}Ii.Completions=Oi;const Gl=Symbol("brand.privateNullableHeaders");function*uy(n){if(!n)return;if(Gl in n){const{values:r,nulls:s}=n;yield*r.entries();for(const a of s)yield[a,null];return}let e=!1,t;n instanceof Headers?t=n.entries():Zc(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let r of t){const s=r[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const a=Zc(r[1])?r[1]:[r[1]];let i=!1;for(const o of a)o!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,o])}}const j=n=>{const e=new Headers,t=new Set;for(const r of n){const s=new Set;for(const[a,i]of uy(r)){const 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{[Gl]:!0,values:e,nulls:t}};class Vl extends z{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:j([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class Zl extends z{create(e,t){return this._client.post("/audio/transcriptions",Tt({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class Wl extends z{create(e,t){return this._client.post("/audio/translations",Tt({body:e,...t,__metadata:{model:e.model}},this._client))}}class Nr extends z{constructor(){super(...arguments),this.transcriptions=new Zl(this._client),this.translations=new Wl(this._client),this.speech=new Vl(this._client)}}Nr.Transcriptions=Zl,Nr.Translations=Wl,Nr.Speech=Vl;class Jl extends z{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(R`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",oe,{query:e,...t})}cancel(e,t){return this._client.post(R`/batches/${e}/cancel`,t)}}class Kl extends z{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(R`/assistants/${e}`,{...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(R`/assistants/${e}`,{body:t,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",oe,{query:e,...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(R`/assistants/${e}`,{...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Xl extends z{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Ql extends z{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Kn extends z{constructor(){super(...arguments),this.sessions=new Xl(this._client),this.transcriptionSessions=new Ql(this._client)}}Kn.Sessions=Xl,Kn.TranscriptionSessions=Ql;class Yl extends z{create(e,t,r){return this._client.post(R`/threads/${e}/messages`,{body:t,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{thread_id:s}=t;return this._client.get(R`/threads/${s}/messages/${e}`,{...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{thread_id:s,...a}=t;return this._client.post(R`/threads/${s}/messages/${e}`,{body:a,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(R`/threads/${e}/messages`,oe,{query:t,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){const{thread_id:s}=t;return this._client.delete(R`/threads/${s}/messages/${e}`,{...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class ed extends z{retrieve(e,t,r){const{thread_id:s,run_id:a,...i}=t;return this._client.get(R`/threads/${s}/runs/${a}/steps/${e}`,{query:i,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){const{thread_id:s,...a}=t;return this._client.getAPIList(R`/threads/${s}/runs/${e}/steps`,oe,{query:a,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}const cy=n=>{if(typeof Buffer<"u"){const e=Buffer.from(n,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(n),t=e.length,r=new Uint8Array(t);for(let s=0;s<t;s++)r[s]=e.charCodeAt(s);return Array.from(new Float32Array(r.buffer))}},ot=n=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[n]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(n)?.trim()};var ye,xt,Ri,tt,Xn,We,kt,Kt,Pt,Qn,Ue,Yn,es,$r,Lr,jr,td,rd,nd,sd,ad,id,od;class Mr extends pi{constructor(){super(...arguments),ye.add(this),Ri.set(this,[]),tt.set(this,{}),Xn.set(this,{}),We.set(this,void 0),kt.set(this,void 0),Kt.set(this,void 0),Pt.set(this,void 0),Qn.set(this,void 0),Ue.set(this,void 0),Yn.set(this,void 0),es.set(this,void 0),$r.set(this,void 0)}[(Ri=new WeakMap,tt=new WeakMap,Xn=new WeakMap,We=new WeakMap,kt=new WeakMap,Kt=new WeakMap,Pt=new WeakMap,Qn=new WeakMap,Ue=new WeakMap,Yn=new WeakMap,es=new WeakMap,$r=new WeakMap,ye=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",s=>{const a=t.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(const a of t)a.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{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){const t=new xt;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=et.fromReadableStream(e,this.controller);for await(const a of s)w(this,ye,"m",Lr).call(this,a);if(s.controller.signal?.aborted)throw new je;return this._addRun(w(this,ye,"m",jr).call(this))}toReadableStream(){return new et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){const a=new xt;return a._run(()=>a._runToolAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,t,r,s){const a=s?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},o=await e.submitToolOutputs(t,i,{...s,signal:this.controller.signal});this._connected();for await(const u of o)w(this,ye,"m",Lr).call(this,u);if(o.controller.signal?.aborted)throw new je;return this._addRun(w(this,ye,"m",jr).call(this))}static createThreadAssistantStream(e,t,r){const s=new xt;return s._run(()=>s._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,r,s){const a=new xt;return a._run(()=>a._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return w(this,Yn,"f")}currentRun(){return w(this,es,"f")}currentMessageSnapshot(){return w(this,We,"f")}currentRunStepSnapshot(){return w(this,$r,"f")}async finalRunSteps(){return await this.done(),Object.values(w(this,tt,"f"))}async finalMessages(){return await this.done(),Object.values(w(this,Xn,"f"))}async finalRun(){if(await this.done(),!w(this,kt,"f"))throw Error("Final run was not received.");return w(this,kt,"f")}async _createThreadAssistantStream(e,t,r){const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const a={...t,stream:!0},i=await e.createAndRun(a,{...r,signal:this.controller.signal});this._connected();for await(const o of i)w(this,ye,"m",Lr).call(this,o);if(i.controller.signal?.aborted)throw new je;return this._addRun(w(this,ye,"m",jr).call(this))}async _createAssistantStream(e,t,r,s){const a=s?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},o=await e.create(t,i,{...s,signal:this.controller.signal});this._connected();for await(const u of o)w(this,ye,"m",Lr).call(this,u);if(o.controller.signal?.aborted)throw new je;return this._addRun(w(this,ye,"m",jr).call(this))}static accumulateDelta(e,t){for(const[r,s]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let a=e[r];if(a==null){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof a=="string"&&typeof s=="string")a+=s;else if(typeof a=="number"&&typeof s=="number")a+=s;else if(kn(a)&&kn(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(const i of s){if(!kn(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const 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}`);const u=a[o];u==null?a.push(i):a[o]=this.accumulateDelta(u,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${a}`);e[r]=a}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,s){return await this._createAssistantStream(t,e,r,s)}async _runToolAssistantStream(e,t,r,s){return await this._createToolAssistantStream(t,e,r,s)}}xt=Mr,Lr=function(e){if(!this.ended)switch(B(this,Yn,e),w(this,ye,"m",nd).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":w(this,ye,"m",od).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":w(this,ye,"m",rd).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":w(this,ye,"m",td).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},jr=function(){if(this.ended)throw new L("stream has ended, this shouldn\'t happen");if(!w(this,kt,"f"))throw Error("Final run has not been received");return w(this,kt,"f")},td=function(e){const[t,r]=w(this,ye,"m",ad).call(this,e,w(this,We,"f"));B(this,We,t),w(this,Xn,"f")[t.id]=t;for(const s of r){const 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(const 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!=w(this,Kt,"f")){if(w(this,Pt,"f"))switch(w(this,Pt,"f").type){case"text":this._emit("textDone",w(this,Pt,"f").text,w(this,We,"f"));break;case"image_file":this._emit("imageFileDone",w(this,Pt,"f").image_file,w(this,We,"f"));break}B(this,Kt,s.index)}B(this,Pt,t.content[s.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(w(this,Kt,"f")!==void 0){const s=e.data.content[w(this,Kt,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,w(this,We,"f"));break;case"text":this._emit("textDone",s.text,w(this,We,"f"));break}}w(this,We,"f")&&this._emit("messageDone",e.data),B(this,We,void 0)}},rd=function(e){const t=w(this,ye,"m",sd).call(this,e);switch(B(this,$r,t),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(const a of r.step_details.tool_calls)a.index==w(this,Qn,"f")?this._emit("toolCallDelta",a,t.step_details.tool_calls[a.index]):(w(this,Ue,"f")&&this._emit("toolCallDone",w(this,Ue,"f")),B(this,Qn,a.index),B(this,Ue,t.step_details.tool_calls[a.index]),w(this,Ue,"f")&&this._emit("toolCallCreated",w(this,Ue,"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":B(this,$r,void 0),e.data.step_details.type=="tool_calls"&&w(this,Ue,"f")&&(this._emit("toolCallDone",w(this,Ue,"f")),B(this,Ue,void 0)),this._emit("runStepDone",e.data,t);break}},nd=function(e){w(this,Ri,"f").push(e),this._emit("event",e)},sd=function(e){switch(e.event){case"thread.run.step.created":return w(this,tt,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=w(this,tt,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){const s=xt.accumulateDelta(t,r.delta);w(this,tt,"f")[e.data.id]=s}return w(this,tt,"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":w(this,tt,"f")[e.data.id]=e.data;break}if(w(this,tt,"f")[e.data.id])return w(this,tt,"f")[e.data.id];throw new Error("No snapshot available")},ad=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];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(const a of s.delta.content)if(a.index in t.content){let i=t.content[a.index];t.content[a.index]=w(this,ye,"m",id).call(this,a,i)}else t.content[a.index]=a,r.push(a);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},id=function(e,t){return xt.accumulateDelta(t,e)},od=function(e){switch(B(this,es,e.data),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":B(this,kt,e.data),w(this,Ue,"f")&&(this._emit("toolCallDone",w(this,Ue,"f")),B(this,Ue,void 0));break}};let Ti=class extends z{constructor(){super(...arguments),this.steps=new ed(this._client)}create(e,t,r){const{include:s,...a}=t;return this._client.post(R`/threads/${e}/runs`,{query:{include:s},body:a,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}retrieve(e,t,r){const{thread_id:s}=t;return this._client.get(R`/threads/${s}/runs/${e}`,{...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{thread_id:s,...a}=t;return this._client.post(R`/threads/${s}/runs/${e}`,{body:a,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(R`/threads/${e}/runs`,oe,{query:t,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){const{thread_id:s}=t;return this._client.post(R`/threads/${s}/runs/${e}/cancel`,{...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){const s=await this.create(e,t,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,t,r){return Mr.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){const s=j([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:a,response:i}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...s}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{const u=i.headers.get("openai-poll-after-ms");if(u){const c=parseInt(u);isNaN(c)||(o=c)}}await Er(o);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,t,r){return Mr.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){const{thread_id:s,...a}=t;return this._client.post(R`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:a,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,r){const s=await this.submitToolOutputs(e,t,r);return await this.poll(s.id,t,r)}submitToolOutputsStream(e,t,r){return Mr.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};Ti.Steps=ed;class ts extends z{constructor(){super(...arguments),this.runs=new Ti(this._client),this.messages=new Yl(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(R`/threads/${e}`,{...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(R`/threads/${e}`,{body:t,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(R`/threads/${e}`,{...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){const r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return Mr.createThreadAssistantStream(e,this._client.beta.threads,t)}}ts.Runs=Ti,ts.Messages=Yl;class Dr extends z{constructor(){super(...arguments),this.realtime=new Kn(this._client),this.assistants=new Kl(this._client),this.threads=new ts(this._client)}}Dr.Realtime=Kn,Dr.Assistants=Kl,Dr.Threads=ts;class ud extends z{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class cd extends z{retrieve(e,t,r){const{container_id:s}=t;return this._client.get(R`/containers/${s}/files/${e}/content`,{...r,headers:j([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}let xi=class extends z{constructor(){super(...arguments),this.content=new cd(this._client)}create(e,t,r){return this._client.post(R`/containers/${e}/files`,Tt({body:t,...r},this._client))}retrieve(e,t,r){const{container_id:s}=t;return this._client.get(R`/containers/${s}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(R`/containers/${e}/files`,oe,{query:t,...r})}delete(e,t,r){const{container_id:s}=t;return this._client.delete(R`/containers/${s}/files/${e}`,{...r,headers:j([{Accept:"*/*"},r?.headers])})}};xi.Content=cd;class ki extends z{constructor(){super(...arguments),this.files=new xi(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(R`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",oe,{query:e,...t})}delete(e,t){return this._client.delete(R`/containers/${e}`,{...t,headers:j([{Accept:"*/*"},t?.headers])})}}ki.Files=xi;let ld=class extends z{create(e,t){const r=!!e.encoding_format;let s=r?e.encoding_format:"base64";r&&_e(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const a=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return r?a:(_e(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(i=>(i&&i.data&&i.data.forEach(o=>{const u=o.embedding;o.embedding=cy(u)}),i)))}};class dd extends z{retrieve(e,t,r){const{eval_id:s,run_id:a}=t;return this._client.get(R`/evals/${s}/runs/${a}/output_items/${e}`,r)}list(e,t,r){const{eval_id:s,...a}=t;return this._client.getAPIList(R`/evals/${s}/runs/${e}/output_items`,oe,{query:a,...r})}}class Pi extends z{constructor(){super(...arguments),this.outputItems=new dd(this._client)}create(e,t,r){return this._client.post(R`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){const{eval_id:s}=t;return this._client.get(R`/evals/${s}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(R`/evals/${e}/runs`,oe,{query:t,...r})}delete(e,t,r){const{eval_id:s}=t;return this._client.delete(R`/evals/${s}/runs/${e}`,r)}cancel(e,t,r){const{eval_id:s}=t;return this._client.post(R`/evals/${s}/runs/${e}`,r)}}Pi.OutputItems=dd;class Ci extends z{constructor(){super(...arguments),this.runs=new Pi(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(R`/evals/${e}`,t)}update(e,t,r){return this._client.post(R`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",oe,{query:e,...t})}delete(e,t){return this._client.delete(R`/evals/${e}`,t)}}Ci.Runs=Pi;let hd=class extends z{create(e,t){return this._client.post("/files",Tt({body:e,...t},this._client))}retrieve(e,t){return this._client.get(R`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",oe,{query:e,...t})}delete(e,t){return this._client.delete(R`/files/${e}`,t)}content(e,t){return this._client.get(R`/files/${e}/content`,{...t,headers:j([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=1800*1e3}={}){const s=new Set(["processed","error","deleted"]),a=Date.now();let i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await Er(t),i=await this.retrieve(e),Date.now()-a>r)throw new xn({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};class fd extends z{}let pd=class extends z{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})}};class Ni extends z{constructor(){super(...arguments),this.graders=new pd(this._client)}}Ni.Graders=pd;class md extends z{create(e,t,r){return this._client.getAPIList(R`/fine_tuning/checkpoints/${e}/permissions`,jn,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(R`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){const{fine_tuned_model_checkpoint:s}=t;return this._client.delete(R`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}}let $i=class extends z{constructor(){super(...arguments),this.permissions=new md(this._client)}};$i.Permissions=md;class gd extends z{list(e,t={},r){return this._client.getAPIList(R`/fine_tuning/jobs/${e}/checkpoints`,oe,{query:t,...r})}}class Li extends z{constructor(){super(...arguments),this.checkpoints=new gd(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(R`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",oe,{query:e,...t})}cancel(e,t){return this._client.post(R`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(R`/fine_tuning/jobs/${e}/events`,oe,{query:t,...r})}pause(e,t){return this._client.post(R`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(R`/fine_tuning/jobs/${e}/resume`,t)}}Li.Checkpoints=gd;class Xt extends z{constructor(){super(...arguments),this.methods=new fd(this._client),this.jobs=new Li(this._client),this.checkpoints=new $i(this._client),this.alpha=new Ni(this._client)}}Xt.Methods=fd,Xt.Jobs=Li,Xt.Checkpoints=$i,Xt.Alpha=Ni;class _d extends z{}class ji extends z{constructor(){super(...arguments),this.graderModels=new _d(this._client)}}ji.GraderModels=_d;class yd extends z{createVariation(e,t){return this._client.post("/images/variations",Tt({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",Tt({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})}}class bd extends z{retrieve(e,t){return this._client.get(R`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",jn,e)}delete(e,t){return this._client.delete(R`/models/${e}`,t)}}class wd extends z{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function ly(n,e){return!e||!hy(e)?{...n,output_parsed:null,output:n.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:vd(n,e)}function vd(n,e){const t=n.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:my(e,s)};if(s.type==="message"){const a=s.content.map(i=>i.type==="output_text"?{...i,parsed:dy(e,i.text)}:i);return{...s,content:a}}return s}),r=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||Mi(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(const s of r.output)if(s.type==="message"){for(const a of s.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),r}function dy(n,e){return n.text?.format?.type!=="json_schema"?null:"$parseRaw"in n.text?.format?(n.text?.format).$parseRaw(e):JSON.parse(e)}function hy(n){return!!di(n.text?.format)}function fy(n){return n?.$brand==="auto-parseable-tool"}function py(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function my(n,e){const t=py(n.tools??[],e.name);return{...e,...e,parsed_arguments:fy(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Mi(n){const e=[];for(const t of n.output)if(t.type==="message")for(const r of t.content)r.type==="output_text"&&e.push(r.text);n.output_text=e.join("")}var Qt,rs,vt,ns,Ed,Sd,Ad,Od;class Di extends pi{constructor(e){super(),Qt.add(this),rs.set(this,void 0),vt.set(this,void 0),ns.set(this,void 0),B(this,rs,e)}static createResponse(e,t,r){const s=new Di(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,r){const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),w(this,Qt,"m",Ed).call(this);let a,i=null;"response_id"in t?(a=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):a=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(const o of a)w(this,Qt,"m",Sd).call(this,o,i);if(a.controller.signal?.aborted)throw new je;return w(this,Qt,"m",Ad).call(this)}[(rs=new WeakMap,vt=new WeakMap,ns=new WeakMap,Qt=new WeakSet,Ed=function(){this.ended||B(this,vt,void 0)},Sd=function(t,r){if(this.ended)return;const s=(i,o)=>{(r==null||o.sequence_number>r)&&this._emit(i,o)},a=w(this,Qt,"m",Od).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{const i=a.output[t.output_index];if(!i)throw new L(`missing output at index ${t.output_index}`);if(i.type==="message"){const o=i.content[t.content_index];if(!o)throw new L(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new L(`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":{const i=a.output[t.output_index];if(!i)throw new L(`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}},Ad=function(){if(this.ended)throw new L("stream has ended, this shouldn\'t happen");const t=w(this,vt,"f");if(!t)throw new L("request ended without sending any events");B(this,vt,void 0);const r=gy(t,w(this,rs,"f"));return B(this,ns,r),r},Od=function(t){let r=w(this,vt,"f");if(!r){if(t.type!=="response.created")throw new L(`When snapshot hasn\'t been set yet, expected \'response.created\' event, got ${t.type}`);return r=B(this,vt,t.response),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{const s=r.output[t.output_index];if(!s)throw new L(`missing output at index ${t.output_index}`);s.type==="message"&&s.content.push(t.part);break}case"response.output_text.delta":{const s=r.output[t.output_index];if(!s)throw new L(`missing output at index ${t.output_index}`);if(s.type==="message"){const a=s.content[t.content_index];if(!a)throw new L(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new L(`expected content to be \'output_text\', got ${a.type}`);a.text+=t.delta}break}case"response.function_call_arguments.delta":{const s=r.output[t.output_index];if(!s)throw new L(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{B(this,vt,t.response);break}}return r},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",s=>{const a=t.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(const a of t)a.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{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();const e=w(this,ns,"f");if(!e)throw new L("stream ended without producing a ChatCompletion");return e}}function gy(n,e){return ly(n,e)}class Id extends z{list(e,t={},r){return this._client.getAPIList(R`/responses/${e}/input_items`,oe,{query:t,...r})}}class Ui extends z{constructor(){super(...arguments),this.inputItems=new Id(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Mi(r),r))}retrieve(e,t={},r){return this._client.get(R`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Mi(s),s))}delete(e,t){return this._client.delete(R`/responses/${e}`,{...t,headers:j([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>vd(r,e))}stream(e,t){return Di.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(R`/responses/${e}/cancel`,t)}}Ui.InputItems=Id;class Rd extends z{create(e,t,r){return this._client.post(R`/uploads/${e}/parts`,Tt({body:t,...r},this._client))}}class Fi extends z{constructor(){super(...arguments),this.parts=new Rd(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(R`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(R`/uploads/${e}/complete`,{body:t,...r})}}Fi.Parts=Rd;const _y=async n=>{const e=await Promise.allSettled(n),t=e.filter(s=>s.status==="rejected");if(t.length){for(const s of t)console.error(s.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}const r=[];for(const s of e)s.status==="fulfilled"&&r.push(s.value);return r};class Td extends z{create(e,t,r){return this._client.post(R`/vector_stores/${e}/file_batches`,{body:t,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{vector_store_id:s}=t;return this._client.get(R`/vector_stores/${s}/file_batches/${e}`,{...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){const{vector_store_id:s}=t;return this._client.post(R`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){const s=await this.create(e,t);return await this.poll(e,s.id,r)}listFiles(e,t,r){const{vector_store_id:s,...a}=t;return this._client.getAPIList(R`/vector_stores/${s}/file_batches/${e}/files`,oe,{query:a,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){const s=j([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:a,response:i}=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse();switch(a.status){case"in_progress":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{const u=i.headers.get("openai-poll-after-ms");if(u){const c=parseInt(u);isNaN(c)||(o=c)}}await Er(o);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},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");const a=s?.maxConcurrency??5,i=Math.min(a,t.length),o=this._client,u=t.values(),c=[...r];async function l(h){for(let f of h){const p=await o.files.create({file:f,purpose:"assistants"},s);c.push(p.id)}}const d=Array(i).fill(u).map(l);return await _y(d),await this.createAndPoll(e,{file_ids:c})}}class xd extends z{create(e,t,r){return this._client.post(R`/vector_stores/${e}/files`,{body:t,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{vector_store_id:s}=t;return this._client.get(R`/vector_stores/${s}/files/${e}`,{...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{vector_store_id:s,...a}=t;return this._client.post(R`/vector_stores/${s}/files/${e}`,{body:a,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(R`/vector_stores/${e}/files`,oe,{query:t,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){const{vector_store_id:s}=t;return this._client.delete(R`/vector_stores/${s}/files/${e}`,{...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){const s=await this.create(e,t,r);return await this.poll(e,s.id,r)}async poll(e,t,r){const s=j([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const a=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse(),i=a.data;switch(i.status){case"in_progress":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{const u=a.response.headers.get("openai-poll-after-ms");if(u){const c=parseInt(u);isNaN(c)||(o=c)}}await Er(o);break;case"failed":case"completed":return i}}}async upload(e,t,r){const s=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,t,r){const s=await this.upload(e,t,r);return await this.poll(e,s.id,r)}content(e,t,r){const{vector_store_id:s}=t;return this._client.getAPIList(R`/vector_stores/${s}/files/${e}/content`,jn,{...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class ss extends z{constructor(){super(...arguments),this.files=new xd(this._client),this.fileBatches=new Td(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(R`/vector_stores/${e}`,{...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(R`/vector_stores/${e}`,{body:t,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",oe,{query:e,...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(R`/vector_stores/${e}`,{...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(R`/vector_stores/${e}/search`,jn,{body:t,method:"post",...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}ss.Files=xd,ss.FileBatches=Td;var Yt,kd,as;class Pd extends z{constructor(){super(...arguments),Yt.add(this)}async unwrap(e,t,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,r,s),JSON.parse(e)}async verifySignature(e,t,r=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");w(this,Yt,"m",kd).call(this,r);const a=j([t]).values,i=w(this,Yt,"m",as).call(this,a,"webhook-signature"),o=w(this,Yt,"m",as).call(this,a,"webhook-timestamp"),u=w(this,Yt,"m",as).call(this,a,"webhook-id"),c=parseInt(o,10);if(isNaN(c))throw new vr("Invalid webhook timestamp format");const l=Math.floor(Date.now()/1e3);if(l-c>s)throw new vr("Webhook timestamp is too old");if(c>l+s)throw new vr("Webhook timestamp is too new");const d=i.split(" ").map(m=>m.startsWith("v1,")?m.substring(3):m),h=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),f=u?`${u}.${o}.${e}`:`${o}.${e}`,p=await crypto.subtle.importKey("raw",h,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const m of d)try{const g=Buffer.from(m,"base64");if(await crypto.subtle.verify("HMAC",p,g,new TextEncoder().encode(f)))return}catch{continue}throw new vr("The given webhook signature does not match the expected signature")}}Yt=new WeakSet,kd=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")},as=function(e,t){if(!e)throw new Error("Headers are required");const r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var Bi,zi,is,Cd;let Z=class{constructor({baseURL:e=ot("OPENAI_BASE_URL"),apiKey:t=ot("OPENAI_API_KEY"),organization:r=ot("OPENAI_ORG_ID")??null,project:s=ot("OPENAI_PROJECT_ID")??null,webhookSecret:a=ot("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(Bi.add(this),is.set(this,void 0),this.completions=new ud(this),this.chat=new Ii(this),this.embeddings=new ld(this),this.files=new hd(this),this.images=new yd(this),this.audio=new Nr(this),this.moderations=new wd(this),this.models=new bd(this),this.fineTuning=new Xt(this),this.graders=new ji(this),this.vectorStores=new ss(this),this.webhooks=new Pd(this),this.beta=new Dr(this),this.batches=new Jl(this),this.uploads=new Fi(this),this.responses=new Ui(this),this.evals=new Ci(this),this.containers=new ki(this),t===void 0)throw new L("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\' }).");const o={apiKey:t,organization:r,project:s,webhookSecret:a,...i,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&b_())throw new L(`It looks like you\'re running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the \\`dangerouslyAllowBrowser\\` option to \\`true\\`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n`);this.baseURL=o.baseURL,this.timeout=o.timeout??zi.DEFAULT_TIMEOUT,this.logger=o.logger??console;const u="warn";this.logLevel=u,this.logLevel=dl(o.logLevel,"ClientOptions.logLevel",this)??dl(ot("OPENAI_LOG"),"process.env[\'OPENAI_LOG\']",this)??u,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??A_(),B(this,is,I_),this._options=o,this.apiKey=t,this.organization=r,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 j([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return C_(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Zt}`}defaultIdempotencyKey(){return`stainless-node-retry-${jc()}`}makeStatusError(e,t,r,s){return ge.generate(e,t,r,s)}buildURL(e,t,r){const s=!w(this,Bi,"m",Cd).call(this)&&r||this.baseURL,a=f_(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return m_(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:r}){}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,r){return this.request(Promise.resolve(r).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new $n(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){const s=await e,a=s.maxRetries??this.maxRetries;t==null&&(t=a),await this.prepareOptions(s);const{req:i,url:o,timeout:u}=await this.buildRequest(s,{retryCount:a-t});await this.prepareRequest(i,{url:o,options:s});const c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(_e(this).debug(`[${c}] sending request`,Rt({retryOfRequestLogID:r,method:s.method,url:o,options:s,headers:i.headers})),s.signal?.aborted)throw new je;const h=new AbortController,f=await this.fetchWithTimeout(o,i,u,h).catch(si),p=Date.now();if(f instanceof Error){const y=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new je;const _=ni(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return _e(this).info(`[${c}] connection ${_?"timed out":"failed"} - ${y}`),_e(this).debug(`[${c}] connection ${_?"timed out":"failed"} (${y})`,Rt({retryOfRequestLogID:r,url:o,durationMs:p-d,message:f.message})),this.retryRequest(s,t,r??c);throw _e(this).info(`[${c}] connection ${_?"timed out":"failed"} - error; no more retries left`),_e(this).debug(`[${c}] connection ${_?"timed out":"failed"} (error; no more retries left)`,Rt({retryOfRequestLogID:r,url:o,durationMs:p-d,message:f.message})),_?new xn:new Tn({cause:f})}const m=[...f.headers.entries()].filter(([y])=>y==="x-request-id").map(([y,_])=>", "+y+": "+JSON.stringify(_)).join(""),g=`[${c}${l}${m}] ${i.method} ${o} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${p-d}ms`;if(!f.ok){const y=await this.shouldRetry(f);if(t&&y){const P=`retrying, ${t} attempts remaining`;return await O_(f.body),_e(this).info(`${g} - ${P}`),_e(this).debug(`[${c}] response error (${P})`,Rt({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:p-d})),this.retryRequest(s,t,r??c,f.headers)}const _=y?"error; no more retries left":"error; not retryable";_e(this).info(`${g} - ${_}`);const b=await f.text().catch(P=>si(P).message),E=y_(b),v=E?void 0:b;throw _e(this).debug(`[${c}] response error (${_})`,Rt({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,message:v,durationMs:Date.now()-d})),this.makeStatusError(f.status,E,v,f.headers)}return _e(this).info(g),_e(this).debug(`[${c}] response start`,Rt({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:p-d})),{response:f,options:s,controller:h,requestLogID:c,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}requestAPIList(e,t){const r=this.makeRequest(t,null,void 0);return new B_(this,r,e)}async fetchWithTimeout(e,t,r,s){const{signal:a,method:i,...o}=t||{};a&&a.addEventListener("abort",()=>s.abort());const u=setTimeout(()=>s.abort(),r),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){const 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,r,s){let a;const i=s?.get("retry-after-ms");if(i){const u=parseFloat(i);Number.isNaN(u)||(a=u)}const o=s?.get("retry-after");if(o&&!a){const u=parseFloat(o);Number.isNaN(u)?a=Date.parse(o)-Date.now():a=u*1e3}if(!(a&&0<=a&&a<60*1e3)){const u=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,u)}return await Er(a),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){const 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}={}){const r={...e},{method:s,path:a,query:i,defaultBaseURL:o}=r,u=this.buildURL(a,i,o);"timeout"in r&&__("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:c,body:l}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:s,bodyHeaders:c,retryCount:t});return{req:{method:s,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...r.fetchOptions??{}},url:u,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let a={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);const i=j([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))}:{},...S_(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const r=j([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.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:Qc(e)}:w(this,is,"f").call(this,{body:e,headers:r})}};zi=Z,is=new WeakMap,Bi=new WeakSet,Cd=function(){return this.baseURL!=="https://api.openai.com/v1"},Z.OpenAI=zi,Z.DEFAULT_TIMEOUT=6e5,Z.OpenAIError=L,Z.APIError=ge,Z.APIConnectionError=Tn,Z.APIConnectionTimeoutError=xn,Z.APIUserAbortError=je,Z.NotFoundError=Fc,Z.ConflictError=Bc,Z.RateLimitError=qc,Z.BadRequestError=Mc,Z.AuthenticationError=Dc,Z.InternalServerError=Hc,Z.PermissionDeniedError=Uc,Z.UnprocessableEntityError=zc,Z.InvalidWebhookSignatureError=vr,Z.toFile=Z_,Z.Completions=ud,Z.Chat=Ii,Z.Embeddings=ld,Z.Files=hd,Z.Images=yd,Z.Audio=Nr,Z.Moderations=wd,Z.Models=bd,Z.FineTuning=Xt,Z.Graders=ji,Z.VectorStores=ss,Z.Webhooks=Pd,Z.Beta=Dr,Z.Batches=Jl,Z.Uploads=Fi,Z.Responses=Ui,Z.Evals=Ci,Z.Containers=ki;let yy=class extends Z{constructor({baseURL:e=ot("OPENAI_BASE_URL"),apiKey:t=ot("AZURE_OPENAI_API_KEY"),apiVersion:r=ot("OPENAI_API_VERSION"),endpoint:s,deployment:a,azureADTokenProvider:i,dangerouslyAllowBrowser:o,...u}={}){if(!r)throw new L("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: \'My API Version\' }).");if(typeof i=="function"&&(o=!0),!i&&!t)throw new L("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(i&&t)throw new L("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(t??(t=Nd),u.defaultQuery={...u.defaultQuery,"api-version":r},e){if(s)throw new L("baseURL and endpoint are mutually exclusive")}else{if(s||(s=process.env.AZURE_OPENAI_ENDPOINT),!s)throw new L("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${s}/openai`}super({apiKey:t,baseURL:e,...u,...o!==void 0?{dangerouslyAllowBrowser:o}:{}}),this.apiVersion="",this._azureADTokenProvider=i,this.apiVersion=r,this.deploymentName=a}async buildRequest(e,t={}){if(by.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!kn(e.body))throw new Error("Expected request body to be an object");const r=this.deploymentName||e.body.model||e.__metadata?.model;r!==void 0&&!this.baseURL.includes("/deployments")&&(e.path=`/deployments/${r}${e.path}`)}return super.buildRequest(e,t)}async _getAzureADToken(){if(typeof this._azureADTokenProvider=="function"){const e=await this._azureADTokenProvider();if(!e||typeof e!="string")throw new L(`Expected \'azureADTokenProvider\' argument to return a string but it returned ${e}`);return e}}async authHeaders(e){}async prepareOptions(e){if(e.headers=j([e.headers]),e.headers.values.get("Authorization")||e.headers.values.get("api-key"))return super.prepareOptions(e);const t=await this._getAzureADToken();if(t)e.headers.values.set("Authorization",`Bearer ${t}`);else if(this.apiKey!==Nd)e.headers.values.set("api-key",this.apiKey);else throw new L("Unable to handle auth");return super.prepareOptions(e)}};const by=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]),Nd="<Missing Key>";var Ur={},$d;function wy(){if($d)return Ur;$d=1,Ur.byteLength=o,Ur.toByteArray=c,Ur.fromByteArray=h;for(var n=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,a=r.length;s<a;++s)n[s]=r[s],e[r.charCodeAt(s)]=s;e[45]=62,e[95]=63;function i(f){var p=f.length;if(p%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var m=f.indexOf("=");m===-1&&(m=p);var g=m===p?0:4-m%4;return[m,g]}function o(f){var p=i(f),m=p[0],g=p[1];return(m+g)*3/4-g}function u(f,p,m){return(p+m)*3/4-m}function c(f){var p,m=i(f),g=m[0],y=m[1],_=new t(u(f,g,y)),b=0,E=y>0?g-4:g,v;for(v=0;v<E;v+=4)p=e[f.charCodeAt(v)]<<18|e[f.charCodeAt(v+1)]<<12|e[f.charCodeAt(v+2)]<<6|e[f.charCodeAt(v+3)],_[b++]=p>>16&255,_[b++]=p>>8&255,_[b++]=p&255;return y===2&&(p=e[f.charCodeAt(v)]<<2|e[f.charCodeAt(v+1)]>>4,_[b++]=p&255),y===1&&(p=e[f.charCodeAt(v)]<<10|e[f.charCodeAt(v+1)]<<4|e[f.charCodeAt(v+2)]>>2,_[b++]=p>>8&255,_[b++]=p&255),_}function l(f){return n[f>>18&63]+n[f>>12&63]+n[f>>6&63]+n[f&63]}function d(f,p,m){for(var g,y=[],_=p;_<m;_+=3)g=(f[_]<<16&16711680)+(f[_+1]<<8&65280)+(f[_+2]&255),y.push(l(g));return y.join("")}function h(f){for(var p,m=f.length,g=m%3,y=[],_=16383,b=0,E=m-g;b<E;b+=_)y.push(d(f,b,b+_>E?E:b+_));return g===1?(p=f[m-1],y.push(n[p>>2]+n[p<<4&63]+"==")):g===2&&(p=(f[m-2]<<8)+f[m-1],y.push(n[p>>10]+n[p>>4&63]+n[p<<2&63]+"=")),y.join("")}return Ur}var vy=wy(),Ey=tr(vy),Sy=Object.defineProperty,Ay=(n,e,t)=>e in n?Sy(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Oy=(n,e,t)=>(Ay(n,e+"",t),t);function Iy(n,e){let t=Array.from({length:n.length},(r,s)=>({start:s,end:s+1}));for(;t.length>1;){let r=null;for(let s=0;s<t.length-1;s++){const a=n.slice(t[s].start,t[s+1].end),i=e.get(a.join(","));i!=null&&(r==null||i<r[0])&&(r=[i,s])}if(r!=null){const s=r[1];t[s]={start:t[s].start,end:t[s+1].end},t.splice(s+1,1)}else break}return t}function Ry(n,e){return n.length===1?[e.get(n.join(","))]:Iy(n,e).map(t=>e.get(n.slice(t.start,t.end).join(","))).filter(t=>t!=null)}function Ty(n){return n.replace(/[\\\\^$*+?.()|[\\]{}]/g,"\\\\$&")}var qi=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(n,e){this.patStr=n.pat_str;const t=n.bpe_ranks.split(`\n`).filter(Boolean).reduce((r,s)=>{const[a,i,...o]=s.split(" "),u=Number.parseInt(i,10);return o.forEach((c,l)=>r[c]=u+l),r},{});for(const[r,s]of Object.entries(t)){const a=Ey.toByteArray(r);this.rankMap.set(a.join(","),s),this.textMap.set(s,a)}this.specialTokens={...n.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((r,[s,a])=>(r[a]=this.textEncoder.encode(s),r),{})}encode(n,e=[],t="all"){const r=new RegExp(this.patStr,"ug"),s=qi.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){const c=qi.specialTokenRegex([...o]),l=n.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(n),!(c==null||i.has(c[0]));)l=c.index+1;const d=c?.index??n.length;for(const f of n.substring(u,d).matchAll(r)){const p=this.textEncoder.encode(f[0]),m=this.rankMap.get(p.join(","));if(m!=null){a.push(m);continue}a.push(...Ry(p,this.rankMap))}if(c==null)break;let h=this.specialTokens[c[0]];a.push(h),u=c.index+c[0].length}return a}decode(n){const e=[];let t=0;for(let a=0;a<n.length;++a){const i=n[a],o=this.textMap.get(i)??this.inverseSpecialTokens[i];o!=null&&(e.push(o),t+=o.length)}const r=new Uint8Array(t);let s=0;for(const a of e)r.set(a,s),s+=a.length;return this.textDecoder.decode(r)}},xy=qi;Oy(xy,"specialTokenRegex",n=>new RegExp(n.map(e=>Ty(e)).join("|"),"g"));function Ld(n){const{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:t,azureOpenAIApiKey:r,azureOpenAIBasePath:s,baseURL:a,azureADTokenProvider:i,azureOpenAIEndpoint:o}=n;if((r||i)&&s&&e)return`${s}/${e}`;if((r||i)&&o&&e)return`${o}/openai/deployments/${e}`;if(r||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}function os(n,e){return n.lc_error_code=e,n.message=`${n.message}\n\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/\n`,n}function jd(n){let e;return n.constructor.name===xn.name?(e=new Error(n.message),e.name="TimeoutError"):n.constructor.name===je.name?(e=new Error(n.message),e.name="AbortError"):n.status===400&&n.message.includes("tool_calls")?e=os(n,"INVALID_TOOL_RESULTS"):n.status===401?e=os(n,"MODEL_AUTHENTICATION"):n.status===429?e=os(n,"MODEL_RATE_LIMIT"):n.status===404?e=os(n,"MODEL_NOT_FOUND"):e=n,e}const ky=n=>n();function Md(n){return typeof Headers<"u"&&n!==null&&typeof n=="object"&&Object.prototype.toString.call(n)==="[object Headers]"}function Py(n){const e=ky(()=>{if(Md(n))return n;if(Array.isArray(n))return new Headers(n);if(typeof n=="object"&&n!==null&&"values"in n&&Md(n.values))return n.values;if(typeof n=="object"&&n!==null){const t=Object.entries(n).filter(([,r])=>typeof r=="string").map(([r,s])=>[r,s]);return new Headers(t)}return new Headers});return Object.fromEntries(e.entries())}const Cy=(n,e)=>n.reduce((t,r,s)=>{const a=Math.floor(s/e),i=t[a]||[];return t[a]=i.concat([r]),t},[]);class Ny{constructor(e){Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.caller=new pc(e??{})}}class $y extends Ny{constructor(e){const t={maxConcurrency:2,...e};super(t),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"text-embedding-ada-002"}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSize",{enumerable:!0,configurable:!0,writable:!0,value:512}),Object.defineProperty(this,"stripNewLines",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"dimensions",{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,"organization",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"encodingFormat",{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});const r=t?.apiKey??t?.openAIApiKey??Re("OPENAI_API_KEY");this.organization=t?.configuration?.organization??Re("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelName=this.model,this.batchSize=t?.batchSize??this.batchSize,this.stripNewLines=t?.stripNewLines??this.stripNewLines,this.timeout=t?.timeout,this.dimensions=t?.dimensions,this.encodingFormat=t?.encodingFormat,this.clientConfig={apiKey:r,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration}}async embedDocuments(e){const t=Cy(this.stripNewLines?e.map(i=>i.replace(/\\n/g," ")):e,this.batchSize),r=t.map(i=>{const o={model:this.model,input:i};return this.dimensions&&(o.dimensions=this.dimensions),this.encodingFormat&&(o.encoding_format=this.encodingFormat),this.embeddingWithRetry(o)}),s=await Promise.all(r),a=[];for(let i=0;i<s.length;i+=1){const o=t[i],{data:u}=s[i];for(let c=0;c<o.length;c+=1)a.push(u[c].embedding)}return a}async embedQuery(e){const t={model:this.model,input:this.stripNewLines?e.replace(/\\n/g," "):e};this.dimensions&&(t.dimensions=this.dimensions),this.encodingFormat&&(t.encoding_format=this.encodingFormat);const{data:r}=await this.embeddingWithRetry(t);return r[0].embedding}async embeddingWithRetry(e){if(!this.client){const r={baseURL:this.clientConfig.baseURL},s=Ld(r),a={...this.clientConfig,baseURL:s,timeout:this.timeout,maxRetries:0};a.baseURL||delete a.baseURL,this.client=new Z(a)}const t={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(e,t)}catch(r){throw jd(r)}})}}class Ly extends $y{constructor(e){super(e),Object.defineProperty(this,"azureOpenAIApiVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"azureOpenAIApiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"azureADTokenProvider",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"azureOpenAIApiInstanceName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"azureOpenAIApiDeploymentName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"azureOpenAIBasePath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.batchSize=e?.batchSize??1,this.azureOpenAIApiKey=e?.azureOpenAIApiKey??e?.apiKey??Re("AZURE_OPENAI_API_KEY"),this.azureOpenAIApiVersion=e?.azureOpenAIApiVersion??e?.openAIApiVersion??Re("AZURE_OPENAI_API_VERSION"),this.azureOpenAIBasePath=e?.azureOpenAIBasePath??Re("AZURE_OPENAI_BASE_PATH"),this.azureOpenAIApiInstanceName=e?.azureOpenAIApiInstanceName??Re("AZURE_OPENAI_API_INSTANCE_NAME"),this.azureOpenAIApiDeploymentName=(e?.azureOpenAIApiEmbeddingsDeploymentName||e?.azureOpenAIApiDeploymentName)??(Re("AZURE_OPENAI_API_EMBEDDINGS_DEPLOYMENT_NAME")||Re("AZURE_OPENAI_API_DEPLOYMENT_NAME")),this.azureADTokenProvider=e?.azureADTokenProvider}async embeddingWithRetry(e){if(!this.client){const r={azureOpenAIApiDeploymentName:this.azureOpenAIApiDeploymentName,azureOpenAIApiInstanceName:this.azureOpenAIApiInstanceName,azureOpenAIApiKey:this.azureOpenAIApiKey,azureOpenAIBasePath:this.azureOpenAIBasePath,azureADTokenProvider:this.azureADTokenProvider,baseURL:this.clientConfig.baseURL},s=Ld(r),a={...this.clientConfig,baseURL:s,timeout:this.timeout,maxRetries:0};this.azureADTokenProvider||(a.apiKey=r.azureOpenAIApiKey),a.baseURL||delete a.baseURL;const i=Py(a.defaultHeaders);a.defaultHeaders={...a.defaultHeaders,"User-Agent":i["User-Agent"]?`${i["User-Agent"]}: langchainjs-azure-openai-v2`:"langchainjs-azure-openai-v2"},this.client=new yy({apiVersion:this.azureOpenAIApiVersion,azureADTokenProvider:this.azureADTokenProvider,deployment:this.azureOpenAIApiDeploymentName,...a})}const t={};return this.azureOpenAIApiKey&&(t.headers={"api-key":this.azureOpenAIApiKey,...t.headers},t.query={"api-version":this.azureOpenAIApiVersion,...t.query}),this.caller.call(async()=>{try{return await this.client.embeddings.create(e,t)}catch(r){throw jd(r)}})}}const jy={"gpt-4.1":{deploymentName:"gpt-4.1",apiVersion:"2024-10-21",pathSegment:"models/gpt-4.1/openai/deployments/gpt-4.1/chat/completions"},"gpt-4.1-mini":{deploymentName:"gpt-4.1-mini",apiVersion:"2024-10-21",pathSegment:"models/gpt-4.1-mini/openai/deployments/gpt-4.1-mini/chat/completions"},"text-embedding-ada-002":{deploymentName:"text-embedding-ada-002",apiVersion:"2024-10-21",pathSegment:"models/text-embedding-ada-002/openai/deployments/text-embedding-ada-002/embeddings"}},My={default:"text-embedding-ada-002"},Dy=["x-stainless-package-version","x-stainless-timeout","x-stainless-retry-count","x-stainless-lang","x-stainless-os","x-stainless-arch","x-stainless-runtime","x-stainless-runtime-version","x-stainless-helper-method","api-key"],Uy=n=>async(e,t)=>{const r=new Headers(t?.headers);return Dy.forEach(s=>r.delete(s)),n&&n.length>0&&r.set("X-Esri-Authorization",`Bearer ${n}`),await fetch(e,{...t,headers:r})};let Ct,Nt;const us=new Map,Fy=12,By=10,zy=async n=>{if(!Ct)return;Nt?Nt.memoryVectors=[]:Nt=new Rn(Ct);const e=[];for(const[t,{layerItem:r}]of n.entries()){const s=`Name: ${r.name}\nTitle: ${r.title}\nDescription: ${r.description}`,a=new Vt({id:t,pageContent:s,metadata:{layerId:t}});e.push(a)}await Nt.addDocuments(e),console.log("Layer Vectorstore contents:",Nt.memoryVectors)},qy=async n=>{if(!Ct)return;us.clear();const e=[];for(const[t,{fieldRegistry:r}]of n.entries()){const s=[],a=[];for(const[u,c]of r.entries()){const l=`Name: ${c.name}\nAlias: ${c.alias}\nDescription: ${c.description}`;s.push(new Vt({id:u,pageContent:l,metadata:{layerId:t}})),a.push(l)}const i=new Rn(Ct),o=(async()=>{const u=await Ct.embedDocuments(a);await i.addVectors(u,s),us.set(t,i)})();e.push(o)}await Promise.all(e),console.log("Field Vectorstore contents:",Array.from(us.entries()).map(([t,r])=>({id:t,contents:r.memoryVectors})))};globalThis.addEventListener("message",n=>{(async()=>{const{type:e,layersAndFieldsRegistry:t,searchQuery:r,layerIdForFieldsSearch:s=[],requestId:a,auth:i}=n.data;switch(e){case"generateEmbeddings":{if(!i?.token||!i.apiUrl){globalThis.postMessage({type:"error",error:"Missing token or apiUrl"});break}const o=My.default,u=jy[o];Ct=new Ly({azureOpenAIApiKey:"x",azureOpenAIBasePath:i.apiUrl,azureOpenAIApiDeploymentName:u.deploymentName,azureOpenAIApiVersion:u.apiVersion,model:o,batchSize:2048,maxConcurrency:10,configuration:{fetch:Uy(i.token)}}),t&&(await zy(t),await qy(t)),globalThis.postMessage("completed");break}case"layerSearch":{if(r&&Nt){const o=await Nt.similaritySearchWithScore(r,By);globalThis.postMessage({requestId:a,results:o})}break}case"fieldSearch":{if(r&&s.length>0){const o=await Ct.embedQuery(r),u=s.map(async d=>{const h=us.get(d);if(!h)return null;const f=await h.similaritySearchVectorWithScore(o,Fy);return{layerId:d,results:f}}),l=(await Promise.all(u)).filter(Boolean);globalThis.postMessage({requestId:a,results:l});return}break}default:console.warn("Unknown message type:",e)}})()})})();\n', n = typeof self < "u" && self.Blob && new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);", s], { type: "text/javascript;charset=utf-8" });
|
|
2
|
+
function a(r) {
|
|
3
|
+
let e;
|
|
4
|
+
try {
|
|
5
|
+
if (e = n && (self.URL || self.webkitURL).createObjectURL(n), !e) throw "";
|
|
6
|
+
const t = new Worker(e, {
|
|
7
|
+
name: r?.name
|
|
8
|
+
});
|
|
9
|
+
return t.addEventListener("error", () => {
|
|
10
|
+
(self.URL || self.webkitURL).revokeObjectURL(e);
|
|
11
|
+
}), t;
|
|
12
|
+
} catch {
|
|
13
|
+
return new Worker(
|
|
14
|
+
"data:text/javascript;charset=utf-8," + encodeURIComponent(s),
|
|
15
|
+
{
|
|
16
|
+
name: r?.name
|
|
17
|
+
}
|
|
18
|
+
);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export {
|
|
22
|
+
a as default
|
|
23
|
+
};
|