@arcgis/ai-orchestrator 5.0.0-next.133
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/LICENSE.md +17 -0
- package/README.md +11 -0
- package/dist/commonFunctions/vectorSearchFields.d.ts +2 -0
- package/dist/commonFunctions/vectorSearchLayers.d.ts +4 -0
- package/dist/dispatcherAgent/dispatcherGraph.d.ts +3 -0
- package/dist/dispatcherAgent/nodes/executeRegisteredAgent.d.ts +3 -0
- package/dist/dispatcherAgent/nodes/exit.d.ts +3 -0
- package/dist/dispatcherAgent/nodes/ingestInput.d.ts +3 -0
- package/dist/dispatcherAgent/nodes/intentDispatcher.d.ts +2 -0
- package/dist/dispatcherAgent/nodes/intentLLM.d.ts +3 -0
- package/dist/dispatcherAgent/reducers/commonReducers.d.ts +1 -0
- package/dist/dispatcherAgent/state/dispatcherGraphState.d.ts +8 -0
- package/dist/embeddings.worker-19IRaTB4.js +23 -0
- package/dist/field_descriptions_prompt-haMV_aoG.js +111 -0
- package/dist/hitl/InterruptHandler.d.ts +30 -0
- package/dist/hitl/types.d.ts +24 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +8328 -0
- package/dist/intent_prompt-BjOozjFv.js +20 -0
- package/dist/layer_descriptions_prompt-NAaKWdJi.js +58 -0
- package/dist/llm/generateFieldDescriptions.d.ts +8 -0
- package/dist/llm/generateLayerAndFieldDescription.d.ts +7 -0
- package/dist/llm/generateLayerDescriptions.d.ts +22 -0
- package/dist/models/modelConfig.d.ts +28 -0
- package/dist/models/types.d.ts +2 -0
- package/dist/orchestrator/orchestrator.d.ts +70 -0
- package/dist/orchestrator/orchestratorEvents.d.ts +60 -0
- package/dist/prompts/getPrompt.d.ts +6 -0
- package/dist/providers/arcgis/aiUtilityService.d.ts +3 -0
- package/dist/providers/azure/azureChat.d.ts +6 -0
- package/dist/providers/azure/promptChain.d.ts +32 -0
- package/dist/providers/azure/sanitizedFetch.d.ts +5 -0
- package/dist/registry/agentRegistry.d.ts +26 -0
- package/dist/services/fieldSearch.d.ts +20 -0
- package/dist/services/layerSearch.d.ts +20 -0
- package/dist/signals/index.d.ts +24 -0
- package/dist/types/types.d.ts +55 -0
- package/dist/utils/cleanHistory.d.ts +2 -0
- package/dist/utils/contextSelectors.d.ts +10 -0
- package/dist/workers/embeddings.worker.d.ts +1 -0
- package/dist/workers/embeddingsWorkerSetup.d.ts +6 -0
- package/package.json +27 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
const s = '(function(){"use strict";var qd=/^(?:[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 zr(n){return typeof n=="string"&&qd.test(n)}for(var me=[],hs=0;hs<256;++hs)me.push((hs+256).toString(16).slice(1));function Hd(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 qr,Gd=new Uint8Array(16);function Vd(){if(!qr&&(qr=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!qr))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return qr(Gd)}var Zd=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Wi={randomUUID:Zd};function rt(n,e,t){if(Wi.randomUUID&&!n)return Wi.randomUUID();n=n||{};var r=n.random||(n.rng||Vd)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Hd(r)}function rr(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var fs,Ji;function Wd(){return Ji||(Ji=1,fs=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()}),fs}var Jd=Wd(),Kd=rr(Jd),Hr={exports:{}},Ki;function Xd(){if(Ki)return Hr.exports;Ki=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 Hr.exports=d,Hr.exports.default=d,Hr.exports}Xd();function Qd(n,e){return e?.[n]||Kd(n)}function Yd(n,e,t){const r={};for(const s in n)Object.hasOwn(n,s)&&(r[e(s,t)]=n[s]);return r}const Xi="__lc_escaped__";function eh(n){return"lc"in n||Object.keys(n).length===1&&Xi in n}function th(n){return{[Xi]:n}}function rh(n){return n!==null&&typeof n=="object"&&"lc_serializable"in n&&typeof n.toJSON=="function"}function ps(n){if(n!==null&&typeof n=="object"&&!Array.isArray(n)){if(rh(n))return n;const e=n;if(eh(e))return th(e);const t={};for(const[r,s]of Object.entries(e))t[r]=ps(s);return t}return Array.isArray(n)?n.map(e=>ps(e)):n}function Qi(n){return Array.isArray(n)?[...n]:{...n}}function nh(n,e){const t=Qi(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]=Qi(o[u]),o=o[u]}o[a]!==void 0&&(o[a]={lc:1,type:"secret",id:[s]})}return t}function Yi(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 St{static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Yi(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 St||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]=ps(u);const a=Object.keys(t).length?nh(s,t):s,i=Yd(a,Qd,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:i}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}const sh=()=>typeof window<"u"&&typeof window.document<"u",ah=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",ih=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),ms=()=>typeof Deno<"u",oh=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!ms(),uh=()=>{let n;return sh()?n="browser":oh()?n="node":ah()?n="webworker":ih()?n="jsdom":ms()?n="deno":n="other",n};let gs;function ch(){return gs===void 0&&(gs={library:"langchain-js",runtime:uh()}),gs}function xe(n){try{return typeof process<"u"?process.env?.[n]:ms()?Deno?.env.get(n):void 0}catch{return}}class lh{}class nr extends lh{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,Yi(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:xe("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 St.prototype.toJSON.call(this)}toJSONNotImplemented(){return St.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends nr{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:rt()}),Object.assign(this,e)}}return new t}}const dh=n=>{const e=n;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"};var Gr={exports:{}};Gr.exports;var eo;function hh(){return eo||(eo=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})})(Gr)),Gr.exports}var fh=hh(),to=rr(fh),ph=/^(?:[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 mh(n){return typeof n=="string"&&ph.test(n)}function gh(n){if(!mh(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 ge=[],_s=0;_s<256;++_s)ge.push((_s+256).toString(16).slice(1));function ro(n,e=0){return(ge[n[e+0]]+ge[n[e+1]]+ge[n[e+2]]+ge[n[e+3]]+"-"+ge[n[e+4]]+ge[n[e+5]]+"-"+ge[n[e+6]]+ge[n[e+7]]+"-"+ge[n[e+8]]+ge[n[e+9]]+"-"+ge[n[e+10]]+ge[n[e+11]]+ge[n[e+12]]+ge[n[e+13]]+ge[n[e+14]]+ge[n[e+15]]).toLowerCase()}var Vr,_h=new Uint8Array(16);function yh(){if(!Vr&&(Vr=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Vr))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Vr(_h)}function bh(n){n=unescape(encodeURIComponent(n));for(var e=[],t=0;t<n.length;++t)e.push(n.charCodeAt(t));return e}var wh="6ba7b810-9dad-11d1-80b4-00c04fd430c8",vh="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Eh(n,e,t){function r(s,a,i,o){var u;if(typeof s=="string"&&(s=bh(s)),typeof a=="string"&&(a=gh(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 ro(c)}try{r.name=n}catch{}return r.DNS=wh,r.URL=vh,r}var Sh=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),no={randomUUID:Sh};function jt(n,e,t){if(no.randomUUID&&!n)return no.randomUUID();n=n||{};var r=n.random||(n.rng||yh)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,ro(r)}function Ah(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 ys(n,e){return n<<e|n>>>32-e}function Oh(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]=ys(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),T=ys(m,5)+Ah(v,g,y,_)+b+e[v]+h[E]>>>0;b=_,_=y,y=ys(g,30)>>>0,g=m,m=T}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 so=Eh("v5",80,Oh);const Ih="gen_ai.operation.name",xh="gen_ai.system",ao="gen_ai.request.model",Rh="gen_ai.response.model",io="gen_ai.usage.input_tokens",oo="gen_ai.usage.output_tokens",uo="gen_ai.usage.total_tokens",Th="gen_ai.request.max_tokens",kh="gen_ai.request.temperature",Ph="gen_ai.request.top_p",Ch="gen_ai.request.frequency_penalty",$h="gen_ai.request.presence_penalty",Nh="gen_ai.response.finish_reasons",Lh="gen_ai.prompt",jh="gen_ai.completion",Mh="gen_ai.request.extra_query",Dh="gen_ai.request.extra_body",Uh="gen_ai.serialized.name",Fh="gen_ai.serialized.signature",Bh="gen_ai.serialized.doc",zh="gen_ai.response.id",qh="gen_ai.response.service_tier",Hh="gen_ai.response.system_fingerprint",Gh="gen_ai.usage.input_token_details",Vh="gen_ai.usage.output_token_details",Zh="langsmith.trace.session_id",Wh="langsmith.trace.session_name",Jh="langsmith.span.kind",Kh="langsmith.trace.name",Xh="langsmith.metadata",co="langsmith.span.tags",Qh="langsmith.request.streaming",Yh="langsmith.request.headers",ef=(...n)=>fetch(...n),lo=Symbol.for("ls:fetch_implementation"),tf=()=>{const n=globalThis[lo];return n?typeof n=="function"&&"Headers"in n&&"Request"in n&&"Response"in n:!1},rf=n=>async(...e)=>{if(n||Re("DEBUG")==="true"){const[r,s]=e;console.log(`→ ${s?.method||"GET"} ${r}`)}const t=await(globalThis[lo]??ef)(...e);return(n||Re("DEBUG")==="true")&&console.log(`← ${t.status} ${t.statusText} ${t.url}`),t},ho=()=>Re("PROJECT")??Xe("LANGCHAIN_SESSION")??"default",fo="0.3.74";let Ke;const nf=()=>typeof window<"u"&&typeof window.document<"u",sf=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",af=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),po=()=>typeof Deno<"u",of=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!po(),mo=()=>Ke||(typeof Bun<"u"?Ke="bun":nf()?Ke="browser":of()?Ke="node":sf()?Ke="webworker":af()?Ke="jsdom":po()?Ke="deno":Ke="other",Ke);let bs;function go(){if(bs===void 0){const n=mo(),e=cf();bs={library:"langsmith",runtime:n,sdk:"langsmith-js",sdk_version:fo,...e}}return bs}function _o(){const n=uf(),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 uf(){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 Re(n){return Xe(`LANGSMITH_${n}`)||Xe(`LANGCHAIN_${n}`)}let ws;function cf(){if(ws!==void 0)return ws;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 ws=e,e}function yo(){return Xe("OTEL_ENABLED")==="true"||Re("OTEL_ENABLED")==="true"}class lf{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){!this.hasWarned&&yo()&&(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 df{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new lf})}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 hf{active(){return{}}with(e,t){return t()}}const vs=Symbol.for("ls:otel_trace"),Es=Symbol.for("ls:otel_context"),bo=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),ff=new df,pf=new hf;class mf{getTraceInstance(){return globalThis[vs]??ff}getContextInstance(){return globalThis[Es]??pf}initializeGlobalInstances(e){globalThis[vs]===void 0&&(globalThis[vs]=e.trace),globalThis[Es]===void 0&&(globalThis[Es]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[bo]=e}getDefaultOTLPTracerComponents(){return globalThis[bo]??void 0}}const Ss=new mf;function wo(){return Ss.getTraceInstance()}function gf(){return Ss.getContextInstance()}function _f(){return Ss.getDefaultOTLPTracerComponents()}const yf={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function bf(n){return yf[n]||n}class wf{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&&wo().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(Jh,t.run_type);const o=bf(t.run_type||"chain");e.setAttribute(Ih,o)}"name"in t&&t.name&&e.setAttribute(Kh,t.name),"session_id"in t&&t.session_id&&e.setAttribute(Zh,t.session_id),"session_name"in t&&t.session_name&&e.setAttribute(Wh,t.session_name),this.setGenAiSystem(e,t);const s=this.extractModelName(t);s&&e.setAttribute(ao,s),"prompt_tokens"in t&&typeof t.prompt_tokens=="number"&&e.setAttribute(io,t.prompt_tokens),"completion_tokens"in t&&typeof t.completion_tokens=="number"&&e.setAttribute(oo,t.completion_tokens),"total_tokens"in t&&typeof t.total_tokens=="number"&&e.setAttribute(uo,t.total_tokens),this.setInvocationParameters(e,t);const a=t.extra?.metadata||{};for(const[o,u]of Object.entries(a))u!=null&&e.setAttribute(`${Xh}.${o}`,String(u));const i=t.tags;if(i&&Array.isArray(i)?e.setAttribute(co,i.join(", ")):i&&e.setAttribute(co,String(i)),"serialized"in t&&typeof t.serialized=="object"){const o=t.serialized;o.name&&e.setAttribute(Uh,String(o.name)),o.signature&&e.setAttribute(Fh,String(o.signature)),o.doc&&e.setAttribute(Bh,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(xh,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(Th,r.max_tokens),r.temperature!==void 0&&e.setAttribute(kh,r.temperature),r.top_p!==void 0&&e.setAttribute(Ph,r.top_p),r.frequency_penalty!==void 0&&e.setAttribute(Ch,r.frequency_penalty),r.presence_penalty!==void 0&&e.setAttribute($h,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(ao,r.model),r.stream!==void 0&&e.setAttribute(Qh,r.stream),r.extra_headers&&e.setAttribute(Yh,JSON.stringify(r.extra_headers)),r.extra_query&&e.setAttribute(Mh,JSON.stringify(r.extra_query)),r.extra_body&&e.setAttribute(Dh,JSON.stringify(r.extra_body))),e.setAttribute(Lh,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(io,s[0]),e.setAttribute(oo,s[1]),e.setAttribute(uo,s[0]+s[1])),r&&typeof r=="object"){if(r.model&&e.setAttribute(Rh,String(r.model)),r.id&&e.setAttribute(zh,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(Nh,a.join(", "))}if(r.service_tier&&e.setAttribute(qh,r.service_tier),r.system_fingerprint&&e.setAttribute(Hh,r.system_fingerprint),r.usage_metadata&&typeof r.usage_metadata=="object"){const a=r.usage_metadata;a.input_token_details&&e.setAttribute(Gh,JSON.stringify(a.input_token_details)),a.output_token_details&&e.setAttribute(Vh,JSON.stringify(a.output_token_details))}}e.setAttribute(jh,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 sr={exports:{}},As={},Os,vo;function vf(){if(vo)return Os;vo=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 Os=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},Os}var Eo;function Ef(){return Eo||(Eo=1,(function(n){var e=vf();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}}})(As)),As}var Is,So;function Sf(){return So||(So=1,Is=Ef()),Is}var Ao;function Af(){if(Ao)return sr.exports;Ao=1;const n=Sf(),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 sr.exports=a,sr.exports.default=a,sr.exports.AbortError=t,sr.exports}var Of=Af(),Zr=rr(Of),Wr={},xs={exports:{}},Oo;function If(){return Oo||(Oo=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})(xs)),xs.exports}var ar={exports:{}},Rs,Io;function xf(){return Io||(Io=1,Rs=(n,e)=>(e=e||(()=>{}),n.then(t=>new Promise(r=>{r(e())}).then(()=>t),t=>new Promise(r=>{r(e())}).then(()=>{throw t})))),Rs}var xo;function Rf(){if(xo)return ar.exports;xo=1;const n=xf();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 ar.exports=t,ar.exports.default=t,ar.exports.TimeoutError=e,ar.exports}var Jr={},Kr={},Ro;function Tf(){if(Ro)return Kr;Ro=1,Object.defineProperty(Kr,"__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 Kr.default=n,Kr}var To;function kf(){if(To)return Jr;To=1,Object.defineProperty(Jr,"__esModule",{value:!0});const n=Tf();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 Jr.default=e,Jr}var ko;function Pf(){if(ko)return Wr;ko=1,Object.defineProperty(Wr,"__esModule",{value:!0});const n=If(),e=Rf(),t=kf(),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 Wr.default=a,Wr}var Cf=Pf(),nt=rr(Cf);const $f=[429,500,502,503,504];let Po=class{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,"default"in nt?this.queue=new nt.default({concurrency:this.maxConcurrency}):this.queue=new nt({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){const r=this.onFailedResponseHook;return this.queue.add(()=>Zr(()=>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&&!$f.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 Co(n){return typeof n?._getType=="function"}function $o(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 Nf=/^[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(!Nf.test(n)){const t=e!==void 0?`Invalid UUID for ${e}: ${n}`:`Invalid UUID: ${n}`;throw new Error(t)}return n}const No={};function Ts(n){No[n]||(console.warn(n),No[n]=!0)}var Xr={exports:{}},ks,Lo;function Qr(){if(Lo)return ks;Lo=1;const n="2.0.0",e=256,t=Number.MAX_SAFE_INTEGER||9007199254740991,r=16,s=e-6;return ks={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},ks}var Ps,jo;function Yr(){return jo||(jo=1,Ps=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\\bsemver\\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{}),Ps}var Mo;function ir(){return Mo||(Mo=1,(function(n,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:s}=Qr(),a=Yr();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*$")})(Xr,Xr.exports)),Xr.exports}var Cs,Do;function $s(){if(Do)return Cs;Do=1;const n=Object.freeze({loose:!0}),e=Object.freeze({});return Cs=r=>r?typeof r!="object"?n:r:e,Cs}var Ns,Uo;function Fo(){if(Uo)return Ns;Uo=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 Ns={compareIdentifiers:e,rcompareIdentifiers:(r,s)=>e(s,r)},Ns}var Ls,Bo;function ve(){if(Bo)return Ls;Bo=1;const n=Yr(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:t}=Qr(),{safeRe:r,t:s}=ir(),a=$s(),{compareIdentifiers:i}=Fo();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 Ls=o,Ls}var js,zo;function Mt(){if(zo)return js;zo=1;const n=ve();return js=(t,r,s=!1)=>{if(t instanceof n)return t;try{return new n(t,r)}catch(a){if(!s)return null;throw a}},js}var Ms,qo;function Lf(){if(qo)return Ms;qo=1;const n=Mt();return Ms=(t,r)=>{const s=n(t,r);return s?s.version:null},Ms}var Ds,Ho;function jf(){if(Ho)return Ds;Ho=1;const n=Mt();return Ds=(t,r)=>{const s=n(t.trim().replace(/^[=v]+/,""),r);return s?s.version:null},Ds}var Us,Go;function Mf(){if(Go)return Us;Go=1;const n=ve();return Us=(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}},Us}var Fs,Vo;function Df(){if(Vo)return Fs;Vo=1;const n=Mt();return Fs=(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"},Fs}var Bs,Zo;function Uf(){if(Zo)return Bs;Zo=1;const n=ve();return Bs=(t,r)=>new n(t,r).major,Bs}var zs,Wo;function Ff(){if(Wo)return zs;Wo=1;const n=ve();return zs=(t,r)=>new n(t,r).minor,zs}var qs,Jo;function Bf(){if(Jo)return qs;Jo=1;const n=ve();return qs=(t,r)=>new n(t,r).patch,qs}var Hs,Ko;function zf(){if(Ko)return Hs;Ko=1;const n=Mt();return Hs=(t,r)=>{const s=n(t,r);return s&&s.prerelease.length?s.prerelease:null},Hs}var Gs,Xo;function qe(){if(Xo)return Gs;Xo=1;const n=ve();return Gs=(t,r,s)=>new n(t,s).compare(new n(r,s)),Gs}var Vs,Qo;function qf(){if(Qo)return Vs;Qo=1;const n=qe();return Vs=(t,r,s)=>n(r,t,s),Vs}var Zs,Yo;function Hf(){if(Yo)return Zs;Yo=1;const n=qe();return Zs=(t,r)=>n(t,r,!0),Zs}var Ws,eu;function Js(){if(eu)return Ws;eu=1;const n=ve();return Ws=(t,r,s)=>{const a=new n(t,s),i=new n(r,s);return a.compare(i)||a.compareBuild(i)},Ws}var Ks,tu;function Gf(){if(tu)return Ks;tu=1;const n=Js();return Ks=(t,r)=>t.sort((s,a)=>n(s,a,r)),Ks}var Xs,ru;function Vf(){if(ru)return Xs;ru=1;const n=Js();return Xs=(t,r)=>t.sort((s,a)=>n(a,s,r)),Xs}var Qs,nu;function en(){if(nu)return Qs;nu=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 iu(){if(au)return ta;au=1;const n=qe();return ta=(t,r,s)=>n(t,r,s)===0,ta}var ra,ou;function uu(){if(ou)return ra;ou=1;const n=qe();return ra=(t,r,s)=>n(t,r,s)!==0,ra}var na,cu;function sa(){if(cu)return na;cu=1;const n=qe();return na=(t,r,s)=>n(t,r,s)>=0,na}var aa,lu;function ia(){if(lu)return aa;lu=1;const n=qe();return aa=(t,r,s)=>n(t,r,s)<=0,aa}var oa,du;function hu(){if(du)return oa;du=1;const n=iu(),e=uu(),t=en(),r=sa(),s=ea(),a=ia();return oa=(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}`)}},oa}var ua,fu;function Zf(){if(fu)return ua;fu=1;const n=ve(),e=Mt(),{safeRe:t,t:r}=ir();return ua=(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)},ua}var ca,pu;function Wf(){if(pu)return ca;pu=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 ca=n,ca}var la,mu;function He(){if(mu)return la;mu=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(Lt(this.set[U],I,this.options))return!0;return!1}}la=e;const t=Wf(),r=new t,s=$s(),a=tn(),i=Yr(),o=ve(),{safeRe:u,t:c,comparatorTrimReplace:l,tildeTrimReplace:d,caretTrimReplace:h}=ir(),{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:p}=Qr(),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=T(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})},T=(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),Br=ue;return F==="="&&Br&&(F=""),W=I.includePrerelease?"-0":"",se?F===">"||F==="<"?M="<0.0.0-0":M="*":F&&Br?(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,Br)=>(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`:Br?W=`<=${se}.${Ie}.${ue}-${Br}`:k?W=`<${se}.${Ie}.${+ue+1}-0`:W=`<=${W}`,`${U} ${W}`.trim()),Lt=(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 la}var da,gu;function tn(){if(gu)return da;gu=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(">")))}}da=e;const t=$s(),{safeRe:r,t:s}=ir(),a=hu(),i=Yr(),o=ve(),u=He();return da}var ha,_u;function rn(){if(_u)return ha;_u=1;const n=He();return ha=(t,r,s)=>{try{r=new n(r,s)}catch{return!1}return r.test(t)},ha}var fa,yu;function Jf(){if(yu)return fa;yu=1;const n=He();return fa=(t,r)=>new n(t,r).set.map(s=>s.map(a=>a.value).join(" ").trim().split(" ")),fa}var pa,bu;function Kf(){if(bu)return pa;bu=1;const n=ve(),e=He();return pa=(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},pa}var ma,wu;function Xf(){if(wu)return ma;wu=1;const n=ve(),e=He();return ma=(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},ma}var ga,vu;function Qf(){if(vu)return ga;vu=1;const n=ve(),e=He(),t=en();return ga=(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},ga}var _a,Eu;function Yf(){if(Eu)return _a;Eu=1;const n=He();return _a=(t,r)=>{try{return new n(t,r).range||"*"}catch{return null}},_a}var ya,Su;function ba(){if(Su)return ya;Su=1;const n=ve(),e=tn(),{ANY:t}=e,r=He(),s=rn(),a=en(),i=ea(),o=ia(),u=sa();return ya=(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,T=null;if(E.forEach(P=>{P.semver===t&&(P=new e(">=0.0.0")),v=v||P,T=T||P,p(P.semver,v.semver,f)?v=P:g(P.semver,T.semver,f)&&(T=P)}),v.operator===y||v.operator===_||(!T.operator||T.operator===y)&&m(l,T.semver))return!1;if(T.operator===_&&g(l,T.semver))return!1}return!0},ya}var wa,Au;function ep(){if(Au)return wa;Au=1;const n=ba();return wa=(t,r,s)=>n(t,r,">",s),wa}var va,Ou;function tp(){if(Ou)return va;Ou=1;const n=ba();return va=(t,r,s)=>n(t,r,"<",s),va}var Ea,Iu;function rp(){if(Iu)return Ea;Iu=1;const n=He();return Ea=(t,r,s)=>(t=new n(t,s),r=new n(r,s),t.intersects(r,s)),Ea}var Sa,xu;function np(){if(xu)return Sa;xu=1;const n=rn(),e=qe();return Sa=(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},Sa}var Aa,Ru;function sp(){if(Ru)return Aa;Ru=1;const n=He(),e=tn(),{ANY:t}=e,r=rn(),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,T=g&&!f.includePrerelease&&g.semver.prerelease.length?g.semver:!1,P=m&&!f.includePrerelease&&m.semver.prerelease.length?m.semver:!1;T&&T.prerelease.length===1&&g.operator==="<"&&T.prerelease[0]===0&&(T=!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(T&&O.semver.prerelease&&O.semver.prerelease.length&&O.semver.major===T.major&&O.semver.minor===T.minor&&O.semver.patch===T.patch&&(T=!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||T)},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 Aa=a,Aa}var Oa,Tu;function ap(){if(Tu)return Oa;Tu=1;const n=ir(),e=Qr(),t=ve(),r=Fo(),s=Mt(),a=Lf(),i=jf(),o=Mf(),u=Df(),c=Uf(),l=Ff(),d=Bf(),h=zf(),f=qe(),p=qf(),m=Hf(),g=Js(),y=Gf(),_=Vf(),b=en(),E=ea(),v=iu(),T=uu(),P=sa(),O=ia(),J=hu(),K=Zf(),ne=tn(),Je=He(),Lt=rn(),k=Jf(),I=Kf(),U=Xf(),M=Qf(),F=Yf(),D=ba(),G=ep(),te=tp(),W=rp(),se=np(),Ie=sp();return Oa={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:T,gte:P,lte:O,cmp:J,coerce:K,Comparator:ne,Range:Je,satisfies:Lt,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},Oa}ap();function ct(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 ip 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(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 ip(s);const a=new Error(s);throw a.status=n.status,a}const ku="ERR_CONFLICTING_ENDPOINTS";class op 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:ku}),this.name="ConflictingEndpointsError"}}function up(n){return typeof n=="object"&&n!==null&&n.code===ku}var Pu="[...]",cp={result:"[Circular]"},nn=[],Dt=[];const lp=new TextEncoder;function dp(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function sn(n){return lp.encode(n)}function Cu(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 hp(n){return function(e,t){return Cu(t)}}function Ce(n,e,t,r,s){try{const a=JSON.stringify(n,hp(t),r);return sn(a)}catch(a){if(!a.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`\nContext: ${e}`:""}`),sn("[Unserializable]");Re("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`\nContext: ${e}`:""}`),typeof s>"u"&&(s=dp()),xa(n,"",0,[],void 0,0,s);let i;try{Dt.length===0?i=JSON.stringify(n,t,r):i=JSON.stringify(n,fp(t),r)}catch{return sn("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;nn.length!==0;){const o=nn.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return sn(i)}}function Ia(n,e,t,r){var s=Object.getOwnPropertyDescriptor(r,t);s.get!==void 0?s.configurable?(Object.defineProperty(r,t,{value:n}),nn.push([r,t,e,s])):Dt.push([e,t,n]):(r[t]=n,nn.push([r,t,e]))}function xa(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){Ia(cp,n,e,s);return}if(typeof i.depthLimit<"u"&&a>i.depthLimit){Ia(Pu,n,e,s);return}if(typeof i.edgesLimit<"u"&&t+1>i.edgesLimit){Ia(Pu,n,e,s);return}if(r.push(n),Array.isArray(n))for(o=0;o<n.length;o++)xa(n[o],o,o,r,n,a,i);else{n=Cu(n);var u=Object.keys(n);for(o=0;o<u.length;o++){var c=u[o];xa(n[c],c,o,r,n,a,i)}}r.pop()}}function fp(n){return n=typeof n<"u"?n:function(e,t){return t},function(e,t){if(Dt.length>0)for(var r=0;r<Dt.length;r++){var s=Dt[r];if(s[1]===e&&s[0]===t){t=s[2],Dt.splice(r,1);break}}return n.call(this,e,t)}}function $u(n,e){const t=go(),r=e??_o(),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 pp=n=>{const e=n?.toString()??Re("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},mp=n=>{const t=n.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return t==="localhost"||t==="127.0.0.1"||t==="::1"};async function gp(n){const e=[];for await(const t of n)e.push(t);return e}function an(n){if(n!==void 0)return n.trim().replace(/^"(.*)"$/,"$1").replace(/^\'(.*)\'$/,"$1")}const _p=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 Nu(n){return typeof n=="number"?Number(n.toFixed(4)):n}class yp{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 bp=24*1024*1024,wp=1e4,vp=100,Lu="https://api.smith.langchain.com";class or{get _fetch(){return this.fetchImplementation||rf(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 yp}),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=or.getDefaultClientConfig();if(this.tracingSampleRate=pp(e.tracingSamplingRate),this.apiUrl=an(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=an(e.apiKey??t.apiKey),this.webUrl=an(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=an(e.workspaceId??Re("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new Po({...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 Po({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:_p,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,yo()&&(this.langSmithToOTELTranslator=new wf),this.cachedLSEnvVarsForMetadata=_o()}static getDefaultClientConfig(){const e=Re("API_KEY"),t=Re("ENDPOINT")??Lu,r=Re("HIDE_INPUTS")==="true",s=Re("HIDE_OUTPUTS")==="true";return{apiUrl:t,apiKey:e,webUrl:void 0,hideInputs:r,hideOutputs:s}}getHostUrl(){return this.webUrl?this.webUrl:mp(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/${fo}`};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 N(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 N(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 N(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??bp}async _getBatchSizeLimit(){const e=await this._ensureServerInfo();return this.batchSizeLimit??e.batch_ingest_config?.size_limit??vp}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=$u(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(wp),...this.fetchOptions});return await N(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=wo(),t=gf();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=$u(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 N(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 N(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,T={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(T)){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=tf(),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 N(f,"Failed to send multipart request",!0),f});try{let c,l=!1;!a&&!this.multipartStreamingDisabled&&mo()!=="bun"?(l=!0,c=await u(o)):c=await u(i),(!this.multipartStreamingDisabled||l)&&c.status===422&&(r?.apiUrl??this.apiUrl)!==Lu&&(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 N(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:Re("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 gp(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"],T={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};T.select.includes("child_run_ids")&&Ts("Deprecated: \'child_run_ids\' in the listRuns select parameter is deprecated and will be removed in a future version.");let P=0;for await(const O of this._getCursorPaginatedList("/runs/query",T))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(([T,P])=>P!==void 0)),y=JSON.stringify(g),b=await(await this.caller.call(async()=>{const T=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 N(T,`Failed to fetch ${f}`),T})).json(),{groups:E,total:v}=b;if(E.length===0)break;for(const T of E)yield T;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 N(P,"get run stats"),P})).json()}async shareRun(e,{shareId:t}={}){const r={run_id:e,share_token:t||jt()};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 N(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 N(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 N(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 N(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 N(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 N(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 N(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 N(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 N(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 N(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 N(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 N(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 N(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 N(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 N(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 N(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 N(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 N(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 N(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 N(c,"fetch similar examples"),c})).json()).examples}async createExample(e,t,r){if(ju(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;ju(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]??jt())}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=>Co(i)?$o(i):i),a=Co(t)?$o(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((T,[P,O])=>(T[P.slice(11)]={presigned_url:O.presigned_url,mime_type:O.mime_type||void 0},T),{})),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 N(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 N(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 N(c,"update dataset splits",!0),c})}async evaluateRun(e,t,{sourceInfo:r,loadChildRuns:s,referenceExample:a}={loadChildRuns:!1}){Ts("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");let i;if(typeof e=="string")i=await this.readRun(e,{loadChildRuns: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??jt(),run_id:e,key:t,score:Nu(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 N(_,"create feedback",!0),_}),m}async updateFeedback(e,{score:t,value:r,correction:s,comment:a}){const i={};t!=null&&(i.score=Nu(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 N(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 N(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 N(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 N(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||jt(),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 N(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 N(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 N(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 N(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 N(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 N(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 N(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 N(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 N(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]=ct(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 N(u,`${t?"like":"unlike"} prompt`),u})).json()}async _getPromptUrl(e){const[t,r,s]=ct(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]=ct(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 N(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]=ct(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 N(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]=ct(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 N(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 N(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??jt()).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 N(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]=ct(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 N(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]=ct(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 N(i,"delete prompt"),i})).json()}async pullPromptCommit(e,t){const[r,s,a]=ct(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 N(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 or({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 _f()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function ju(n){return"dataset_id"in n||"dataset_name"in n}const Ep=n=>!!["TRACING_V2","TRACING"].find(t=>Re(t)==="true"),Ra=Symbol.for("lc:context_variables");function Sp(n){return n.replace(/[-:.]/g,"")}function Mu(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:Sp(s)+e,microsecondPrecisionDatestring:s}}class on{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 on(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 Te{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}),Ap(e)){Object.assign(this,{...e});return}const t=Te.getDefaultConfig(),{metadata:r,...s}=e,a=s.client??Te.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=Tp(this.replicas),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){const{dottedOrder:o,microsecondPrecisionDatestring:u}=Mu(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:jt(),run_type:"chain",project_name:ho(),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 Te.sharedClient||(Te.sharedClient=new or),Te.sharedClient}createChild(e){const t=this.child_execution_order+1,r=new Te({...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});Ra in this&&(r[Ra]=this[Ra]);const s=Symbol.for("lc:child_config"),a=e.extra?.[s]??this.extra[s];if(Ip(a)){const u={...a},c=Op(u.callbacks)?u.callbacks.copy?.():void 0;c&&(Object.assign(c,{_parentRunId:r.id}),c.handlers?.find(Du)?.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=>so(`${d}:${e}`,so.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=xp(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=go();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){Ts("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=Ep();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 Te({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 Te({...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=on.fromHeader(r.baggage);u.metadata=c.metadata,u.tags=c.tags,u.project_name=c.project_name,u.replicas=c.replicas}return new Te(u)}toHeaders(e){const t={"langsmith-trace":this.dotted_order,baggage:new on(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(Te,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function Ap(n){return n!=null&&typeof n.createChild=="function"&&typeof n.postRun=="function"}function Du(n){return typeof n=="object"&&n!=null&&typeof n.name=="string"&&n.name==="langchain_tracer"}function Uu(n){return Array.isArray(n)&&n.some(e=>Du(e))}function Op(n){return typeof n=="object"&&n!=null&&Array.isArray(n.handlers)}function Ip(n){return n!=null&&typeof n.callbacks=="object"&&(Uu(n.callbacks?.handlers)||Uu(n.callbacks))}function xp(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 Rp(){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){kp(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(up(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 Tp(n){return n?n.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):Rp()}function kp(n){if(Object.keys(n).length>0&&Re("ENDPOINT"))throw new op}const Pp=n=>{if(n)return n.events=n.events??[],n.child_runs=n.child_runs??[],n};function Ta(n,e){if(n)return new Te({...n,start_time:n._serialized_start_time??n.start_time,parent_run:Ta(e),child_runs:n.child_runs.map(t=>Ta(t)).filter(t=>t!==void 0),extra:{...n.extra,runtime:ch()},tracingEnabled:!1})}function ka(n,e){return n&&!Array.isArray(n)&&typeof n=="object"?n:{[e]:n}}function ur(n){return typeof n._addRunToRunMap=="function"}class cr extends nr{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?Pp(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}=Mu(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=Ta(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=ka(e,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),a?.inputs!==void 0&&(i.inputs=ka(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=ka(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 Fu(n){return typeof n=="string"?n.trim():n==null?n:Fe(n,n.toString())}function lt(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}=to;class Bu extends cr{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(to.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}] [${lt(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}] [${lt(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}] [${lt(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}] [${lt(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: "${Fu(e.inputs.input)}"`)}onToolEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Ee(ke.cyan,"[tool/end]")} [${t}] [${lt(e)}] Exiting Tool run with output: "${Fu(e.outputs?.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${Ee(ke.red,"[tool/error]")} [${t}] [${lt(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}] [${lt(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}] [${lt(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 Cp(n){return!!(n&&typeof n=="object"&&"type"in n&&n.type==="tool_call")}class $p extends Error{constructor(e,t){super(e),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=t}}function Np(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 zu(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 Lp(n,e){return typeof n=="string"?n===""?e:typeof e=="string"?n+e:Array.isArray(e)&&e.some(t=>zu(t))?[{type:"text",source_type:"text",text:n},...e]:[{type:"text",text:n},...e]:Array.isArray(e)?Pa(n,e)??[...n,...e]:e===""?n:Array.isArray(n)&&n.some(t=>zu(t))?[...n,{type:"file",source_type:"text",text:e}]:[...n,{type:"text",text:e}]}function jp(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 Mp extends St{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=jp(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}}function un(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]=un(t[r],s);else if(Array.isArray(t[r]))t[r]=Pa(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 Pa(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]=un(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 Dp extends Mp{}class cn extends Dp{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=Np(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:Lp(this.content,e.content),additional_kwargs:un(this.additional_kwargs,e.additional_kwargs),response_metadata:un(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=Pa(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 cn(t)}}function Up(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 Fp=class{getStore(){}run(e,t){return t()}};const Ca=Symbol.for("ls:tracing_async_local_storage"),Bp=new Fp;let zp=class{getInstance(){return globalThis[Ca]??Bp}initializeGlobalInstance(e){globalThis[Ca]===void 0&&(globalThis[Ca]=e)}};const qp=new zp;function Hp(n=!1){const e=qp.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 $a(n){return typeof n=="function"&&"langsmith:traceable"in n}let Na;const Gp=()=>{if(Na===void 0){const n=xe("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};Na=new or(n)}return Na};class lr extends cr{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??ho(),this.replicas=a,this.exampleId=t,this.client=s??Gp();const i=lr.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 Te({...t,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return Hp(!0)}catch{return}}}const qu=Symbol.for("ls:tracing_async_local_storage"),ln=Symbol.for("lc:context_variables"),Vp=n=>{globalThis[qu]=n},dr=()=>globalThis[qu];let hr;function Zp(){const n="default"in nt?nt.default:nt;return new n({autoStart:!0,concurrency:1})}function Wp(){return typeof hr>"u"&&(hr=Zp()),hr}async function ce(n,e){if(e===!0){const t=dr();t!==void 0?await t.run(void 0,async()=>n()):await n()}else hr=Wp(),hr.add(async()=>{const t=dr();t!==void 0?await t.run(void 0,async()=>n()):await n()})}const Jp=n=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(t=>xe(t)==="true");function Hu(n){const e=dr();return e===void 0?void 0:e.getStore()?.[ln]?.[n]}const Kp=Symbol("lc:configure_hooks"),Xp=()=>Hu(Kp)||[];function Qp(n){return n?Array.isArray(n)||"name"in n?{callbacks:n}:n:{}}class Yp{setHandler(e){return this.setHandlers([e])}}class dn{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 em extends dn{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 Gu extends dn{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 tm extends dn{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 rm extends dn{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 Yp{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:rt();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return ur(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 Gu(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:rt();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return ur(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=Up(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 Gu(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,r=rt(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreChain)return ur(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 tm(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,r=rt(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreAgent)return ur(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 rm(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,r=rt(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreRetriever)return ur(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 em(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 nr{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:rt()}),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(hn)??[],!0)):u=e,u=u.copy(Array.isArray(t)?t.map(hn):t?.handlers,!1));const c=xe("LANGCHAIN_VERBOSE")==="true"||o?.verbose,l=lr.getTraceableRunTree()?.tracingEnabled||Jp(),d=l||(xe("LANGCHAIN_TRACING")??!1);if(c||d){if(u||(u=new Be),c&&!u.handlers.some(h=>h.name===Bu.prototype.name)){const h=new Bu;u.addHandler(h,!0)}if(d&&!u.handlers.some(h=>h.name==="langchain_tracer")&&l){const h=new lr;u.addHandler(h,!0)}if(l){const h=lr.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 Xp()){const g=m&&xe(m)==="true"&&p;let y;const _=h!==void 0?Hu(h):void 0;_&&dh(_)?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 hn(n){return"name"in n?n:nr.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 Vu;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(Vu||(Vu={}));const C=Q.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),dt=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 st 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 st))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()}}st.create=n=>new st(n);const La=(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 nm=La;function sm(){return nm}const am=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 R(n,e){const t=sm(),r=am({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===La?void 0:La].filter(s=>!!s)});n.common.issues.push(r)}class $e{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 $e.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"}),fr=n=>({status:"dirty",value:n}),ze=n=>({status:"valid",value:n}),Zu=n=>n.status==="aborted",Wu=n=>n.status==="dirty",Ut=n=>n.status==="valid",fn=n=>typeof Promise<"u"&&n instanceof Promise;var $;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})($||($={}));class ht{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 Ju=(n,e)=>{if(Ut(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 st(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 dt(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:dt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new $e,ctx:{common:e.parent.common,data:e.data,parsedType:dt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(fn(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:dt(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Ju(r,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:dt(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return Ut(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=>Ut(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:dt(e)},s=this._parse({data:e,path:r.path,parent:r}),a=await(fn(s)?s:Promise.resolve(s));return Ju(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 zt({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 mt.create(this,this._def)}nullable(){return qt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Qe.create(this)}promise(){return _n.create(this,this._def)}or(e){return mn.create([this,e],this._def)}and(e){return gn.create(this,e,this._def)}transform(e){return new zt({...V(this._def),schema:this,typeName:A.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Ua({...V(this._def),innerType:this,defaultValue:t,typeName:A.ZodDefault})}brand(){return new Rm({typeName:A.ZodBranded,type:this,...V(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Fa({...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 Ba.create(this,e)}readonly(){return za.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const im=/^c[^\\s-]{8,}$/i,om=/^[0-9a-z]+$/,um=/^[0-9A-HJKMNP-TV-Z]{26}$/i,cm=/^[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,lm=/^[a-z0-9_-]{21}$/i,dm=/^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/,hm=/^[-+]?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)?)??$/,fm=/^(?!\\.)(?!.*\\.\\.)([A-Z0-9_\'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i,pm="^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$";let ja;const mm=/^(?:(?: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])$/,gm=/^(?:(?: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])$/,_m=/^(([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]))$/,ym=/^(([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])$/,bm=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,wm=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ku="((\\\\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])))",vm=new RegExp(`^${Ku}$`);function Xu(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 Em(n){return new RegExp(`^${Xu(n)}$`)}function Sm(n){let e=`${Ku}T${Xu(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 Am(n,e){return!!((e==="v4"||!e)&&mm.test(n)||(e==="v6"||!e)&&_m.test(n))}function Om(n,e){if(!dm.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 Im(n,e){return!!((e==="v4"||!e)&&gm.test(n)||(e==="v6"||!e)&&ym.test(n))}class ft extends X{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==C.string){const a=this._getOrReturnCtx(e);return R(a,{code:S.invalid_type,expected:C.string,received:a.parsedType}),q}const r=new $e;let s;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),R(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),R(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?R(s,{code:S.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&R(s,{code:S.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),r.dirty())}else if(a.kind==="email")fm.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"email",code:S.invalid_string,message:a.message}),r.dirty());else if(a.kind==="emoji")ja||(ja=new RegExp(pm,"u")),ja.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"emoji",code:S.invalid_string,message:a.message}),r.dirty());else if(a.kind==="uuid")cm.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"uuid",code:S.invalid_string,message:a.message}),r.dirty());else if(a.kind==="nanoid")lm.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"nanoid",code:S.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid")im.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"cuid",code:S.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid2")om.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"cuid2",code:S.invalid_string,message:a.message}),r.dirty());else if(a.kind==="ulid")um.test(e.data)||(s=this._getOrReturnCtx(e,s),R(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),R(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),R(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),R(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),R(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),R(s,{code:S.invalid_string,validation:{endsWith:a.value},message:a.message}),r.dirty()):a.kind==="datetime"?Sm(a).test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{code:S.invalid_string,validation:"datetime",message:a.message}),r.dirty()):a.kind==="date"?vm.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{code:S.invalid_string,validation:"date",message:a.message}),r.dirty()):a.kind==="time"?Em(a).test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{code:S.invalid_string,validation:"time",message:a.message}),r.dirty()):a.kind==="duration"?hm.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"duration",code:S.invalid_string,message:a.message}),r.dirty()):a.kind==="ip"?Am(e.data,a.version)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"ip",code:S.invalid_string,message:a.message}),r.dirty()):a.kind==="jwt"?Om(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"jwt",code:S.invalid_string,message:a.message}),r.dirty()):a.kind==="cidr"?Im(e.data,a.version)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"cidr",code:S.invalid_string,message:a.message}),r.dirty()):a.kind==="base64"?bm.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"base64",code:S.invalid_string,message:a.message}),r.dirty()):a.kind==="base64url"?wm.test(e.data)||(s=this._getOrReturnCtx(e,s),R(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,...$.errToObj(r)})}_addCheck(e){return new ft({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...$.errToObj(e)})}url(e){return this._addCheck({kind:"url",...$.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...$.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...$.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...$.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...$.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...$.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...$.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...$.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...$.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...$.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...$.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...$.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,...$.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,...$.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...$.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...$.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...$.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...$.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...$.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...$.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...$.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...$.errToObj(t)})}nonempty(e){return this.min(1,$.errToObj(e))}trim(){return new ft({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ft({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ft({...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}}ft.create=n=>new ft({checks:[],typeName:A.ZodString,coerce:n?.coerce??!1,...V(n)});function xm(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 pr 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 R(a,{code:S.invalid_type,expected:C.number,received:a.parsedType}),q}let r;const s=new $e;for(const a of this._def.checks)a.kind==="int"?Q.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),R(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),R(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),R(r,{code:S.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?xm(e.data,a.value)!==0&&(r=this._getOrReturnCtx(e,r),R(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),R(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,$.toString(t))}gt(e,t){return this.setLimit("min",e,!1,$.toString(t))}lte(e,t){return this.setLimit("max",e,!0,$.toString(t))}lt(e,t){return this.setLimit("max",e,!1,$.toString(t))}setLimit(e,t,r,s){return new pr({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:$.toString(s)}]})}_addCheck(e){return new pr({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:$.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:$.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:$.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:$.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:$.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:$.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:$.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:$.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:$.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)}}pr.create=n=>new pr({checks:[],typeName:A.ZodNumber,coerce:n?.coerce||!1,...V(n)});class mr 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 $e;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),R(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),R(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),R(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 R(t,{code:S.invalid_type,expected:C.bigint,received:t.parsedType}),q}gte(e,t){return this.setLimit("min",e,!0,$.toString(t))}gt(e,t){return this.setLimit("min",e,!1,$.toString(t))}lte(e,t){return this.setLimit("max",e,!0,$.toString(t))}lt(e,t){return this.setLimit("max",e,!1,$.toString(t))}setLimit(e,t,r,s){return new mr({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:$.toString(s)}]})}_addCheck(e){return new mr({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:$.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:$.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:$.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:$.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:$.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}}mr.create=n=>new mr({checks:[],typeName:A.ZodBigInt,coerce:n?.coerce??!1,...V(n)});class Qu extends X{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==C.boolean){const r=this._getOrReturnCtx(e);return R(r,{code:S.invalid_type,expected:C.boolean,received:r.parsedType}),q}return ze(e.data)}}Qu.create=n=>new Qu({typeName:A.ZodBoolean,coerce:n?.coerce||!1,...V(n)});class pn 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 R(a,{code:S.invalid_type,expected:C.date,received:a.parsedType}),q}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return R(a,{code:S.invalid_date}),q}const r=new $e;let s;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),R(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),R(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 pn({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:$.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:$.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}}pn.create=n=>new pn({checks:[],coerce:n?.coerce||!1,typeName:A.ZodDate,...V(n)});class Yu extends X{_parse(e){if(this._getType(e)!==C.symbol){const r=this._getOrReturnCtx(e);return R(r,{code:S.invalid_type,expected:C.symbol,received:r.parsedType}),q}return ze(e.data)}}Yu.create=n=>new Yu({typeName:A.ZodSymbol,...V(n)});class ec extends X{_parse(e){if(this._getType(e)!==C.undefined){const r=this._getOrReturnCtx(e);return R(r,{code:S.invalid_type,expected:C.undefined,received:r.parsedType}),q}return ze(e.data)}}ec.create=n=>new ec({typeName:A.ZodUndefined,...V(n)});class tc extends X{_parse(e){if(this._getType(e)!==C.null){const r=this._getOrReturnCtx(e);return R(r,{code:S.invalid_type,expected:C.null,received:r.parsedType}),q}return ze(e.data)}}tc.create=n=>new tc({typeName:A.ZodNull,...V(n)});class Ma extends X{constructor(){super(...arguments),this._any=!0}_parse(e){return ze(e.data)}}Ma.create=n=>new Ma({typeName:A.ZodAny,...V(n)});class rc extends X{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ze(e.data)}}rc.create=n=>new rc({typeName:A.ZodUnknown,...V(n)});class pt extends X{_parse(e){const t=this._getOrReturnCtx(e);return R(t,{code:S.invalid_type,expected:C.never,received:t.parsedType}),q}}pt.create=n=>new pt({typeName:A.ZodNever,...V(n)});class nc extends X{_parse(e){if(this._getType(e)!==C.undefined){const r=this._getOrReturnCtx(e);return R(r,{code:S.invalid_type,expected:C.void,received:r.parsedType}),q}return ze(e.data)}}nc.create=n=>new nc({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 R(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)&&(R(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&&(R(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&&(R(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 ht(t,i,t.path,o)))).then(i=>$e.mergeArray(r,i));const a=[...t.data].map((i,o)=>s.type._parseSync(new ht(t,i,t.path,o)));return $e.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new Qe({...this._def,minLength:{value:e,message:$.toString(t)}})}max(e,t){return new Qe({...this._def,maxLength:{value:e,message:$.toString(t)}})}length(e,t){return new Qe({...this._def,exactLength:{value:e,message:$.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 Ft(n){if(n instanceof ae){const e={};for(const t in n.shape){const r=n.shape[t];e[t]=mt.create(Ft(r))}return new ae({...n._def,shape:()=>e})}else return n instanceof Qe?new Qe({...n._def,type:Ft(n.element)}):n instanceof mt?mt.create(Ft(n.unwrap())):n instanceof qt?qt.create(Ft(n.unwrap())):n instanceof At?At.create(n.items.map(e=>Ft(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 R(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 pt&&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 ht(s,d,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof pt){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&&(R(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 ht(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=>$e.mergeObjectSync(r,c)):$e.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return $.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:$.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 Ft(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 mt;)a=a._def.innerType;t[r]=a}return new ae({...this._def,shape:()=>t})}keyof(){return oc(Q.objectKeys(this.shape))}}ae.create=(n,e)=>new ae({shape:()=>n,unknownKeys:"strip",catchall:pt.create(),typeName:A.ZodObject,...V(e)}),ae.strictCreate=(n,e)=>new ae({shape:()=>n,unknownKeys:"strict",catchall:pt.create(),typeName:A.ZodObject,...V(e)}),ae.lazycreate=(n,e)=>new ae({shape:n,unknownKeys:"strip",catchall:pt.create(),typeName:A.ZodObject,...V(e)});class mn 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 st(o.ctx.common.issues));return R(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 st(u));return R(t,{code:S.invalid_union,unionErrors:o}),q}}get options(){return this._def.options}}mn.create=(n,e)=>new mn({options:n,typeName:A.ZodUnion,...V(e)});function Da(n,e){const t=dt(n),r=dt(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=Da(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=Da(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 gn extends X{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(a,i)=>{if(Zu(a)||Zu(i))return q;const o=Da(a.value,i.value);return o.valid?((Wu(a)||Wu(i))&&t.dirty(),{status:t.value,value:o.data}):(R(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}))}}gn.create=(n,e,t)=>new gn({left:n,right:e,typeName:A.ZodIntersection,...V(t)});class At extends X{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==C.array)return R(r,{code:S.invalid_type,expected:C.array,received:r.parsedType}),q;if(r.data.length<this._def.items.length)return R(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&&(R(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 ht(r,i,r.path,o)):null}).filter(i=>!!i);return r.common.async?Promise.all(a).then(i=>$e.mergeArray(t,i)):$e.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new At({...this._def,rest:e})}}At.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new At({items:n,typeName:A.ZodTuple,rest:null,...V(e)})};class sc 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 R(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 ht(r,o,r.path,[c,"key"])),value:a._parse(new ht(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}}}}sc.create=(n,e,t)=>new sc({valueType:e,keyType:n,typeName:A.ZodMap,...V(t)});class gr extends X{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==C.set)return R(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&&(R(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&&(R(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 ht(r,u,r.path,c)));return r.common.async?Promise.all(o).then(u=>i(u)):i(o)}min(e,t){return new gr({...this._def,minSize:{value:e,message:$.toString(t)}})}max(e,t){return new gr({...this._def,maxSize:{value:e,message:$.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}gr.create=(n,e)=>new gr({valueType:n,minSize:null,maxSize:null,typeName:A.ZodSet,...V(e)});class ac 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})}}ac.create=(n,e)=>new ac({getter:n,typeName:A.ZodLazy,...V(e)});class ic extends X{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return R(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}}ic.create=(n,e)=>new ic({value:n,typeName:A.ZodLiteral,...V(e)});function oc(n,e){return new Bt({values:n,typeName:A.ZodEnum,...V(e)})}class Bt extends X{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),r=this._def.values;return R(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 R(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 Bt.create(e,{...this._def,...t})}exclude(e,t=this._def){return Bt.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}}Bt.create=oc;class uc 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 R(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 R(r,{received:r.data,code:S.invalid_enum_value,options:s}),q}return ze(e.data)}get enum(){return this._def.values}}uc.create=(n,e)=>new uc({values:n,typeName:A.ZodNativeEnum,...V(e)});class _n 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 R(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})))}}_n.create=(n,e)=>new _n({type:n,typeName:A.ZodPromise,...V(e)});class zt 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=>{R(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"?fr(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"?fr(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(!Ut(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=>Ut(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:t.value,value:o})):q);Q.assertNever(s)}}zt.create=(n,e,t)=>new zt({schema:n,typeName:A.ZodEffects,effect:e,...V(t)}),zt.createWithPreprocess=(n,e,t)=>new zt({schema:e,effect:{type:"preprocess",transform:n},typeName:A.ZodEffects,...V(t)});class mt extends X{_parse(e){return this._getType(e)===C.undefined?ze(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}mt.create=(n,e)=>new mt({innerType:n,typeName:A.ZodOptional,...V(e)});class qt extends X{_parse(e){return this._getType(e)===C.null?ze(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}qt.create=(n,e)=>new qt({innerType:n,typeName:A.ZodNullable,...V(e)});class Ua 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}}Ua.create=(n,e)=>new Ua({innerType:n,typeName:A.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...V(e)});class Fa 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 fn(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new st(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new st(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Fa.create=(n,e)=>new Fa({innerType:n,typeName:A.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...V(e)});class cc extends X{_parse(e){if(this._getType(e)!==C.nan){const r=this._getOrReturnCtx(e);return R(r,{code:S.invalid_type,expected:C.nan,received:r.parsedType}),q}return{status:"valid",value:e.data}}}cc.create=n=>new cc({typeName:A.ZodNaN,...V(n)});class Rm 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 Ba 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(),fr(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 Ba({in:e,out:t,typeName:A.ZodPipeline})}}class za extends X{_parse(e){const t=this._def.innerType._parse(e),r=s=>(Ut(s)&&(s.value=Object.freeze(s.value)),s);return fn(t)?t.then(s=>r(s)):r(t)}unwrap(){return this._def.innerType}}za.create=(n,e)=>new za({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 Tm=ft.create,lc=Ma.create;pt.create,Qe.create;const km=ae.create;mn.create,gn.create,At.create,Bt.create,_n.create,mt.create,qt.create;const Pm=Object.prototype.hasOwnProperty;function Cm(n,e){return Pm.call(n,e)}function $m(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)Cm(n,t)&&e.push(t);return e}function Ht(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}function qa(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 Nm(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}function Ha(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(let t=0,r=n.length;t<r;t++)if(Ha(n[t]))return!0}else if(typeof n=="object"){const t=$m(n),r=t.length;for(var e=0;e<r;e++)if(Ha(n[t[e]]))return!0}}return!1}function dc(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 Lm extends Error{constructor(e,t,r,s,a){super(dc(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=dc(e,{name:t,index:r,operation:s,tree:a})}}const ie=Lm,Gt={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=Ga(t,this.path);r&&(r=Ht(r));const s=_r(t,{op:"remove",path:this.from}).removed;return _r(t,{op:"add",path:this.path,value:s}),{newDocument:t,removed:r}},copy:function(n,e,t){const r=Ga(t,this.from);return _r(t,{op:"add",path:this.path,value:Ht(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:bn(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}};var jm={add:function(n,e,t){return qa(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:Gt.move,copy:Gt.copy,test:Gt.test,_get:Gt._get};function Ga(n,e){if(e=="")return n;var t={op:"_get",path:e};return _r(n,t),t.value}function _r(n,e,t=!1,r=!0,s=!0,a=0){if(t&&(typeof t=="function"?t(e,0,n,e.path):Va(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=Ga(n,e.from),e.op==="move"&&(i.removed=n),i;if(e.op==="test"){if(i.test=bn(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=Ht(n));const o=(e.path||"").split("/");let u=n,c=1,l=o.length,d,h,f;for(typeof t=="function"?f=t:f=Va;;){if(h=o[c],h&&h.indexOf("~")!=-1&&(h=Nm(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&&!qa(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);qa(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=jm[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=Gt[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 yn(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=Ht(n));const a=new Array(e.length);for(let i=0,o=e.length;i<o;i++)a[i]=_r(n,e[i],t,!0,s,i),n=a[i].newDocument;return a.newDocument=n,a}function Va(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(Gt[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")&&Ha(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=Mm([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 Mm(n,e,t){try{if(!Array.isArray(n))throw new ie("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)yn(Ht(e),Ht(n),t||!0);else{t=t||Va;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 bn(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(!bn(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],!bn(n[i],e[i]))return!1;return!0}return n!==n&&e!==e}class Dm{getStore(){}run(e,t){return t()}enterWith(e){}}const Um=new Dm,hc=Symbol.for("lc:child_config");class Fm{getInstance(){return dr()??Um}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[hc]}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 Te({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[hc]:e}),i!==void 0&&i[ln]!==void 0&&(c===void 0&&(c={}),c[ln]=i[ln]),a.run(c,t)}initializeGlobalInstance(e){dr()===void 0&&Vp(e)}}const gt=new Fm,Za=25;async function Ge(n){return Be._configureSync(n?.callbacks,void 0,n?.tags,void 0,n?.metadata)}function fc(...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(hn(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(hn(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 Bm=new Set(["string","number","boolean"]);function Y(n){const e=gt.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))Bm.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 we(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 Vt(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 _t(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 Ne 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 Ne({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 Ne({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 pc(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 mc(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]=mc(t[r],s):t[r]=s;return t}else throw new Error(`Cannot concat ${typeof n} and ${typeof e}`)}class Zt{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)=>{gt.runWithConfig(Vt(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?gt.runWithConfig(Vt(this.config),this.signal?async()=>_t(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 zm(n,e,t,r,...s){const a=new Zt({generator:e,startSetup:t,signal:r}),i=await a.setup;return{output:n(a,i,...s),setup:i}}class yt{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=yn({},t);return new yr({ops:t,state:r[r.length-1].newDocument})}}class yr extends yt{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=yn(this.state,e.ops);return new yr({ops:t,state:r[r.length-1].newDocument})}static fromRunLogPatch(e){const t=yn({},e.ops);return new yr({ops:e.ops,state:t[t.length-1].newDocument})}}const qm=n=>n.name==="log_stream_tracer";async function gc(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 _c(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 Hm(n){return n!==void 0&&n.message!==void 0}class yc extends cr{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=Ne.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 yt({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 yt({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 gc(e,this._schemaFormat)),await this.writer.write(new yt({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 gc(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await _c(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 yt({ops:r});await this.writer.write(s)}finally{if(e.id===this.rootId){const t=new yt({ops:[{op:"replace",path:"/final_output",value:await _c(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?Hm(r?.chunk)?i=r?.chunk:i=new cn({id:`run-${e.id}`,content:t}):i=t;const o=new yt({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 wn{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 wn({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}}function vn({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 Gm=n=>n.name==="event_stream_tracer";class Vm extends cr{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=Ne.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 wn({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=vn(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 cn({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 wn({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=vn(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=vn(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=vn(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 Zm=[400,401,402,403,404,405,406,407,409],Wm=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&&Zm.includes(+e))throw n;if(n?.error?.code==="insufficient_quota"){const t=new Error(n?.message);throw t.name="InsufficientQuotaError",t}};class bc{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??Wm;const t="default"in nt?nt.default:nt;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>Zr(()=>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 wc extends cr{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 Wa(n){return n?n.lc_runnable:!1}class Jm{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 Ja(n){return n.replace(/[^a-zA-Z-_0-9]/g,"_")}const Km=["*","_","`"];function Xm(n){let e="";for(const[t,r]of Object.entries(n))e+=` classDef ${t} ${r};\n`;return e}function Qm(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=Km.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,T])=>`${v} = ${T}`).join(`\n`)}</em></small>`);const E=(p[m]??p[f]).replace("{0}",Ja(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 T=b;const P=T.split(" ");P.length>u&&(T=Array.from({length:Math.ceil(P.length/u)},(O,J)=>P.slice(J*u,(J+1)*u).join(" ")).join(" <br> ")),v=E?` -. ${T} .-> `:` -- ${T} --> `}else v=E?" -.-> ":" --> ";c+=` ${Ja(y)}${v}${Ja(_)};\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+=Xm(a??{})),c}async function Ym(n,e){return eg(n,{...e,imageType:"png"})}async function eg(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 En(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 Sn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const tg={};function Ka(n){return tg}function rg(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 ng(n,e){return typeof e=="bigint"?e.toString():e}const sg=Error.captureStackTrace?Error.captureStackTrace:(...n)=>{};function An(n,e,t){const r=new n._zod.constr(e??n._zod.def);return(!e||t?.parent)&&(r._zod.parent=n),r}function ag(n){return{}}function Xa(n,e=0){for(let t=e;t<n.issues.length;t++)if(n.issues[t]?.continue!==!0)return!0;return!1}function On(n){return typeof n=="string"?n:n?.message}function Qa(n,e,t){const r={...n,path:n.path??[]};if(!n.message){const s=On(n.inst?._zod.def?.error?.(n))??On(e?.error?.(n))??On(t.customError?.(n))??On(t.localeError?.(n))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}const vc=(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,ng,2)},enumerable:!0}),Object.defineProperty(n,"toString",{value:()=>n.message,enumerable:!1})},ig=En("$ZodError",vc),Ya=En("$ZodError",vc,{Parent:Error}),og=(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 Sn;if(i.issues.length){const o=new(s?.Err??n)(i.issues.map(u=>Qa(u,a,Ka())));throw sg(o,s?.callee),o}return i.value})(Ya),ug=(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 Sn;return a.issues.length?{success:!1,error:new(n??ig)(a.issues.map(i=>Qa(i,s,Ka())))}:{success:!0,data:a.value}})(Ya),cg=(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=>Qa(i,s,Ka())))}:{success:!0,data:a.value}})(Ya),lg={major:4,minor:0,patch:0},dg=En("$ZodType",(n,e)=>{var t;n??(n={}),n._zod.def=e,n._zod.bag=n._zod.bag||{},n._zod.version=lg;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=Xa(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 Sn;if(c||h instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await h,a.issues.length!==d&&(u||(u=Xa(a,d)))});else{if(a.issues.length===d)continue;u||(u=Xa(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 Sn;return o.then(u=>s(u,r,i))}return s(o,r,i)}}n["~standard"]={validate:s=>{try{const a=ug(n,s);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return cg(n,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),hg=En("$ZodNever",(n,e)=>{dg.init(n,e),n._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:n}),t)});class Ec{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 fg(){return new Ec}const bt=fg();function pg(n,e){return new n({type:"never",...ag()})}class Sc{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??bt,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=rg(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 Ac(n,e){if(n instanceof Ec){const r=new Sc(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 Sc(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 mg=Symbol("Let zodToJsonSchema decide on which parser to use"),gg={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"},_g=n=>({...gg,...n}),yg=n=>{const e=_g(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 Oc(n,e,t,r){r?.errorMessages&&t&&(n.errorMessage={...n.errorMessage,[e]:t})}function re(n,e,t,r,s){n[e]=t,Oc(n,e,r,s)}const Ic=(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"?Ic(e,n.currentPath):e.join("/")}}function bg(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 wg(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 vg(){return{type:"boolean"}}function xc(n,e){return ee(n.type._def,e)}const Eg=(n,e)=>ee(n.innerType._def,e);function Rc(n,e,t){const r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,a)=>Rc(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 Sg(n,e)}}const Sg=(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 Ag(n,e){return{...ee(n.innerType._def,e),default:n.defaultValue()}}function Og(n,e){return e.effectStrategy==="input"?ee(n.schema._def,e):Le(e)}function Ig(n){return{type:"string",enum:Array.from(n.values)}}const xg=n=>"type"in n&&n.type==="string"?!1:"allOf"in n;function Rg(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(xg(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 Tg(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 ei;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:()=>(ei===void 0&&(ei=RegExp("^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$","u")),ei),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 Tc(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(`^${ti(r.value,e)}`),r.message,e);break;case"endsWith":Se(t,RegExp(`${ti(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(ti(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 ti(n,e){return e.patternStrategy==="escape"?Pg(n):n}const kg=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Pg(n){let e="";for(let t=0;t<n.length;t++)kg.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:kc(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):re(n,"pattern",kc(e,r),t,r)}function kc(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 Pc(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}=Tc(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}=xc(n.keyType._def,e);return{...t,propertyNames:s}}}return t}function Cg(n,e){if(e.mapStrategy==="record")return Pc(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 $g(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 Ng(n){return n.target==="openAi"?void 0:{not:Le({...n,currentPath:[...n.currentPath,"not"]})}}function Lg(n){return n.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const In={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function jg(n,e){if(e.target==="openApi3")return Cc(n,e);const t=n.options instanceof Map?Array.from(n.options.values()):n.options;if(t.every(r=>r._def.typeName in In&&(!r._def.checks||!r._def.checks.length))){const r=t.reduce((s,a)=>{const i=In[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 Cc(n,e)}const Cc=(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 Mg(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:In[n.innerType._def.typeName],nullable:!0}:{type:[In[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 Dg(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",Oc(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 Ug(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=Bg(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=Fg(n,e);return i!==void 0&&(r.additionalProperties=i),r}function Fg(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 Bg(n){try{return n.isOptional()}catch{return!0}}const zg=(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)},qg=(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 Hg(n,e){return ee(n.type._def,e)}function Gg(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 Vg(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 Zg(n){return{not:Le(n)}}function Wg(n){return Le(n)}const Jg=(n,e)=>ee(n.innerType._def,e),Kg=(n,e,t)=>{switch(e){case A.ZodString:return Tc(n,t);case A.ZodNumber:return Dg(n,t);case A.ZodObject:return Ug(n,t);case A.ZodBigInt:return wg(n,t);case A.ZodBoolean:return vg();case A.ZodDate:return Rc(n,t);case A.ZodUndefined:return Zg(t);case A.ZodNull:return Lg(t);case A.ZodArray:return bg(n,t);case A.ZodUnion:case A.ZodDiscriminatedUnion:return jg(n,t);case A.ZodIntersection:return Rg(n,t);case A.ZodTuple:return Vg(n,t);case A.ZodRecord:return Pc(n,t);case A.ZodLiteral:return Tg(n,t);case A.ZodEnum:return Ig(n);case A.ZodNativeEnum:return $g(n);case A.ZodNullable:return Mg(n,t);case A.ZodOptional:return zg(n,t);case A.ZodMap:return Cg(n,t);case A.ZodSet:return Gg(n,t);case A.ZodLazy:return()=>n.getter()._def;case A.ZodPromise:return Hg(n,t);case A.ZodNaN:case A.ZodNever:return Ng(t);case A.ZodEffects:return Og(n,t);case A.ZodAny:return Le(t);case A.ZodUnknown:return Wg(t);case A.ZodDefault:return Ag(n,t);case A.ZodBranded:return xc(n,t);case A.ZodReadonly:return Jg(n,t);case A.ZodCatch:return Eg(n,t);case A.ZodPipeline:return qg(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!==mg)return o}if(r&&!t){const o=Xg(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=Kg(n,n.typeName,e),i=typeof a=="function"?ee(a(),e):a;if(i&&Qg(n,e,i),e.postProcess){const o=e.postProcess(i,n,e);return s.jsonSchema=i,o}return s.jsonSchema=i,i}const Xg=(n,e)=>{switch(e.$refStrategy){case"root":return{$ref:n.path.join("/")};case"relative":return{$ref:Ic(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}},Qg=(n,e,t)=>(n.description&&(t.description=n.description,e.markdownDescription&&(t.markdownDescription=n.description)),t),Yg=(n,e)=>{const t=yg(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 at(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 wt(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 e_(n){return!n||typeof n!="object"||Array.isArray(n)?!1:!!(at(n)||wt(n))}async function t_(n,e){if(at(n))return og(n,e);if(wt(n))return n.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function r_(n){if(at(n))return bt.get(n)?.description;if(wt(n)||"description"in n&&typeof n.description=="string")return n.description}function n_(n){return e_(n)?wt(n)?n._def.typeName==="ZodString":at(n)?n._zod.def.type==="string":!1:!1}function br(n){return at(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 $c(n){return at(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 ri(n,e=!1){if(wt(n))return n.strict();if(br(n)){const t=n._zod.def.shape;if(e)for(const[a,i]of Object.entries(n._zod.def.shape)){if(br(i)){const u=ri(i,e);t[a]=u}else if($c(i)){let u=i._zod.def.element;br(u)&&(u=ri(u,e)),t[a]=An(i,{...i._zod.def,element:u})}else t[a]=i;const o=bt.get(i);o&&bt.add(t[a],o)}const r=An(n,{...n._zod.def,shape:t,catchall:pg(hg)}),s=bt.get(n);return s&&bt.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function s_(n){return wt(n)&&"typeName"in n._def&&n._def.typeName==="ZodEffects"}function a_(n){return at(n)&&n._zod.def.type==="pipe"}function wr(n,e=!1){if(wt(n))return s_(n)?wr(n._def.schema,e):n;if(at(n)){let t=n;if(a_(n)&&(t=wr(n._zod.def.in,e)),e){if(br(t)){const s=t._zod.def.shape;for(const[a,i]of Object.entries(t._zod.def.shape))s[a]=wr(i,e);t=An(t,{...t._zod.def,shape:s})}else if($c(t)){const s=wr(t._zod.def.element,e);t=An(t,{...t._zod.def,element:s})}}const r=bt.get(n);return r&&bt.add(t,r),t}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function i_(n){if(at(n)){const e=wr(n,!0);if(br(e)){const t=ri(e,!0);return Ac(t)}else return Ac(n)}return wt(n)?Yg(n):n}function o_(n,e){if(n!==void 0&&!zr(n))return n;if(Wa(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 u_(n){return Wa(n.data)?{type:"runnable",data:{id:n.data.lc_id,name:n.data.getName()}}:{type:"schema",data:{...i_(n.data.schema),title:n.data.name}}}class xn{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]=zr(t.id)?r:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...u_(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??rt(),a={id:s,data:e,name:o_(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 Nc(this)}lastNode(){return Lc(this)}extend(e,t=""){let r=t;Object.values(e.nodes).map(c=>c.id).every(zr)&&(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&&Nc(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&Lc(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 zr(s)&&t.get(a)===1?a:s};return new xn({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 Qm(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 Ym(t,{backgroundColor:e?.backgroundColor})}}function Nc(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 Lc(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 c_(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 Ne.fromReadableStream(t)}function jc(n){return typeof n=="object"&&n!==null&&typeof n[Symbol.iterator]=="function"&&typeof n.next=="function"}const l_=n=>n!=null&&typeof n=="object"&&"next"in n&&typeof n.next=="function";function ni(n){return typeof n=="object"&&n!==null&&typeof n[Symbol.asyncIterator]=="function"}function*Mc(n,e){for(;;){const{value:t,done:r}=gt.runWithConfig(Vt(n),e.next.bind(e),!0);if(r)break;yield t}}async function*si(n,e){const t=e[Symbol.asyncIterator]();for(;;){const{value:r,done:s}=await gt.runWithConfig(Vt(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 St{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 Ot({bound:this,kwargs:e,config:{}})}map(){return new Rn({bound:this})}withRetry(e){return new Dc({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new Ot({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new h_({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 bc({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 Zt({generator:this._streamIterator(e,r),config:r});return await s.setup,Ne.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 _t(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 _t(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 mc(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 zm(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(Gm);let m=f.output;p!==void 0&&h!==void 0&&(m=p.tapOutputIterable(h.runId,m));const g=h?.handlers.find(qm);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 xn,r=t.addNode({name:`${this.getName()}Input`,schema:lc()}),s=t.addNode(this),a=t.addNode({name:`${this.getName()}Output`,schema:lc()});return t.addEdge(r,s),t.addEdge(s,a),t}pipe(e){return new It({first:this,last:xt(e)})}pick(e){return this.pipe(new p_(e))}assign(e){return this.pipe(new f_(new vr({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 yc({...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 yt({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"?c_(s):Ne.fromAsyncGenerator(s)}async*_streamEventsV2(e,t,r){const s=new Vm({...r,autoClose:!1}),a=Y(t),i=a.runId??rt();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 yc({...r,autoClose:!1,_schemaFormat:"streaming_events"}),d=new Jm({...r}),h=this._streamLog(e,l,i);for await(const p of h){if(s?s=s.concat(p):s=yr.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 T=v.streamed_output.length;if(T!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${T} 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 Wa(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new Ot({bound:this,config:{},configFactories:[s=>({callbacks:[new wc({config:s,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return m_(this,e)}}class Ot 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=fc(this.config,...e);return fc(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 Dc({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 Ne.fromAsyncGenerator(a())}static isRunnableBinding(e){return e.bound&&Ae.isRunnable(e.bound)}withListeners({onStart:e,onEnd:t,onError:r}){return new Ot({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[s=>({callbacks:[new wc({config:s,onStart:e,onEnd:t,onError:r})]})]})}}class Rn 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 Rn({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,we(t,{callbacks:r?.getChild()}))}withListeners({onStart:e,onEnd:t,onError:r}){return new Rn({bound:this.bound.withListeners({onStart:e,onEnd:t,onError:r})})}}class Dc extends Ot{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 we(t,{callbacks:r?.getChild(s)})}async _invoke(e,t,r){return Zr(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 Zr(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 It 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,we(r,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`)}));i=await _t(d,t?.signal)}if(t?.signal?.aborted)throw new Error("Aborted");o=await this.last.invoke(i,we(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 we(s[h],{callbacks:f})}),r);o=await _t(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(),we(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,we(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 xn;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 It.isRunnableSequence(e)?new It({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new It({first:this.first,middle:[...this.middle,this.last],last:xt(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 It({...s,first:xt(e),middle:t.slice(0,-1).map(xt),last:xt(t[t.length-1])})}}class vr 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]=xt(r)}static from(e){return new vr({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,we(r,{callbacks:a?.getChild(`map:key:${u}`)}))});await _t(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=pc(e,Object.keys(s).length),i=new Map(Object.entries(s).map(([o,u],c)=>{const l=u.transform(a[c],we(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 _t(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 Zt({generator:this.transform(r(),s),config:s});return await a.setup,Ne.fromAsyncGenerator(a)}}class ai 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}),!$a(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(we(r,{callbacks:s}),e);return _t(a,r?.signal)}async*_streamIterator(e,t){const[r]=this._getOptionsList(t??{},1),s=await this.invoke(e,t);if(ni(s)){for await(const a of s)r?.signal?.throwIfAborted(),yield a;return}if(l_(s)){for(;;){r?.signal?.throwIfAborted();const a=s.next();if(a.done)break;yield a.value}return}yield s}static from(e){return new ai({func:e})}}function d_(n){if($a(n))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn\'t happen.")}class Tn extends Ae{static lc_name(){return"RunnableLambda"}constructor(e){if($a(e.func))return ai.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}),d_(e.func),this.func=e.func}static from(e){return new Tn({func:e})}async _invoke(e,t,r){return new Promise((s,a)=>{const i=we(t,{callbacks:r?.getChild(),recursionLimit:(t?.recursionLimit??Za)-1});gt.runWithConfig(Vt(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??Za)-1})}else if(ni(o)){let u;for await(const c of si(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(jc(o)){let u;for(const c of Mc(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=we(r,{callbacks:t?.getChild(),recursionLimit:(r?.recursionLimit??Za)-1}),i=await new Promise((o,u)=>{gt.runWithConfig(Vt(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(ni(i))for await(const o of si(a,i))r?.signal?.throwIfAborted(),yield o;else if(jc(i))for(const o of Mc(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 Zt({generator:this.transform(r(),s),config:s});return await a.setup,Ne.fromAsyncGenerator(a)}}class h_ 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=we(i,{callbacks:o?.getChild()});return await gt.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=we(i,{callbacks:o?.getChild()});try{const f=await d.stream(e,h);c=si(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)=>we(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 xt(n){if(typeof n=="function")return new Tn({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]=xt(r);return new vr({steps:e})}else throw new Error(`Expected a Runnable, function or object.\nInstead got an unsupported type.`)}class f_ extends Ae{static lc_name(){return"RunnableAssign"}constructor(e){e instanceof vr&&(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]=pc(e),o=this.mapper.transform(i,we(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 Zt({generator:this.transform(r(),s),config:s});return await a.setup,Ne.fromAsyncGenerator(a)}}class p_ 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 Zt({generator:this.transform(r(),s),config:s});return await a.setup,Ne.fromAsyncGenerator(a)}}class Uc extends Ot{constructor(e){const t=It.from([Tn.from(async r=>{let s;if(Cp(r))try{s=await t_(this.schema,r.args)}catch{throw new $p("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 m_(n,e){const t=e.name??n.getName(),r=e.description??r_(e.schema);return n_(e.schema)?new Uc({name:t,description:r,schema:km({input:Tm()}).transform(s=>s.input),bound:n}):new Uc({name:t,description:r,schema:e.schema,bound:n})}class g_ 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(Qp(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 ii extends g_{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 __ extends St{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 ii({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 ii({...o,searchKwargs:e.searchKwargs}):new ii({...o})}}}class Wt{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 y_(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 b_(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 w_(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 Fc(n,e){return w_(n,e,b_)}function v_(n,e,t=.5,r=4){if(Math.min(r,e.length)<=0)return[];const s=Array.isArray(n[0])?n:[n],a=Fc(s,e)[0],i=E_(a).maxIndex,o=[e[i]],u=[i];for(;u.length<Math.min(r,e.length);){let c=-1/0,l=-1;const d=Fc(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 E_(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 kn extends __{_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??y_}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 Wt({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 Wt({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 v_(r,a,t.lambda,t.k).map(o=>new Wt({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 Wt({pageContent:e[i],metadata:o});a.push(u)}return kn.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 Bc=function(){const{crypto:n}=globalThis;if(n?.randomUUID)return Bc=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 oi(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}const ui=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 _e extends L{constructor(e,t,r,s){super(`${_e.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 Pn({message:r,cause:ui(t)});const a=t?.error;return e===400?new zc(e,a,r,s):e===401?new qc(e,a,r,s):e===403?new Hc(e,a,r,s):e===404?new Gc(e,a,r,s):e===409?new Vc(e,a,r,s):e===422?new Zc(e,a,r,s):e===429?new Wc(e,a,r,s):e>=500?new Jc(e,a,r,s):new _e(e,a,r,s)}}class je extends _e{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Pn extends _e{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Cn extends Pn{constructor({message:e}={}){super({message:e??"Request timed out."})}}class zc extends _e{}class qc extends _e{}class Hc extends _e{}class Gc extends _e{}class Vc extends _e{}class Zc extends _e{}class Wc extends _e{}class Jc extends _e{}class Kc extends L{constructor(){super("Could not parse response content as the length limit was reached")}}class Xc extends L{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Er extends Error{constructor(e){super(e)}}const S_=/^[a-z][a-z0-9+.-]*:/i,A_=n=>S_.test(n);let Pe=n=>(Pe=Array.isArray,Pe(n)),Qc=Pe;function O_(n){return typeof n!="object"?{}:n??{}}function I_(n){if(!n)return!0;for(const e in n)return!1;return!0}function x_(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function $n(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}const R_=(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},T_=n=>{try{return JSON.parse(n)}catch{return}},Sr=n=>new Promise(e=>setTimeout(e,n)),Jt="5.12.2",k_=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function P_(){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 C_=()=>{const n=P_();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Jt,"X-Stainless-OS":el(Deno.build.os),"X-Stainless-Arch":Yc(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":Jt,"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":Jt,"X-Stainless-OS":el(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Yc(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=$_();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Jt,"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":Jt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function $_(){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 Yc=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",el=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 tl;const N_=()=>tl??(tl=C_());function L_(){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 rl(...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 nl(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return rl({start(){},async pull(t){const{done:r,value:s}=await e.next();r?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function sl(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 j_(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 M_=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),al="RFC3986",il=n=>String(n),ol={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:il},D_="RFC1738";let ci=(n,e)=>(ci=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),ci(n,e));const Ye=(()=>{const n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})(),li=1024,U_=(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+=li){const u=a.length>=li?a.slice(o,o+li):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===D_&&(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 F_(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function ul(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 cl={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},ll=function(n,e){Array.prototype.push.apply(n,Pe(e)?e:[e])};let dl;const de={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:U_,encodeValuesOnly:!1,format:al,formatter:il,indices:!1,serializeDate(n){return(dl??(dl=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function B_(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}const di={};function hl(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(di))!==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(di)>"u"&&(E=0)}if(typeof c=="function"?_=c(e,_):_ instanceof Date?_=h?.(_):t==="comma"&&Pe(_)&&(_=ul(_,function(K){return K instanceof Date?h?.(K):K})),_===null){if(a)return u&&!m?u(e,de.encoder,g,"key",f):e;_=""}if(B_(_)||F_(_)){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 T=[];if(typeof _>"u")return T;let P;if(t==="comma"&&Pe(_))m&&u&&(_=ul(_,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 Lt=d&&o?ne.replace(/\\./g,"%2E"):ne,k=Pe(_)?typeof t=="function"?t(J,Lt):J:J+(d?"."+Lt:"["+Lt+"]");y.set(n,E);const I=new WeakMap;I.set(di,y),ll(T,hl(Je,k,t,r,s,a,i,o,t==="comma"&&m&&Pe(_)?null:u,c,l,d,h,f,p,m,g,I))}return T}function z_(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=al;if(typeof n.format<"u"){if(!ci(ol,n.format))throw new TypeError("Unknown format option provided.");t=n.format}const r=ol[t];let s=de.filter;(typeof n.filter=="function"||Pe(n.filter))&&(s=n.filter);let a;if(n.arrayFormat&&n.arrayFormat in cl?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 q_(n,e={}){let t=n;const r=z_(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=cl[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||ll(i,hl(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 H_(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 fl;function hi(n){let e;return(fl??(e=new globalThis.TextEncoder,fl=e.encode.bind(e)))(n)}let pl;function ml(n){let e;return(pl??(e=new globalThis.TextDecoder,pl=e.decode.bind(e)))(n)}var Me,De;class Nn{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"?hi(e):e;B(this,Me,H_([w(this,Me,"f"),t]));const r=[];let s;for(;(s=G_(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(ml(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=ml(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,Nn.NEWLINE_CHARS=new Set([`\n`,"\\r"]),Nn.NEWLINE_REGEXP=/\\r\\n|[\\n\\r]/g;function G_(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 V_(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 Ln={off:0,error:200,warn:300,info:400,debug:500},gl=(n,e,t)=>{if(n){if(x_(Ln,n))return n;ye(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Ln))}`)}};function Ar(){}function jn(n,e,t){return!e||Ln[n]>Ln[t]?Ar:e[n].bind(e)}const Z_={error:Ar,warn:Ar,info:Ar,debug:Ar};let _l=new WeakMap;function ye(n){const e=n.logger,t=n.logLevel??"off";if(!e)return Z_;const r=_l.get(e);if(r&&r[0]===t)return r[1];const s={error:jn("error",e,t),warn:jn("warn",e,t),info:jn("info",e,t),debug:jn("debug",e,t)};return _l.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 Or;class et{constructor(e,t,r){this.iterator=e,Or.set(this,void 0),this.controller=t,B(this,Or,r)}static fromSSEResponse(e,t,r){let s=!1;const a=r?ye(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 W_(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 _e(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 _e(void 0,c.error,c.message,void 0);yield{event:u.event,data:c}}}o=!0}catch(u){if(oi(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 Nn,u=sl(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(oi(u))return;throw u}finally{o||t.abort()}}return new et(i,t,r)}[(Or=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,Or,"f")),new et(()=>s(t),this.controller,w(this,Or,"f"))]}toReadableStream(){const e=this;let t;return rl({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=hi(JSON.stringify(s)+`\n`);r.enqueue(i)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}}async function*W_(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 K_,r=new Nn,s=sl(n.body);for await(const a of J_(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*J_(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"?hi(t):t;let s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let a;for(;(a=V_(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class K_{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]=X_(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}}function X_(n,e){const t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}async function yl(n,e){const{response:t,requestLogID:r,retryOfRequestLogID:s,startTime:a}=e,i=await(async()=>{if(e.options.stream)return ye(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 bl(d,t)}return await t.text()})();return ye(n).debug(`[${r}] response parsed`,Rt({retryOfRequestLogID:s,url:t.url,status:t.status,body:i,durationMs:Date.now()-a})),i}function bl(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 Ir;class Mn extends Promise{constructor(e,t,r=yl){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=r,Ir.set(this,void 0),B(this,Ir,e)}_thenUnwrap(e){return new Mn(w(this,Ir,"f"),this.responsePromise,async(t,r)=>bl(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,Ir,"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)}}Ir=new WeakMap;var Dn;class wl{constructor(e,t,r,s){Dn.set(this,void 0),B(this,Dn,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,Dn,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Dn=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Q_ extends Mn{constructor(e,t,r){super(e,t,async(s,a)=>new r(s,a.response,await yl(s,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class Un extends wl{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 wl{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:{...O_(this.options.query),after:t}}:null}}const vl=()=>{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 xr(n,e,t){return vl(),new File(n,e??"unknown_file",t)}function Fn(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 El=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",Tt=async(n,e)=>({...n,body:await ey(n.body,e)}),Sl=new WeakMap;function Y_(n){const e=typeof n=="function"?n:n.fetch,t=Sl.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 Sl.set(e,r),r}const ey=async(n,e)=>{if(!await Y_(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])=>fi(t,r,s))),t},ty=n=>n instanceof Blob&&"name"in n,fi=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,xr([await t.blob()],Fn(t)));else if(El(t))n.append(e,xr([await new Response(nl(t)).blob()],Fn(t)));else if(ty(t))n.append(e,t,Fn(t));else if(Array.isArray(t))await Promise.all(t.map(r=>fi(n,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,s])=>fi(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`)}},Al=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",ry=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&Al(n),ny=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function sy(n,e,t){if(vl(),n=await n,ry(n))return n instanceof File?n:xr([await n.arrayBuffer()],n.name);if(ny(n)){const s=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\\\/]/).pop()),xr(await pi(s),e,t)}const r=await pi(n);if(e||(e=Fn(n)),!t?.type){const s=r.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof s=="string"&&(t={...t,type:s})}return xr(r,e,t)}async function pi(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(Al(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(El(n))for await(const t of n)e.push(...await pi(t));else{const t=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${t?`; constructor: ${t}`:""}${ay(n)}`)}return e}function ay(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}class z{constructor(e){this._client=e}}function Ol(n){return n.replace(/[^A-Za-z0-9\\-._~!$&\'()*+,;=:@]+/g,encodeURIComponent)}const Il=Object.freeze(Object.create(null)),x=((n=Ol)=>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??Il)??Il)?.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})(Ol);let xl=class extends z{list(e,t={},r){return this._client.getAPIList(x`/chat/completions/${e}/messages`,oe,{query:t,...r})}};function Bn(n){return n!==void 0&&"function"in n&&n.function!==void 0}function mi(n){return n?.$brand==="auto-parseable-response-format"}function Rr(n){return n?.$brand==="auto-parseable-tool"}function iy(n,e){return!e||!Rl(e)?{...n,choices:n.choices.map(t=>(Tl(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:gi(n,e)}function gi(n,e){const t=n.choices.map(r=>{if(r.finish_reason==="length")throw new Kc;if(r.finish_reason==="content_filter")throw new Xc;return Tl(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(s=>uy(e,s))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?oy(e,r.message.content):null}}});return{...n,choices:t}}function oy(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 uy(n,e){const t=n.tools?.find(r=>Bn(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 cy(n,e){if(!n||!("tools"in n)||!n.tools)return!1;const t=n.tools?.find(r=>Bn(r)&&r.function?.name===e.function.name);return Bn(t)&&(Rr(t)||t?.function.strict||!1)}function Rl(n){return mi(n.response_format)?!0:n.tools?.some(e=>Rr(e)||e.type==="function"&&e.function.strict===!0)??!1}function Tl(n){for(const e of n||[])if(e.type!=="function")throw new L(`Currently only \\`function\\` tool calls are supported; Received \\`${e.type}\\``)}function ly(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 zn=n=>n?.role==="assistant",kl=n=>n?.role==="tool";var _i,qn,Hn,Tr,kr,Gn,Pr,it,Cr,Vn,Zn,Kt,Pl;class yi{constructor(){_i.add(this),this.controller=new AbortController,qn.set(this,void 0),Hn.set(this,()=>{}),Tr.set(this,()=>{}),kr.set(this,void 0),Gn.set(this,()=>{}),Pr.set(this,()=>{}),it.set(this,{}),Cr.set(this,!1),Vn.set(this,!1),Zn.set(this,!1),Kt.set(this,!1),B(this,qn,new Promise((e,t)=>{B(this,Hn,e,"f"),B(this,Tr,t,"f")})),B(this,kr,new Promise((e,t)=>{B(this,Gn,e,"f"),B(this,Pr,t,"f")})),w(this,qn,"f").catch(()=>{}),w(this,kr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},w(this,_i,"m",Pl).bind(this))},0)}_connected(){this.ended||(w(this,Hn,"f").call(this),this._emit("connect"))}get ended(){return w(this,Cr,"f")}get errored(){return w(this,Vn,"f")}get aborted(){return w(this,Zn,"f")}abort(){this.controller.abort()}on(e,t){return(w(this,it,"f")[e]||(w(this,it,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=w(this,it,"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,it,"f")[e]||(w(this,it,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{B(this,Kt,!0),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){B(this,Kt,!0),await w(this,kr,"f")}_emit(e,...t){if(w(this,Cr,"f"))return;e==="end"&&(B(this,Cr,!0),w(this,Gn,"f").call(this));const r=w(this,it,"f")[e];if(r&&(w(this,it,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!w(this,Kt,"f")&&!r?.length&&Promise.reject(s),w(this,Tr,"f").call(this,s),w(this,Pr,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!w(this,Kt,"f")&&!r?.length&&Promise.reject(s),w(this,Tr,"f").call(this,s),w(this,Pr,"f").call(this,s),this._emit("end")}}_emitFinal(){}}qn=new WeakMap,Hn=new WeakMap,Tr=new WeakMap,kr=new WeakMap,Gn=new WeakMap,Pr=new WeakMap,it=new WeakMap,Cr=new WeakMap,Vn=new WeakMap,Zn=new WeakMap,Kt=new WeakMap,_i=new WeakSet,Pl=function(e){if(B(this,Vn,!0),e instanceof Error&&e.name==="AbortError"&&(e=new je),e instanceof je)return B(this,Zn,!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 dy(n){return typeof n.parse=="function"}var Oe,bi,Wn,wi,vi,Ei,Cl,$l;const hy=10;class Nl extends yi{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),kl(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(zn(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",bi).call(this)}async finalMessage(){return await this.done(),w(this,Oe,"m",Wn).call(this)}async finalFunctionToolCall(){return await this.done(),w(this,Oe,"m",wi).call(this)}async finalFunctionToolCallResult(){return await this.done(),w(this,Oe,"m",vi).call(this)}async totalUsage(){return await this.done(),w(this,Oe,"m",Ei).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",Wn).call(this);t&&this._emit("finalMessage",t);const r=w(this,Oe,"m",bi).call(this);r&&this._emit("finalContent",r);const s=w(this,Oe,"m",wi).call(this);s&&this._emit("finalFunctionToolCall",s);const a=w(this,Oe,"m",vi).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",w(this,Oe,"m",Ei).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",Cl).call(this,t);const a=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(gi(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=hy}=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=dy(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 T=await E.function(v,this),P=w(this,Oe,"m",$l).call(this,T);if(this._addMessage({role:s,tool_call_id:y,content:P}),u)return}}}}Oe=new WeakSet,bi=function(){return w(this,Oe,"m",Wn).call(this).content??null},Wn=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(zn(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new L("stream ended without producing a ChatCompletionMessage with role=assistant")},wi=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(zn(t)&&t?.tool_calls?.length)return t.tool_calls.filter(r=>r.type==="function").at(-1)?.function}},vi=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(kl(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}},Ei=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},Cl=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.")},$l=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Si extends Nl{static runTools(e,t,r){const s=new Si,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),zn(e)&&e.content&&this._emit("content",e.content)}}const Ll=1,jl=2,Ml=4,Dl=8,Ul=16,Fl=32,Bl=64,zl=128,ql=256,Hl=zl|ql,Gl=Ul|Fl|Hl|Bl,Vl=Ll|jl|Gl,Zl=Ml|Dl,fy=Vl|Zl,pe={STR:Ll,NUM:jl,ARR:Ml,OBJ:Dl,NULL:Ul,BOOL:Fl,NAN:Bl,INFINITY:zl,MINUS_INFINITY:ql,INF:Hl,SPECIAL:Gl,ATOM:Vl,COLLECTION:Zl,ALL:fy};class py extends Error{}class my extends Error{}function gy(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 _y(n.trim(),e)}const _y=(n,e)=>{const t=n.length;let r=0;const s=h=>{throw new py(`${h} at position ${r}`)},a=h=>{throw new my(`${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()},Wl=n=>gy(n,pe.ALL^pe.NUM);var he,ot,Xt,vt,Ai,Jn,Oi,Ii,xi,Kn,Ri,Jl;class $r extends Nl{constructor(e){super(),he.add(this),ot.set(this,void 0),Xt.set(this,void 0),vt.set(this,void 0),B(this,ot,e),B(this,Xt,[])}get currentChatCompletionSnapshot(){return w(this,vt,"f")}static fromReadableStream(e){const t=new $r(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){const s=new $r(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",Ai).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",Oi).call(this,i);if(a.controller.signal?.aborted)throw new je;return this._addChatCompletion(w(this,he,"m",Kn).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",Ai).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",Kn).call(this)),w(this,he,"m",Oi).call(this,i),a=i.id;if(s.controller.signal?.aborted)throw new je;return this._addChatCompletion(w(this,he,"m",Kn).call(this))}[(ot=new WeakMap,Xt=new WeakMap,vt=new WeakMap,he=new WeakSet,Ai=function(){this.ended||B(this,vt,void 0)},Jn=function(t){let r=w(this,Xt,"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,Xt,"f")[t.index]=r,r)},Oi=function(t){if(this.ended)return;const r=w(this,he,"m",Jl).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",Jn).call(this,a);a.finish_reason&&(w(this,he,"m",xi).call(this,a),i.current_tool_call_index!=null&&w(this,he,"m",Ii).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",xi).call(this,a),i.current_tool_call_index!=null&&w(this,he,"m",Ii).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))}}},Ii=function(t,r){if(w(this,he,"m",Jn).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,ot,"f")?.tools?.find(o=>Bn(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},xi=function(t){const r=w(this,he,"m",Jn).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;const s=w(this,he,"m",Ri).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}))},Kn=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 chunks");return B(this,vt,void 0),B(this,Xt,[]),yy(t,w(this,ot,"f"))},Ri=function(){const t=w(this,ot,"f")?.response_format;return mi(t)?t:null},Jl=function(t){var r,s,a,i;let o=w(this,vt,"f");const{choices:u,...c}=t;o?Object.assign(o,c):o=B(this,vt,{...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:T,refusal:P,...O}=f;Object.assign(m.logprobs,O),T&&((r=m.logprobs).content??(r.content=[]),m.logprobs.content.push(...T)),P&&((s=m.logprobs).refusal??(s.refusal=[]),m.logprobs.refusal.push(...P))}if(d&&(m.finish_reason=d,w(this,ot,"f")&&Rl(w(this,ot,"f")))){if(d==="length")throw new Kc;if(d==="content_filter")throw new Xc}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",Ri).call(this)&&(m.message.parsed=Wl(m.message.content))),E){m.message.tool_calls||(m.message.tool_calls=[]);for(const{index:T,id:P,type:O,function:J,...K}of E){const ne=(i=m.message.tool_calls)[T]??(i[T]={});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,cy(w(this,ot,"f"),ne)&&(ne.function.parsed_arguments=Wl(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 yy(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:T,id:P,...O}=b,{arguments:J,name:K,...ne}=v||{};if(P==null)throw new L(`missing choices[${d}].tool_calls[${E}].id\n${Xn(n)}`);if(T==null)throw new L(`missing choices[${d}].tool_calls[${E}].type\n${Xn(n)}`);if(K==null)throw new L(`missing choices[${d}].tool_calls[${E}].function.name\n${Xn(n)}`);if(J==null)throw new L(`missing choices[${d}].tool_calls[${E}].function.arguments\n${Xn(n)}`);return{...O,id:P,type:T,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 iy(u,e)}function Xn(n){return JSON.stringify(n)}function ab(n){}class Qn extends $r{static fromReadableStream(e){const t=new Qn(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){const s=new Qn(t),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,a)),s}}let Ti=class extends z{constructor(){super(...arguments),this.messages=new xl(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(x`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(x`/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(x`/chat/completions/${e}`,t)}parse(e,t){return ly(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>gi(r,e))}runTools(e,t){return e.stream?Qn.runTools(this._client,e,t):Si.runTools(this._client,e,t)}stream(e,t){return $r.createChatCompletion(this._client,e,t)}};Ti.Messages=xl;class ki extends z{constructor(){super(...arguments),this.completions=new Ti(this._client)}}ki.Completions=Ti;const Kl=Symbol("brand.privateNullableHeaders");function*by(n){if(!n)return;if(Kl 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():Qc(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=Qc(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 by(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{[Kl]:!0,values:e,nulls:t}};class Xl 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 Ql 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 Yl 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 Ql(this._client),this.translations=new Yl(this._client),this.speech=new Xl(this._client)}}Nr.Transcriptions=Ql,Nr.Translations=Yl,Nr.Speech=Xl;class ed extends z{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(x`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",oe,{query:e,...t})}cancel(e,t){return this._client.post(x`/batches/${e}/cancel`,t)}}class td 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(x`/assistants/${e}`,{...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(x`/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(x`/assistants/${e}`,{...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class rd extends z{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class nd extends z{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Yn extends z{constructor(){super(...arguments),this.sessions=new rd(this._client),this.transcriptionSessions=new nd(this._client)}}Yn.Sessions=rd,Yn.TranscriptionSessions=nd;class sd extends z{create(e,t,r){return this._client.post(x`/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(x`/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(x`/threads/${s}/messages/${e}`,{body:a,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(x`/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(x`/threads/${s}/messages/${e}`,{...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class ad extends z{retrieve(e,t,r){const{thread_id:s,run_id:a,...i}=t;return this._client.get(x`/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(x`/threads/${s}/runs/${e}/steps`,oe,{query:a,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}const wy=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))}},ut=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 be,kt,Pi,tt,es,We,Pt,Qt,Ct,ts,Ue,rs,ns,Lr,jr,Mr,id,od,ud,cd,ld,dd,hd;class Dr extends yi{constructor(){super(...arguments),be.add(this),Pi.set(this,[]),tt.set(this,{}),es.set(this,{}),We.set(this,void 0),Pt.set(this,void 0),Qt.set(this,void 0),Ct.set(this,void 0),ts.set(this,void 0),Ue.set(this,void 0),rs.set(this,void 0),ns.set(this,void 0),Lr.set(this,void 0)}[(Pi=new WeakMap,tt=new WeakMap,es=new WeakMap,We=new WeakMap,Pt=new WeakMap,Qt=new WeakMap,Ct=new WeakMap,ts=new WeakMap,Ue=new WeakMap,rs=new WeakMap,ns=new WeakMap,Lr=new WeakMap,be=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 kt;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,be,"m",jr).call(this,a);if(s.controller.signal?.aborted)throw new je;return this._addRun(w(this,be,"m",Mr).call(this))}toReadableStream(){return new et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){const a=new kt;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,be,"m",jr).call(this,u);if(o.controller.signal?.aborted)throw new je;return this._addRun(w(this,be,"m",Mr).call(this))}static createThreadAssistantStream(e,t,r){const s=new kt;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 kt;return a._run(()=>a._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return w(this,rs,"f")}currentRun(){return w(this,ns,"f")}currentMessageSnapshot(){return w(this,We,"f")}currentRunStepSnapshot(){return w(this,Lr,"f")}async finalRunSteps(){return await this.done(),Object.values(w(this,tt,"f"))}async finalMessages(){return await this.done(),Object.values(w(this,es,"f"))}async finalRun(){if(await this.done(),!w(this,Pt,"f"))throw Error("Final run was not received.");return w(this,Pt,"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,be,"m",jr).call(this,o);if(i.controller.signal?.aborted)throw new je;return this._addRun(w(this,be,"m",Mr).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,be,"m",jr).call(this,u);if(o.controller.signal?.aborted)throw new je;return this._addRun(w(this,be,"m",Mr).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($n(a)&&$n(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(!$n(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)}}kt=Dr,jr=function(e){if(!this.ended)switch(B(this,rs,e),w(this,be,"m",ud).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,be,"m",hd).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,be,"m",od).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,be,"m",id).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Mr=function(){if(this.ended)throw new L("stream has ended, this shouldn\'t happen");if(!w(this,Pt,"f"))throw Error("Final run has not been received");return w(this,Pt,"f")},id=function(e){const[t,r]=w(this,be,"m",ld).call(this,e,w(this,We,"f"));B(this,We,t),w(this,es,"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,Qt,"f")){if(w(this,Ct,"f"))switch(w(this,Ct,"f").type){case"text":this._emit("textDone",w(this,Ct,"f").text,w(this,We,"f"));break;case"image_file":this._emit("imageFileDone",w(this,Ct,"f").image_file,w(this,We,"f"));break}B(this,Qt,s.index)}B(this,Ct,t.content[s.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(w(this,Qt,"f")!==void 0){const s=e.data.content[w(this,Qt,"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)}},od=function(e){const t=w(this,be,"m",cd).call(this,e);switch(B(this,Lr,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,ts,"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,ts,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,Lr,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}},ud=function(e){w(this,Pi,"f").push(e),this._emit("event",e)},cd=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=kt.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")},ld=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,be,"m",dd).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")},dd=function(e,t){return kt.accumulateDelta(t,e)},hd=function(e){switch(B(this,ns,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,Pt,e.data),w(this,Ue,"f")&&(this._emit("toolCallDone",w(this,Ue,"f")),B(this,Ue,void 0));break}};let Ci=class extends z{constructor(){super(...arguments),this.steps=new ad(this._client)}create(e,t,r){const{include:s,...a}=t;return this._client.post(x`/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(x`/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(x`/threads/${s}/runs/${e}`,{body:a,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(x`/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(x`/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 Dr.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 Sr(o);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,t,r){return Dr.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){const{thread_id:s,...a}=t;return this._client.post(x`/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 Dr.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};Ci.Steps=ad;class ss extends z{constructor(){super(...arguments),this.runs=new Ci(this._client),this.messages=new sd(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(x`/threads/${e}`,{...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(x`/threads/${e}`,{body:t,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(x`/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 Dr.createThreadAssistantStream(e,this._client.beta.threads,t)}}ss.Runs=Ci,ss.Messages=sd;class Ur extends z{constructor(){super(...arguments),this.realtime=new Yn(this._client),this.assistants=new td(this._client),this.threads=new ss(this._client)}}Ur.Realtime=Yn,Ur.Assistants=td,Ur.Threads=ss;class fd extends z{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class pd extends z{retrieve(e,t,r){const{container_id:s}=t;return this._client.get(x`/containers/${s}/files/${e}/content`,{...r,headers:j([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}let $i=class extends z{constructor(){super(...arguments),this.content=new pd(this._client)}create(e,t,r){return this._client.post(x`/containers/${e}/files`,Tt({body:t,...r},this._client))}retrieve(e,t,r){const{container_id:s}=t;return this._client.get(x`/containers/${s}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(x`/containers/${e}/files`,oe,{query:t,...r})}delete(e,t,r){const{container_id:s}=t;return this._client.delete(x`/containers/${s}/files/${e}`,{...r,headers:j([{Accept:"*/*"},r?.headers])})}};$i.Content=pd;class Ni extends z{constructor(){super(...arguments),this.files=new $i(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(x`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",oe,{query:e,...t})}delete(e,t){return this._client.delete(x`/containers/${e}`,{...t,headers:j([{Accept:"*/*"},t?.headers])})}}Ni.Files=$i;let md=class extends z{create(e,t){const r=!!e.encoding_format;let s=r?e.encoding_format:"base64";r&&ye(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:(ye(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=wy(u)}),i)))}};class gd extends z{retrieve(e,t,r){const{eval_id:s,run_id:a}=t;return this._client.get(x`/evals/${s}/runs/${a}/output_items/${e}`,r)}list(e,t,r){const{eval_id:s,...a}=t;return this._client.getAPIList(x`/evals/${s}/runs/${e}/output_items`,oe,{query:a,...r})}}class Li extends z{constructor(){super(...arguments),this.outputItems=new gd(this._client)}create(e,t,r){return this._client.post(x`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){const{eval_id:s}=t;return this._client.get(x`/evals/${s}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(x`/evals/${e}/runs`,oe,{query:t,...r})}delete(e,t,r){const{eval_id:s}=t;return this._client.delete(x`/evals/${s}/runs/${e}`,r)}cancel(e,t,r){const{eval_id:s}=t;return this._client.post(x`/evals/${s}/runs/${e}`,r)}}Li.OutputItems=gd;class ji extends z{constructor(){super(...arguments),this.runs=new Li(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(x`/evals/${e}`,t)}update(e,t,r){return this._client.post(x`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",oe,{query:e,...t})}delete(e,t){return this._client.delete(x`/evals/${e}`,t)}}ji.Runs=Li;let _d=class extends z{create(e,t){return this._client.post("/files",Tt({body:e,...t},this._client))}retrieve(e,t){return this._client.get(x`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",oe,{query:e,...t})}delete(e,t){return this._client.delete(x`/files/${e}`,t)}content(e,t){return this._client.get(x`/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 Sr(t),i=await this.retrieve(e),Date.now()-a>r)throw new Cn({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};class yd extends z{}let bd=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 Mi extends z{constructor(){super(...arguments),this.graders=new bd(this._client)}}Mi.Graders=bd;class wd extends z{create(e,t,r){return this._client.getAPIList(x`/fine_tuning/checkpoints/${e}/permissions`,Un,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(x`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){const{fine_tuned_model_checkpoint:s}=t;return this._client.delete(x`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}}let Di=class extends z{constructor(){super(...arguments),this.permissions=new wd(this._client)}};Di.Permissions=wd;class vd extends z{list(e,t={},r){return this._client.getAPIList(x`/fine_tuning/jobs/${e}/checkpoints`,oe,{query:t,...r})}}class Ui extends z{constructor(){super(...arguments),this.checkpoints=new vd(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(x`/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(x`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(x`/fine_tuning/jobs/${e}/events`,oe,{query:t,...r})}pause(e,t){return this._client.post(x`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(x`/fine_tuning/jobs/${e}/resume`,t)}}Ui.Checkpoints=vd;class Yt extends z{constructor(){super(...arguments),this.methods=new yd(this._client),this.jobs=new Ui(this._client),this.checkpoints=new Di(this._client),this.alpha=new Mi(this._client)}}Yt.Methods=yd,Yt.Jobs=Ui,Yt.Checkpoints=Di,Yt.Alpha=Mi;class Ed extends z{}class Fi extends z{constructor(){super(...arguments),this.graderModels=new Ed(this._client)}}Fi.GraderModels=Ed;class Sd 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 Ad extends z{retrieve(e,t){return this._client.get(x`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Un,e)}delete(e,t){return this._client.delete(x`/models/${e}`,t)}}class Od extends z{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function vy(n,e){return!e||!Sy(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)}:Id(n,e)}function Id(n,e){const t=n.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:Iy(e,s)};if(s.type==="message"){const a=s.content.map(i=>i.type==="output_text"?{...i,parsed:Ey(e,i.text)}:i);return{...s,content:a}}return s}),r=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||Bi(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 Ey(n,e){return n.text?.format?.type!=="json_schema"?null:"$parseRaw"in n.text?.format?(n.text?.format).$parseRaw(e):JSON.parse(e)}function Sy(n){return!!mi(n.text?.format)}function Ay(n){return n?.$brand==="auto-parseable-tool"}function Oy(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function Iy(n,e){const t=Oy(n.tools??[],e.name);return{...e,...e,parsed_arguments:Ay(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Bi(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 er,as,Et,is,xd,Rd,Td,kd;class zi extends yi{constructor(e){super(),er.add(this),as.set(this,void 0),Et.set(this,void 0),is.set(this,void 0),B(this,as,e)}static createResponse(e,t,r){const s=new zi(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,er,"m",xd).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,er,"m",Rd).call(this,o,i);if(a.controller.signal?.aborted)throw new je;return w(this,er,"m",Td).call(this)}[(as=new WeakMap,Et=new WeakMap,is=new WeakMap,er=new WeakSet,xd=function(){this.ended||B(this,Et,void 0)},Rd=function(t,r){if(this.ended)return;const s=(i,o)=>{(r==null||o.sequence_number>r)&&this._emit(i,o)},a=w(this,er,"m",kd).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}},Td=function(){if(this.ended)throw new L("stream has ended, this shouldn\'t happen");const t=w(this,Et,"f");if(!t)throw new L("request ended without sending any events");B(this,Et,void 0);const r=xy(t,w(this,as,"f"));return B(this,is,r),r},kd=function(t){let r=w(this,Et,"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,Et,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,Et,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,is,"f");if(!e)throw new L("stream ended without producing a ChatCompletion");return e}}function xy(n,e){return vy(n,e)}class Pd extends z{list(e,t={},r){return this._client.getAPIList(x`/responses/${e}/input_items`,oe,{query:t,...r})}}class qi extends z{constructor(){super(...arguments),this.inputItems=new Pd(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"&&Bi(r),r))}retrieve(e,t={},r){return this._client.get(x`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Bi(s),s))}delete(e,t){return this._client.delete(x`/responses/${e}`,{...t,headers:j([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>Id(r,e))}stream(e,t){return zi.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(x`/responses/${e}/cancel`,t)}}qi.InputItems=Pd;class Cd extends z{create(e,t,r){return this._client.post(x`/uploads/${e}/parts`,Tt({body:t,...r},this._client))}}class Hi extends z{constructor(){super(...arguments),this.parts=new Cd(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(x`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(x`/uploads/${e}/complete`,{body:t,...r})}}Hi.Parts=Cd;const Ry=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 $d extends z{create(e,t,r){return this._client.post(x`/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(x`/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(x`/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(x`/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 Sr(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 Ry(d),await this.createAndPoll(e,{file_ids:c})}}class Nd extends z{create(e,t,r){return this._client.post(x`/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(x`/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(x`/vector_stores/${s}/files/${e}`,{body:a,...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(x`/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(x`/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 Sr(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(x`/vector_stores/${s}/files/${e}/content`,Un,{...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class os extends z{constructor(){super(...arguments),this.files=new Nd(this._client),this.fileBatches=new $d(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(x`/vector_stores/${e}`,{...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(x`/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(x`/vector_stores/${e}`,{...t,headers:j([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(x`/vector_stores/${e}/search`,Un,{body:t,method:"post",...r,headers:j([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}os.Files=Nd,os.FileBatches=$d;var tr,Ld,us;class jd extends z{constructor(){super(...arguments),tr.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,tr,"m",Ld).call(this,r);const a=j([t]).values,i=w(this,tr,"m",us).call(this,a,"webhook-signature"),o=w(this,tr,"m",us).call(this,a,"webhook-timestamp"),u=w(this,tr,"m",us).call(this,a,"webhook-id"),c=parseInt(o,10);if(isNaN(c))throw new Er("Invalid webhook timestamp format");const l=Math.floor(Date.now()/1e3);if(l-c>s)throw new Er("Webhook timestamp is too old");if(c>l+s)throw new Er("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 Er("The given webhook signature does not match the expected signature")}}tr=new WeakSet,Ld=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")},us=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 Gi,Vi,cs,Md;let Z=class{constructor({baseURL:e=ut("OPENAI_BASE_URL"),apiKey:t=ut("OPENAI_API_KEY"),organization:r=ut("OPENAI_ORG_ID")??null,project:s=ut("OPENAI_PROJECT_ID")??null,webhookSecret:a=ut("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(Gi.add(this),cs.set(this,void 0),this.completions=new fd(this),this.chat=new ki(this),this.embeddings=new md(this),this.files=new _d(this),this.images=new Sd(this),this.audio=new Nr(this),this.moderations=new Od(this),this.models=new Ad(this),this.fineTuning=new Yt(this),this.graders=new Fi(this),this.vectorStores=new os(this),this.webhooks=new jd(this),this.beta=new Ur(this),this.batches=new ed(this),this.uploads=new Hi(this),this.responses=new qi(this),this.evals=new ji(this),this.containers=new Ni(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&&k_())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??Vi.DEFAULT_TIMEOUT,this.logger=o.logger??console;const u="warn";this.logLevel=u,this.logLevel=gl(o.logLevel,"ClientOptions.logLevel",this)??gl(ut("OPENAI_LOG"),"process.env[\'OPENAI_LOG\']",this)??u,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??L_(),B(this,cs,M_),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 q_(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Jt}`}defaultIdempotencyKey(){return`stainless-node-retry-${Bc()}`}makeStatusError(e,t,r,s){return _e.generate(e,t,r,s)}buildURL(e,t,r){const s=!w(this,Gi,"m",Md).call(this)&&r||this.baseURL,a=A_(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return I_(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 Mn(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(ye(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(ui),p=Date.now();if(f instanceof Error){const y=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new je;const _=oi(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return ye(this).info(`[${c}] connection ${_?"timed out":"failed"} - ${y}`),ye(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 ye(this).info(`[${c}] connection ${_?"timed out":"failed"} - error; no more retries left`),ye(this).debug(`[${c}] connection ${_?"timed out":"failed"} (error; no more retries left)`,Rt({retryOfRequestLogID:r,url:o,durationMs:p-d,message:f.message})),_?new Cn:new Pn({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 j_(f.body),ye(this).info(`${g} - ${P}`),ye(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";ye(this).info(`${g} - ${_}`);const b=await f.text().catch(P=>ui(P).message),E=T_(b),v=E?void 0:b;throw ye(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 ye(this).info(g),ye(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 Q_(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 Sr(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&&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))}:{},...N_(),"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:nl(e)}:w(this,cs,"f").call(this,{body:e,headers:r})}};Vi=Z,cs=new WeakMap,Gi=new WeakSet,Md=function(){return this.baseURL!=="https://api.openai.com/v1"},Z.OpenAI=Vi,Z.DEFAULT_TIMEOUT=6e5,Z.OpenAIError=L,Z.APIError=_e,Z.APIConnectionError=Pn,Z.APIConnectionTimeoutError=Cn,Z.APIUserAbortError=je,Z.NotFoundError=Gc,Z.ConflictError=Vc,Z.RateLimitError=Wc,Z.BadRequestError=zc,Z.AuthenticationError=qc,Z.InternalServerError=Jc,Z.PermissionDeniedError=Hc,Z.UnprocessableEntityError=Zc,Z.InvalidWebhookSignatureError=Er,Z.toFile=sy,Z.Completions=fd,Z.Chat=ki,Z.Embeddings=md,Z.Files=_d,Z.Images=Sd,Z.Audio=Nr,Z.Moderations=Od,Z.Models=Ad,Z.FineTuning=Yt,Z.Graders=Fi,Z.VectorStores=os,Z.Webhooks=jd,Z.Beta=Ur,Z.Batches=ed,Z.Uploads=Hi,Z.Responses=qi,Z.Evals=ji,Z.Containers=Ni;let Ty=class extends Z{constructor({baseURL:e=ut("OPENAI_BASE_URL"),apiKey:t=ut("AZURE_OPENAI_API_KEY"),apiVersion:r=ut("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=Dd),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(ky.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!$n(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!==Dd)e.headers.values.set("api-key",this.apiKey);else throw new L("Unable to handle auth");return super.prepareOptions(e)}};const ky=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]),Dd="<Missing Key>";var Fr={},Ud;function Py(){if(Ud)return Fr;Ud=1,Fr.byteLength=o,Fr.toByteArray=c,Fr.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 Fr}var Cy=Py(),$y=rr(Cy),Ny=Object.defineProperty,Ly=(n,e,t)=>e in n?Ny(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,jy=(n,e,t)=>(Ly(n,e+"",t),t);function My(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 Dy(n,e){return n.length===1?[e.get(n.join(","))]:My(n,e).map(t=>e.get(n.slice(t.start,t.end).join(","))).filter(t=>t!=null)}function Uy(n){return n.replace(/[\\\\^$*+?.()|[\\]{}]/g,"\\\\$&")}var Zi=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=$y.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=Zi.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=Zi.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(...Dy(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)}},Fy=Zi;jy(Fy,"specialTokenRegex",n=>new RegExp(n.map(e=>Uy(e)).join("|"),"g"));function Fd(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 ls(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 Bd(n){let e;return n.constructor.name===Cn.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=ls(n,"INVALID_TOOL_RESULTS"):n.status===401?e=ls(n,"MODEL_AUTHENTICATION"):n.status===429?e=ls(n,"MODEL_RATE_LIMIT"):n.status===404?e=ls(n,"MODEL_NOT_FOUND"):e=n,e}const By=n=>n();function zd(n){return typeof Headers<"u"&&n!==null&&typeof n=="object"&&Object.prototype.toString.call(n)==="[object Headers]"}function zy(n){const e=By(()=>{if(zd(n))return n;if(Array.isArray(n))return new Headers(n);if(typeof n=="object"&&n!==null&&"values"in n&&zd(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 qy=(n,e)=>n.reduce((t,r,s)=>{const a=Math.floor(s/e),i=t[a]||[];return t[a]=i.concat([r]),t},[]);class Hy{constructor(e){Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.caller=new bc(e??{})}}class Gy extends Hy{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??xe("OPENAI_API_KEY");this.organization=t?.configuration?.organization??xe("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=qy(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=Fd(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 Bd(r)}})}}class Vy extends Gy{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??xe("AZURE_OPENAI_API_KEY"),this.azureOpenAIApiVersion=e?.azureOpenAIApiVersion??e?.openAIApiVersion??xe("AZURE_OPENAI_API_VERSION"),this.azureOpenAIBasePath=e?.azureOpenAIBasePath??xe("AZURE_OPENAI_BASE_PATH"),this.azureOpenAIApiInstanceName=e?.azureOpenAIApiInstanceName??xe("AZURE_OPENAI_API_INSTANCE_NAME"),this.azureOpenAIApiDeploymentName=(e?.azureOpenAIApiEmbeddingsDeploymentName||e?.azureOpenAIApiDeploymentName)??(xe("AZURE_OPENAI_API_EMBEDDINGS_DEPLOYMENT_NAME")||xe("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=Fd(r),a={...this.clientConfig,baseURL:s,timeout:this.timeout,maxRetries:0};this.azureADTokenProvider||(a.apiKey=r.azureOpenAIApiKey),a.baseURL||delete a.baseURL;const i=zy(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 Ty({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 Bd(r)}})}}const Zy={"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"}},Wy={default:"text-embedding-ada-002"},Jy=["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"],Ky=n=>async(e,t)=>{const r=new Headers(t?.headers);return Jy.forEach(s=>r.delete(s)),n&&n.length>0&&r.set("X-Esri-Authorization",`Bearer ${n}`),await fetch(e,{...t,headers:r})};let $t,Nt;const ds=new Map,Xy=12,Qy=10,Yy=async n=>{if(!$t)return;Nt?Nt.memoryVectors=[]:Nt=new kn($t);const e=[];for(const[t,{layerItem:r}]of n.entries()){const s=`Name: ${r.name}\nTitle: ${r.title}\nDescription: ${r.description}`,a=new Wt({id:t,pageContent:s,metadata:{layerId:t}});e.push(a)}await Nt.addDocuments(e),console.log("Layer Vectorstore contents:",Nt.memoryVectors)},eb=async n=>{if(!$t)return;ds.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 Wt({id:u,pageContent:l,metadata:{layerId:t}})),a.push(l)}const i=new kn($t),o=(async()=>{const u=await $t.embedDocuments(a);await i.addVectors(u,s),ds.set(t,i)})();e.push(o)}await Promise.all(e),console.log("Field Vectorstore contents:",Array.from(ds.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=Wy.default,u=Zy[o];$t=new Vy({azureOpenAIApiKey:"x",azureOpenAIBasePath:i.apiUrl,azureOpenAIApiDeploymentName:u.deploymentName,azureOpenAIApiVersion:u.apiVersion,model:o,batchSize:2048,maxConcurrency:10,configuration:{fetch:Ky(i.token)}}),t&&(await Yy(t),await eb(t)),globalThis.postMessage("completed");break}case"layerSearch":{if(r&&Nt){const o=await Nt.similaritySearchWithScore(r,Qy);globalThis.postMessage({requestId:a,results:o})}break}case"fieldSearch":{if(r&&s.length>0){const o=await $t.embedQuery(r),u=s.map(async d=>{const h=ds.get(d);if(!h)return null;const f=await h.similaritySearchVectorWithScore(o,Xy);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
|
+
};
|