(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[349],{1192:(e,t,r)=>{let a=r(89377);e.exports=(e,t)=>{let r=a(e,t);return r&&r.prerelease.length?r.prerelease:null}},1776:(e,t,r)=>{"use strict";r.d(t,{Az:()=>a.Az});var a=r(4397)},1995:(e,t,r)=>{"use strict";r.d(t,{YN:()=>a.YN,kI:()=>i.k,zZ:()=>a.zZ});var a=r(4693),i=(r(92173),r(27123));a.YN,r(87150),a.YN,r(71150),a.fJ},3909:(e,t,r)=>{"use strict";r.d(t,{vd:()=>s,CC:()=>o});var a,i=r(1995),n=r(42452);class s extends i.YN{parseResultWithPrompt(e,t,r){return this.parseResult(e,r)}_baseMessageToString(e){return"string"==typeof e.content?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return"string"==typeof e?this._callWithConfig(async(e,t)=>this.parseResult([{text:e}],t?.callbacks),e,{...t,runType:"parser"}):this._callWithConfig(async(e,t)=>this.parseResult([{message:e,text:this._baseMessageToString(e)}],t?.callbacks),e,{...t,runType:"parser"})}}class o extends Error{constructor(e,t,r,a=!1){if(super(e),Object.defineProperty(this,"llmOutput",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"observation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sendToLLM",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.llmOutput=t,this.observation=r,this.sendToLLM=a,a&&(void 0===r||void 0===t))throw Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");(0,n.Y)(this,"OUTPUT_PARSING_FAILURE")}}"undefined"!=typeof self&&self.location&&"null"!==self.location.origin?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");let l=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,u=[0,31,28,31,30,31,30,31,31,30,31,30,31],c=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,h=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,d=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,p=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,f=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,m=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,g=/^(?:\/(?:[^~/]|~0|~1)*)*$/,y=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,b=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,_=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,w=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i;function v(e){return e.test.bind(e)}function O(e){return e%4==0&&(e%100!=0||e%400==0)}(function e(e,t){let r=t.match(c);if(!r)return!1;let a=+r[1],i=+r[2],n=+r[3],s=!!r[5];return(a<=23&&i<=59&&n<=59||23==a&&59==i&&60==n)&&(!e||s)}).bind(void 0,!1),v(d),v(p),v(f),v(h),v(_),v(w),v(m),v(g),v(y),v(b);!function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"}(a||(a={})),r(64520),r(90338),r(23294),r(55594),r(50084),r(82591),r(58036);let E=e=>{if(0===Object.keys(e).length)return{};let t={};return e.children.length>0?t[e.name]=e.children.map(E):t[e.name]=e.text??void 0,t}},4071:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r){let a=0,i=e.length;for(;i>0;){let n=i/2|0,s=a+n;0>=r(e[s],t)?(a=++s,i-=n+1):i=n}return a}},4397:(e,t,r)=>{"use strict";let a;r.d(t,{Az:()=>d,Ec:()=>h});var i=r(49509);let n=()=>"undefined"!=typeof window&&void 0!==window.document,s=()=>"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name,o=()=>"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")),l=()=>"undefined"!=typeof Deno,u=()=>void 0!==i&&void 0!==i.versions&&void 0!==i.versions.node&&!l(),c=()=>{let e;return n()?"browser":u()?"node":s()?"webworker":o()?"jsdom":l()?"deno":"other"};async function h(){return void 0===a&&(a={library:"langchain-js",runtime:c()}),a}function d(e){try{if(void 0!==i)return i.env?.[e];if(l())return Deno?.env.get(e);return}catch(e){return}}},4693:(e,t,r)=>{"use strict";r.d(t,{YN:()=>Y,B2:()=>eo,fJ:()=>V,jY:()=>ei,ck:()=>et,zZ:()=>ee,GH:()=>J,Bp:()=>es});var a=r(55594),i=r(52813),n=r(79737),s=r(19839),o=r(82591),l=r(25050),u=r(87150),c=r(41039);class h{constructor(e){Object.defineProperty(this,"ops",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),r=(0,o.X6)({},t);return new d({ops:t,state:r[r.length-1].newDocument})}}class d extends h{constructor(e){super(e),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.state=e.state}concat(e){let t=this.ops.concat(e.ops),r=(0,o.X6)(this.state,e.ops);return new d({ops:t,state:r[r.length-1].newDocument})}static fromRunLogPatch(e){let t=(0,o.X6)({},e.ops);return new d({ops:e.ops,state:t[t.length-1].newDocument})}}let p=e=>"log_stream_tracer"===e.name;async function f(e,t){if("original"===t)throw Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");let{inputs:r}=e;return["retriever","llm","prompt"].includes(e.run_type)?r:1!==Object.keys(r).length||r?.input!==""?r.input:void 0}async function m(e,t){let{outputs:r}=e;return"original"===t||["retriever","llm","prompt"].includes(e.run_type)?r:void 0!==r&&1===Object.keys(r).length&&r?.output!==void 0?r.output:r}function g(e){return void 0!==e&&void 0!==e.message}class y extends l.J{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=u.bO.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;let t=e.tags??[],r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.run_type)),void 0!==this.includeTags&&(r=r||void 0!==t.find(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.run_type)),void 0!==this.excludeTags&&(r=r&&t.every(e=>!this.excludeTags?.includes(e))),r}async *tapOutputIterable(e,t){for await(let r of t){if(e!==this.rootId){let t=this.keyMapByRunId[e];t&&await this.writer.write(new h({ops:[{op:"add",path:`/logs/${t}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(void 0===this.rootId&&(this.rootId=e.id,await this.writer.write(new h({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;void 0===this.counterMapByRunName[e.name]&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;let t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=1===t?e.name:`${e.name}:${t}`;let 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};"streaming_events"===this._schemaFormat&&(r.inputs=await f(e,this._schemaFormat)),await this.writer.write(new h({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(void 0===t)return;let r=[];"streaming_events"===this._schemaFormat&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await f(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await m(e,this._schemaFormat)}),void 0!==e.end_time&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let a=new h({ops:r});await this.writer.write(a)}finally{if(e.id===this.rootId){let t=new h({ops:[{op:"replace",path:"/final_output",value:await m(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){let a;let i=this.keyMapByRunId[e.id];if(void 0===i)return;a=void 0!==e.inputs.messages?g(r?.chunk)?r?.chunk:new c.H({id:`run-${e.id}`,content:t}):t;let n=new h({ops:[{op:"add",path:`/logs/${i}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${i}/streamed_output/-`,value:a}]});await this.writer.write(n)}}var b=r(23294);function _({name:e,serialized:t}){return void 0!==e?e:t?.name!==void 0?t.name:t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}let w=e=>"event_stream_tracer"===e.name;class v extends l.J{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=u.bO.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let t=e.tags??[],r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.runType)),void 0!==this.includeTags&&(r=r||void 0!==t.find(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.runType)),void 0!==this.excludeTags&&(r=r&&t.every(e=>!this.excludeTags?.includes(e))),r}async *tapOutputIterable(e,t){let r=await t.next();if(r.done)return;let a=this.runInfoMap.get(e);if(void 0===a){yield r.value;return}function i(e,t){return"llm"===e&&"string"==typeof t?new b.mu({text:t}):t}let n=this.tappedPromises.get(e);if(void 0===n){let s;n=new Promise(e=>{s=e}),this.tappedPromises.set(e,n);try{let n={event:`on_${a.runType}_stream`,run_id:e,name:a.name,tags:a.tags,metadata:a.metadata,data:{}};for await(let e of(await this.send({...n,data:{chunk:i(a.runType,r.value)}},a),yield r.value,t))"tool"!==a.runType&&"retriever"!==a.runType&&await this.send({...n,data:{chunk:i(a.runType,e)}},a),yield e}finally{s()}}else for await(let e of(yield r.value,t))yield e}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){let r=this.tappedPromises.get(e.run_id);void 0!==r?r.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){let t=_(e),r=void 0!==e.inputs.messages?"chat_model":"llm",a={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,a);let i=`on_${r}_start`;await this.send({event:i,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},a)}async onLLMNewToken(e,t,r){let a,i;let n=this.runInfoMap.get(e.id);if(void 0===n)throw Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(1!==this.runInfoMap.size){if("chat_model"===n.runType)i="on_chat_model_stream",a=r?.chunk===void 0?new c.H({content:t,id:`run-${e.id}`}):r.chunk.message;else if("llm"===n.runType)i="on_llm_stream",a=r?.chunk===void 0?new b.mu({text:t}):r.chunk;else throw Error(`Unexpected run type ${n.runType}`);await this.send({event:i,data:{chunk:a},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}}async onLLMEnd(e){let t,r;let a=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===a)throw Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let i=e.outputs?.generations;if("chat_model"===a.runType){for(let e of i??[]){if(void 0!==r)break;r=e[0]?.message}t="on_chat_model_end"}else if("llm"===a.runType)r={generations:i?.map(e=>e.map(e=>({text:e.text,generationInfo:e.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},t="on_llm_end";else throw Error(`onLLMEnd: Unexpected run type: ${a.runType}`);await this.sendEndEvent({event:t,data:{output:r,input:a.inputs},run_id:e.id,name:a.name,tags:a.tags,metadata:a.metadata},a)}async onChainStart(e){let t=_(e),r=e.run_type??"chain",a={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type},i={};""===e.inputs.input&&1===Object.keys(e.inputs).length?(i={},a.inputs={}):void 0!==e.inputs.input?(i.input=e.inputs.input,a.inputs=e.inputs.input):(i.input=e.inputs,a.inputs=e.inputs),this.runInfoMap.set(e.id,a),await this.send({event:`on_${r}_start`,data:i,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},a)}async onChainEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw Error(`onChainEnd: Run ID ${e.id} not found in run map.`);let r=`on_${e.run_type}_end`,a=e.inputs??t.inputs??{},i={output:e.outputs?.output??e.outputs,input:a};a.input&&1===Object.keys(a).length&&(i.input=a.input,t.inputs=a.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){let t=_(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){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(void 0===t.inputs)throw Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);let 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){let t=_(e),r="retriever",a={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,a),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??{}},a)}async onRetrieverEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw 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){let a=this.runInfoMap.get(r);if(void 0===a)throw Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:a.tags,metadata:a.metadata,data:t},a)}async finish(){Promise.all([...this.tappedPromises.values()]).finally(()=>{this.writer.close()})}}var O=r(23931),E=r(67146),k=r(92173),x=r(65408);class S extends l.J{constructor({config:e,onStart:t,onEnd:r,onError:a}){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=a}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 A(e){return!!e&&e.lc_runnable}class P{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=void 0===this.includeNames&&void 0===this.includeTypes&&void 0===this.includeTags,a=e.tags??[];return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(t)),void 0!==this.includeTags&&(r=r||a.some(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(t)),void 0!==this.excludeTags&&(r=r&&a.every(e=>!this.excludeTags?.includes(e))),r}}var T=r(89351),I=r(50084),N=r(18056);function j(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}let R=["*","_","`"];function C(e){let t="";for(let[r,a]of Object.entries(e))t+=` classDef ${r} ${a}; `;return t}function $(e,t,r){let{firstNode:a,lastNode:i,nodeColors:n,withStyles:s=!0,curveStyle:o="linear",wrapLabelNWords:l=9}=r??{},u=s?`%%{init: {'flowchart': {'curve': '${o}'}}}%% graph TD; `:"graph TD;\n";if(s){let t="default",r={[t]:"{0}({1})"};for(let[n,s]of(void 0!==a&&(r[a]="{0}([{1}]):::first"),void 0!==i&&(r[i]="{0}([{1}]):::last"),Object.entries(e))){let e=s.name.split(":").pop()??"",a=R.some(t=>e.startsWith(t)&&e.endsWith(t))?`

${e}

`:e;Object.keys(s.metadata??{}).length&&(a+=`
${Object.entries(s.metadata??{}).map(([e,t])=>`${e} = ${t}`).join("\n")}`);let i=(r[n]??r[t]).replace("{0}",j(n)).replace("{1}",a);u+=` ${i} `}}let c={};for(let e of t){let t=e.source.split(":"),r=e.target.split(":"),a=t.filter((e,t)=>e===r[t]).join(":");c[a]||(c[a]=[]),c[a].push(e)}let h=new Set;function d(e,t){let r=1===e.length&&e[0].source===e[0].target;if(t&&!r){let e=t.split(":").pop();if(h.has(e))throw Error(`Found duplicate subgraph '${e}' -- 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.`);h.add(e),u+=` subgraph ${e} `}for(let t of e){let{source:e,target:r,data:a,conditional:i}=t,n="";if(void 0!==a){let e=a,t=e.split(" ");t.length>l&&(e=Array.from({length:Math.ceil(t.length/l)},(e,r)=>t.slice(r*l,(r+1)*l).join(" ")).join(" 
 ")),n=i?` -.  ${e}  .-> `:` --  ${e}  --> `}else n=i?" -.-> ":" --\x3e ";u+=` ${j(e)}${n}${j(r)}; `}for(let e in c)e.startsWith(`${t}:`)&&e!==t&&d(c[e],e);t&&!r&&(u+=" end\n")}for(let e in d(c[""]??[],""),c)e.includes(":")||""===e||d(c[e],e);return s&&(u+=C(n??{})),u}async function M(e,t){let{backgroundColor:r="white"}=t??{},a=btoa(e);void 0===r||/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`);let i=`https://mermaid.ink/img/${a}?bgColor=${r}`,n=await fetch(i);if(!n.ok)throw Error(`Failed to render the graph using the Mermaid.INK API. Status code: ${n.status} Status text: ${n.statusText}`);return await n.blob()}function L(e,t){if(void 0!==e&&!(0,N.A)(e))return e;if(!A(t))return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e}catch(e){return t.getName()}}function U(e){return A(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...(0,I.Ik)(e.data.schema),title:e.data.name}}}class D{constructor(e){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){let e={};return Object.values(this.nodes).forEach((t,r)=>{e[t.id]=(0,N.A)(t.id)?r:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...U(t)})),edges:this.edges.map(t=>{let r={source:e[t.source],target:e[t.target]};return void 0!==t.data&&(r.data=t.data),void 0!==t.conditional&&(r.conditional=t.conditional),r})}}addNode(e,t,r){if(void 0!==t&&void 0!==this.nodes[t])throw Error(`Node with id ${t} already exists`);let a=t??(0,n.A)(),i={id:a,data:e,name:L(t,e),metadata:r};return this.nodes[a]=i,i}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,a){if(void 0===this.nodes[e.id])throw Error(`Source node ${e.id} not in graph`);if(void 0===this.nodes[t.id])throw Error(`Target node ${t.id} not in graph`);let i={source:e.id,target:t.id,data:r,conditional:a};return this.edges.push(i),i}firstNode(){return F(this)}lastNode(){return B(this)}extend(e,t=""){let r=t;Object.values(e.nodes).map(e=>e.id).every(N.A)&&(r="");let a=e=>r?`${r}:${e}`:e;Object.entries(e.nodes).forEach(([e,t])=>{this.nodes[a(e)]={...t,id:a(e)}});let i=e.edges.map(e=>({...e,source:a(e.source),target:a(e.target)}));this.edges=[...this.edges,...i];let n=e.firstNode(),s=e.lastNode();return[n?{id:a(n.id),data:n.data}:void 0,s?{id:a(s.id),data:s.data}:void 0]}trimFirstNode(){let e=this.firstNode();e&&F(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&B(this,[e.id])&&this.removeNode(e)}reid(){let e=Object.fromEntries(Object.values(this.nodes).map(e=>[e.id,e.name])),t=new Map;Object.values(e).forEach(e=>{t.set(e,(t.get(e)||0)+1)});let r=r=>{let a=e[r];return(0,N.A)(r)&&1===t.get(a)?a:r};return new D({nodes:Object.fromEntries(Object.entries(this.nodes).map(([e,t])=>[r(e),{...t,id:r(e)}])),edges:this.edges.map(e=>({...e,source:r(e.source),target:r(e.target)}))})}drawMermaid(e){let{withStyles:t,curveStyle:r,nodeColors:a={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:i}=e??{},n=this.reid(),s=n.firstNode(),o=n.lastNode();return $(n.nodes,n.edges,{firstNode:s?.id,lastNode:o?.id,withStyles:t,curveStyle:r,nodeColors:a,wrapLabelNWords:i})}async drawMermaidPng(e){return M(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}}function F(e,t=[]){let r=new Set(e.edges.filter(e=>!t.includes(e.source)).map(e=>e.target)),a=[];for(let i of Object.values(e.nodes))t.includes(i.id)||r.has(i.id)||a.push(i);return 1===a.length?a[0]:void 0}function B(e,t=[]){let r=new Set(e.edges.filter(e=>!t.includes(e.target)).map(e=>e.source)),a=[];for(let i of Object.values(e.nodes))t.includes(i.id)||r.has(i.id)||a.push(i);return 1===a.length?a[0]:void 0}function z(e){let t=new TextEncoder,r=new ReadableStream({async start(r){for await(let a of e)r.enqueue(t.encode(`event: data data: ${JSON.stringify(a)} `));r.enqueue(t.encode("event: end\n\n")),r.close()}});return u.bO.fromReadableStream(r)}function H(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.iterator]&&"function"==typeof e.next}let Z=e=>null!=e&&"object"==typeof e&&"next"in e&&"function"==typeof e.next;function q(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.asyncIterator]}function*G(e,t){for(;;){let{value:r,done:a}=T.Nx.runWithConfig((0,k.DY)(e),t.next.bind(t),!0);if(a)break;yield r}}async function*W(e,t){let r=t[Symbol.asyncIterator]();for(;;){let{value:a,done:i}=await T.Nx.runWithConfig((0,k.DY)(e),r.next.bind(t),!0);if(i)break;yield a}}var K=r(28809);function J(e,t){return!e||Array.isArray(e)||e instanceof Date||"object"!=typeof e?{[t]:e}:e}class Y extends O.y{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(e){let t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}bind(e){return new V({bound:this,kwargs:e,config:{}})}map(){return new X({bound:this})}withRetry(e){return new Q({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new V({bound:this,config:e,kwargs:{}})}withFallbacks(e){return new en({runnable:this,fallbacks:Array.isArray(e)?e:e.fallbacks})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw 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(k.ZI);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");let r=Object.fromEntries(Object.entries(e).filter(([e])=>"runId"!==e));return Array.from({length:t},(t,a)=>(0,k.ZI)(0===a?e:r))}return Array.from({length:t},()=>(0,k.ZI)(e))}async batch(e,t,r){let a=this._getOptionsList(t??{},e.length),i=a[0]?.maxConcurrency??r?.maxConcurrency,n=new x.g({maxConcurrency:i,onFailedAttempt:e=>{throw e}});return Promise.all(e.map((e,t)=>n.call(async()=>{try{return await this.invoke(e,a[t])}catch(e){if(r?.returnExceptions)return e;throw e}})))}async *_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){let r=(0,k.ZI)(t),a=new u.Tr({generator:this._streamIterator(e,r),config:r});return await a.setup,u.bO.fromAsyncGenerator(a)}_separateRunnableConfigFromCallOptions(e){let t;t=void 0===e?(0,k.ZI)(e):(0,k.ZI)({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});let 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){let a;let i=(0,k.ZI)(r),n=await (0,k.kJ)(i),s=await n?.handleChainStart(this.toJSON(),J(t,"input"),i.runId,i?.runType,void 0,void 0,i?.runName??this.getName());delete i.runId;try{let n=e.call(this,t,i,s);a=await (0,E.o)(n,r?.signal)}catch(e){throw await s?.handleChainError(e),e}return await s?.handleChainEnd(J(a,"output")),a}async _batchWithConfig(e,t,r,a){let i;let n=this._getOptionsList(r??{},t.length),s=await Promise.all(n.map(k.kJ)),o=await Promise.all(s.map(async(e,r)=>{let a=await e?.handleChainStart(this.toJSON(),J(t[r],"input"),n[r].runId,n[r].runType,void 0,void 0,n[r].runName??this.getName());return delete n[r].runId,a}));try{let r=e.call(this,t,n,o,a);i=await (0,E.o)(r,n?.[0]?.signal)}catch(e){throw await Promise.all(o.map(t=>t?.handleChainError(e))),e}return await Promise.all(o.map(e=>e?.handleChainEnd(J(i,"output")))),i}async *_transformStreamWithConfig(e,t,r){let a,i,n;let s=!0,o=!0,l=(0,k.ZI)(r),c=await (0,k.kJ)(l);async function*h(){for await(let t of e){if(s){if(void 0===a)a=t;else try{a=(0,u.xW)(a,t)}catch{a=void 0,s=!1}}yield t}}try{let e=await (0,u.DS)(t.bind(this),h(),async()=>c?.handleChainStart(this.toJSON(),{input:""},l.runId,l.runType,void 0,void 0,l.runName??this.getName()),r?.signal,l);delete l.runId,n=e.setup;let a=n?.handlers.find(w),s=e.output;void 0!==a&&void 0!==n&&(s=a.tapOutputIterable(n.runId,s));let d=n?.handlers.find(p);for await(let e of(void 0!==d&&void 0!==n&&(s=d.tapOutputIterable(n.runId,s)),s))if(yield e,o){if(void 0===i)i=e;else try{i=(0,u.xW)(i,e)}catch{i=void 0,o=!1}}}catch(e){throw await n?.handleChainError(e,void 0,void 0,void 0,{inputs:J(a,"input")}),e}await n?.handleChainEnd(i??{},void 0,void 0,void 0,{inputs:J(a,"input")})}getGraph(e){let t=new D,r=t.addNode({name:`${this.getName()}Input`,schema:a.z.any()}),i=t.addNode(this),n=t.addNode({name:`${this.getName()}Output`,schema:a.z.any()});return t.addEdge(r,i),t.addEdge(i,n),t}pipe(e){return new ee({first:this,last:es(e)})}pick(e){return this.pipe(new el(e))}assign(e){return this.pipe(new eo(new et({steps:e})))}async *transform(e,t){let r;for await(let t of e)r=void 0===r?t:(0,u.xW)(r,t);yield*this._streamIterator(r,(0,k.ZI)(t))}async *streamLog(e,t,r){let a=new y({...r,autoClose:!1,_schemaFormat:"original"}),i=(0,k.ZI)(t);yield*this._streamLog(e,a,i)}async *_streamLog(e,t,r){let{callbacks:a}=r;if(void 0===a)r.callbacks=[t];else if(Array.isArray(a))r.callbacks=a.concat([t]);else{let e=a.copy();e.addHandler(t,!0),r.callbacks=e}let i=this.stream(e,r),n=async function(){try{for await(let e of(await i)){let r=new h({ops:[{op:"add",path:"/streamed_output/-",value:e}]});await t.writer.write(r)}}finally{await t.writer.close()}}();try{for await(let e of t)yield e}finally{await n}}streamEvents(e,t,r){let a;if("v1"===t.version)a=this._streamEventsV1(e,t,r);else if("v2"===t.version)a=this._streamEventsV2(e,t,r);else throw Error('Only versions "v1" and "v2" of the schema are currently supported.');return"text/event-stream"===t.encoding?z(a):u.bO.fromAsyncGenerator(a)}async *_streamEventsV2(e,t,r){let a;let i=new v({...r,autoClose:!1}),s=(0,k.ZI)(t),o=s.runId??(0,n.A)();s.runId=o;let l=s.callbacks;if(void 0===l)s.callbacks=[i];else if(Array.isArray(l))s.callbacks=l.concat(i);else{let e=l.copy();e.addHandler(i,!0),s.callbacks=e}let u=new AbortController,c=this,h=async function(){try{let r;t?.signal?"any"in AbortSignal?r=AbortSignal.any([u.signal,t.signal]):(r=t.signal,t.signal.addEventListener("abort",()=>{u.abort()},{once:!0})):r=u.signal;let a=await c.stream(e,{...s,signal:r});for await(let e of i.tapOutputIterable(o,a))if(u.signal.aborted)break}finally{await i.finish()}}(),d=!1;try{for await(let t of i){if(!d){t.data.input=e,d=!0,a=t.run_id,yield t;continue}t.run_id===a&&t.event.endsWith("_end")&&t.data?.input&&delete t.data.input,yield t}}finally{u.abort(),await h}}async *_streamEventsV1(e,t,r){let a;let i=!1,n=(0,k.ZI)(t),s=n.tags??[],o=n.metadata??{},l=n.runName??this.getName(),u=new y({...r,autoClose:!1,_schemaFormat:"streaming_events"}),c=new P({...r});for await(let t of this._streamLog(e,u,n)){if(void 0===(a=a?a.concat(t):d.fromRunLogPatch(t)).state)throw Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!i){i=!0;let t={...a.state},r={run_id:t.id,event:`on_${t.type}_start`,name:l,tags:s,metadata:o,data:{input:e}};c.includeEvent(r,t.type)&&(yield r)}for(let e of[...new Set(t.ops.filter(e=>e.path.startsWith("/logs/")).map(e=>e.path.split("/")[2]))]){let t;let r={},i=a.state.logs[e];if("start"==(t=void 0===i.end_time?i.streamed_output.length>0?"stream":"start":"end"))void 0!==i.inputs&&(r.input=i.inputs);else if("end"===t)void 0!==i.inputs&&(r.input=i.inputs),r.output=i.final_output;else if("stream"===t){let e=i.streamed_output.length;if(1!==e)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${i.name}"`);r={chunk:i.streamed_output[0]},i.streamed_output=[]}yield{event:`on_${i.type}_${t}`,name:i.name,run_id:i.id,tags:i.tags,metadata:i.metadata,data:r}}let{state:r}=a;if(r.streamed_output.length>0){let e=r.streamed_output.length;if(1!==e)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${r.name}"`);let t={chunk:r.streamed_output[0]};r.streamed_output=[];let a={event:`on_${r.type}_stream`,run_id:r.id,tags:s,metadata:o,name:l,data:t};c.includeEvent(a,r.type)&&(yield a)}}let h=a?.state;if(void 0!==h){let e={event:`on_${h.type}_end`,name:l,run_id:h.id,tags:s,metadata:o,data:{output:h.final_output}};c.includeEvent(e,h.type)&&(yield e)}}static isRunnable(e){return A(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new V({bound:this,config:{},configFactories:[a=>({callbacks:[new S({config:a,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return ec(this,e)}}class V extends Y{static lc_name(){return"RunnableBinding"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"configFactories",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){let t=(0,k.SV)(this.config,...e);return(0,k.SV)(t,...this.configFactories?await Promise.all(this.configFactories.map(async e=>await e(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 this.constructor({bound:this.bound.withRetry(e),kwargs:this.kwargs,config:this.config})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig((0,k.ZI)(t),this.kwargs))}async batch(e,t,r){let a=Array.isArray(t)?await Promise.all(t.map(async e=>this._mergeConfig((0,k.ZI)(e),this.kwargs))):await this._mergeConfig((0,k.ZI)(t),this.kwargs);return this.bound.batch(e,a,r)}async *_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig((0,k.ZI)(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig((0,k.ZI)(t),this.kwargs))}async *transform(e,t){yield*this.bound.transform(e,await this._mergeConfig((0,k.ZI)(t),this.kwargs))}streamEvents(e,t,r){let a=this,i=async function*(){yield*a.bound.streamEvents(e,{...await a._mergeConfig((0,k.ZI)(t),a.kwargs),version:t.version},r)};return u.bO.fromAsyncGenerator(i())}static isRunnableBinding(e){return e.bound&&Y.isRunnable(e.bound)}withListeners({onStart:e,onEnd:t,onError:r}){return new V({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[a=>({callbacks:[new S({config:a,onStart:e,onEnd:t,onError:r})]})]})}}class X extends Y{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 X({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,(0,k.tn)(t,{callbacks:r?.getChild()}))}withListeners({onStart:e,onEnd:t,onError:r}){return new X({bound:this.bound.withListeners({onStart:e,onEnd:t,onError:r})})}}class Q extends V{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){let a=e>1?`retry:attempt:${e}`:void 0;return(0,k.tn)(t,{callbacks:r?.getChild(a)})}async _invoke(e,t,r){return i(a=>super.invoke(e,this._patchConfigForRetry(a,t,r)),{onFailedAttempt:t=>this.onFailedAttempt(t,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,a){let n={};try{await i(async i=>{let s;let o=e.map((e,t)=>t).filter(e=>void 0===n[e.toString()]||n[e.toString()]instanceof Error),l=o.map(t=>e[t]),u=o.map(e=>this._patchConfigForRetry(i,t?.[e],r?.[e])),c=await super.batch(l,u,{...a,returnExceptions:!0});for(let e=0;ethis.onFailedAttempt(e,e.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(e){if(a?.returnExceptions!==!0)throw e}return Object.keys(n).sort((e,t)=>parseInt(e,10)-parseInt(t,10)).map(e=>n[parseInt(e,10)])}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}}class ee extends Y{static lc_name(){return"RunnableSequence"}constructor(e){super(e),Object.defineProperty(this,"first",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"middle",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"last",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitSequenceTags",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){let r;let a=(0,k.ZI)(t),i=await (0,k.kJ)(a),n=await i?.handleChainStart(this.toJSON(),J(e,"input"),a.runId,void 0,void 0,void 0,a?.runName);delete a.runId;let s=e;try{let e=[this.first,...this.middle];for(let r=0;r{let i=await t?.handleChainStart(this.toJSON(),J(e[r],"input"),a[r].runId,void 0,void 0,void 0,a[r].runName);return delete a[r].runId,i})),s=e;try{for(let e=0;e{let i=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return(0,k.tn)(a[r],{callbacks:i})}),r);s=await (0,E.o)(t,a[0]?.signal)}}catch(e){throw await Promise.all(n.map(t=>t?.handleChainError(e))),e}return await Promise.all(n.map(e=>e?.handleChainEnd(J(s,"output")))),s}async *_streamIterator(e,t){let r;let a=await (0,k.kJ)(t),{runId:i,...n}=t??{},s=await a?.handleChainStart(this.toJSON(),J(e,"input"),i,void 0,void 0,void 0,n?.runName),o=[this.first,...this.middle,this.last],l=!0;async function*c(){yield e}try{let e=o[0].transform(c(),(0,k.tn)(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let t=1;t{let n=a.getGraph(e);0!==i&&n.trimFirstNode(),i!==this.steps.length-1&&n.trimLastNode(),t.extend(n);let s=n.firstNode();if(!s)throw Error(`Runnable ${a} has no first node`);r&&t.addEdge(r,s),r=n.lastNode()}),t}pipe(e){return new ee(ee.isRunnableSequence(e)?{first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}:{first:this.first,middle:[...this.middle,this.last],last:es(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&Y.isRunnable(e)}static from([e,...t],r){let a={};return"string"==typeof r?a.name=r:void 0!==r&&(a=r),new ee({...a,first:es(e),middle:t.slice(0,-1).map(es),last:es(t[t.length-1])})}}class et extends Y{static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}constructor(e){for(let[t,r]of(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={},Object.entries(e.steps)))this.steps[t]=es(r)}static from(e){return new et({steps:e})}async invoke(e,t){let r=(0,k.ZI)(t),a=await (0,k.kJ)(r),i=await a?.handleChainStart(this.toJSON(),{input:e},r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;let n={};try{let a=Object.entries(this.steps).map(async([t,a])=>{n[t]=await a.invoke(e,(0,k.tn)(r,{callbacks:i?.getChild(`map:key:${t}`)}))});await (0,E.o)(Promise.all(a),t?.signal)}catch(e){throw await i?.handleChainError(e),e}return await i?.handleChainEnd(n),n}async *_transform(e,t,r){let a={...this.steps},i=(0,u.gI)(e,Object.keys(a).length),n=new Map(Object.entries(a).map(([e,a],n)=>{let s=a.transform(i[n],(0,k.tn)(r,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,s.next().then(t=>({key:e,gen:s,result:t}))]}));for(;n.size;){let e=Promise.race(n.values()),{key:t,result:a,gen:i}=await (0,E.o)(e,r?.signal);n.delete(t),a.done||(yield{[t]:a.value},n.set(t,i.next().then(e=>({key:t,gen:i,result:e}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let a=(0,k.ZI)(t),i=new u.Tr({generator:this.transform(r(),a),config:a});return await i.setup,u.bO.fromAsyncGenerator(i)}}class er extends Y{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}),!(0,s.GZ)(e.func))throw Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,t){let[r]=this._getOptionsList(t??{},1),a=await (0,k.kJ)(r),i=this.func((0,k.tn)(r,{callbacks:a}),e);return(0,E.o)(i,r?.signal)}async *_streamIterator(e,t){let[r]=this._getOptionsList(t??{},1),a=await this.invoke(e,t);if(q(a)){for await(let e of a)r?.signal?.throwIfAborted(),yield e;return}if(Z(a)){for(;;){r?.signal?.throwIfAborted();let e=a.next();if(e.done)break;yield e.value}return}yield a}static from(e){return new er({func:e})}}function ea(e){if((0,s.GZ)(e))throw Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}class ei extends Y{static lc_name(){return"RunnableLambda"}constructor(e){if((0,s.GZ)(e.func))return er.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}),ea(e.func),this.func=e.func}static from(e){return new ei({func:e})}async _invoke(e,t,r){return new Promise((a,i)=>{let n=(0,k.tn)(t,{callbacks:r?.getChild(),recursionLimit:(t?.recursionLimit??k.p_)-1});T.Nx.runWithConfig((0,k.DY)(n),async()=>{try{let r=await this.func(e,{...n});if(r&&Y.isRunnable(r)){if(t?.recursionLimit===0)throw Error("Recursion limit reached.");r=await r.invoke(e,{...n,recursionLimit:(n.recursionLimit??k.p_)-1})}else if(q(r)){let e;for await(let a of W(n,r))if(t?.signal?.throwIfAborted(),void 0===e)e=a;else try{e=(0,u.xW)(e,a)}catch(t){e=a}r=e}else if(H(r)){let e;for(let a of G(n,r))if(t?.signal?.throwIfAborted(),void 0===e)e=a;else try{e=(0,u.xW)(e,a)}catch(t){e=a}r=e}a(r)}catch(e){i(e)}})})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async *_transform(e,t,r){let a;for await(let t of e)if(void 0===a)a=t;else try{a=(0,u.xW)(a,t)}catch(e){a=t}let i=(0,k.tn)(r,{callbacks:t?.getChild(),recursionLimit:(r?.recursionLimit??k.p_)-1}),n=await new Promise((e,t)=>{T.Nx.runWithConfig((0,k.DY)(i),async()=>{try{let t=await this.func(a,{...i,config:i});e(t)}catch(e){t(e)}})});if(n&&Y.isRunnable(n)){if(r?.recursionLimit===0)throw Error("Recursion limit reached.");for await(let e of(await n.stream(a,i)))yield e}else if(q(n))for await(let e of W(i,n))r?.signal?.throwIfAborted(),yield e;else if(H(n))for(let e of G(i,n))r?.signal?.throwIfAborted(),yield e;else yield n}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let a=(0,k.ZI)(t),i=new u.Tr({generator:this.transform(r(),a),config:a});return await i.setup,u.bO.fromAsyncGenerator(i)}}class en extends Y{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(){for(let e of(yield this.runnable,this.fallbacks))yield e}async invoke(e,t){let r=(0,k.ZI)(t),a=await (0,k.kJ)(r),{runId:i,...n}=r,s=await a?.handleChainStart(this.toJSON(),J(e,"input"),i,void 0,void 0,void 0,n?.runName),o=(0,k.tn)(n,{callbacks:s?.getChild()});return await T.Nx.runWithConfig(o,async()=>{let t;for(let a of this.runnables()){r?.signal?.throwIfAborted();try{let t=await a.invoke(e,o);return await s?.handleChainEnd(J(t,"output")),t}catch(e){void 0===t&&(t=e)}}if(void 0===t)throw Error("No error stored at end of fallback.");throw await s?.handleChainError(t),t})}async *_streamIterator(e,t){let r,a,i;let n=(0,k.ZI)(t),s=await (0,k.kJ)(n),{runId:o,...l}=n,c=await s?.handleChainStart(this.toJSON(),J(e,"input"),o,void 0,void 0,void 0,l?.runName);for(let t of this.runnables()){n?.signal?.throwIfAborted();let i=(0,k.tn)(l,{callbacks:c?.getChild()});try{let r=await t.stream(e,i);a=W(i,r);break}catch(e){void 0===r&&(r=e)}}if(void 0===a){let e=r??Error("No error stored at end of fallback.");throw await c?.handleChainError(e),e}try{for await(let e of a){yield e;try{i=void 0===i?i:(0,u.xW)(i,e)}catch(e){i=void 0}}}catch(e){throw await c?.handleChainError(e),e}await c?.handleChainEnd(J(i,"output"))}async batch(e,t,r){let a;if(r?.returnExceptions)throw Error("Not implemented.");let i=this._getOptionsList(t??{},e.length),n=await Promise.all(i.map(e=>(0,k.kJ)(e))),s=await Promise.all(n.map(async(t,r)=>{let a=await t?.handleChainStart(this.toJSON(),J(e[r],"input"),i[r].runId,void 0,void 0,void 0,i[r].runName);return delete i[r].runId,a}));for(let t of this.runnables()){i[0].signal?.throwIfAborted();try{let a=await t.batch(e,s.map((e,t)=>(0,k.tn)(i[t],{callbacks:e?.getChild()})),r);return await Promise.all(s.map((e,t)=>e?.handleChainEnd(J(a[t],"output")))),a}catch(e){void 0===a&&(a=e)}}if(!a)throw Error("No error stored at end of fallbacks.");throw await Promise.all(s.map(e=>e?.handleChainError(a))),a}}function es(e){if("function"==typeof e)return new ei({func:e});if(Y.isRunnable(e))return e;if(Array.isArray(e)||"object"!=typeof e)throw Error(`Expected a Runnable, function or object. Instead got an unsupported type.`);{let t={};for(let[r,a]of Object.entries(e))t[r]=es(a);return new et({steps:t})}}class eo extends Y{static lc_name(){return"RunnableAssign"}constructor(e){e instanceof et&&(e={mapper:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mapper=e.mapper}async invoke(e,t){let r=await this.mapper.invoke(e,t);return{...e,...r}}async *_transform(e,t,r){let a=this.mapper.getStepsKeys(),[i,n]=(0,u.gI)(e),s=this.mapper.transform(n,(0,k.tn)(r,{callbacks:t?.getChild()})),o=s.next();for await(let e of i){if("object"!=typeof e||Array.isArray(e))throw Error(`RunnableAssign can only be used with objects as input, got ${typeof e}`);let t=Object.fromEntries(Object.entries(e).filter(([e])=>!a.includes(e)));Object.keys(t).length>0&&(yield t)}for await(let e of(yield(await o).value,s))yield e}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let a=(0,k.ZI)(t),i=new u.Tr({generator:this.transform(r(),a),config:a});return await i.setup,u.bO.fromAsyncGenerator(i)}}class el extends Y{static lc_name(){return"RunnablePick"}constructor(e){("string"==typeof e||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("string"==typeof this.keys)return e[this.keys];{let t=this.keys.map(t=>[t,e[t]]).filter(e=>void 0!==e[1]);return 0===t.length?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async *_transform(e){for await(let t of e){let e=await this._pick(t);void 0!==e&&(yield e)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let a=(0,k.ZI)(t),i=new u.Tr({generator:this.transform(r(),a),config:a});return await i.setup,u.bO.fromAsyncGenerator(i)}}class eu extends V{constructor(e){super({bound:ee.from([ei.from(async e=>{let t;if((0,K.K)(e))try{t=await this.schema.parseAsync(e.args)}catch(t){throw new K.q("Received tool input did not match expected schema",JSON.stringify(e.args))}else t=e;return t}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name}),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 ec(e,t){let r=t.name??e.getName(),i=t.description??t.schema?.description;return new eu(t.schema.constructor===a.z.ZodString?{name:r,description:i,schema:a.z.object({input:a.z.string()}).transform(e=>e.input),bound:e}:{name:r,description:i,schema:t.schema,bound:e})}},4837:(e,t,r)=>{"use strict";r.d(t,{Z:()=>i});var a=r(72257);class i extends a.J{constructor(e){super({maxConcurrency:1,...e}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"llama2"}),Object.defineProperty(this,"baseUrl",{enumerable:!0,configurable:!0,writable:!0,value:"http://localhost:11434"}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keepAlive",{enumerable:!0,configurable:!0,writable:!0,value:"5m"}),Object.defineProperty(this,"requestOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e?.model&&(this.model=e.model),e?.baseUrl&&(this.baseUrl=e.baseUrl),e?.headers&&(this.headers=e.headers),e?.keepAlive&&(this.keepAlive=e.keepAlive),e?.requestOptions&&(this.requestOptions=this._convertOptions(e.requestOptions))}_convertOptions(e){let t={},r={embeddingOnly:"embedding_only",f16KV:"f16_kv",frequencyPenalty:"frequency_penalty",keepAlive:"keep_alive",logitsAll:"logits_all",lowVram:"low_vram",mainGpu:"main_gpu",mirostat:"mirostat",mirostatEta:"mirostat_eta",mirostatTau:"mirostat_tau",numBatch:"num_batch",numCtx:"num_ctx",numGpu:"num_gpu",numGqa:"num_gqa",numKeep:"num_keep",numPredict:"num_predict",numThread:"num_thread",penalizeNewline:"penalize_newline",presencePenalty:"presence_penalty",repeatLastN:"repeat_last_n",repeatPenalty:"repeat_penalty",ropeFrequencyBase:"rope_frequency_base",ropeFrequencyScale:"rope_frequency_scale",temperature:"temperature",stop:"stop",tfsZ:"tfs_z",topK:"top_k",topP:"top_p",typicalP:"typical_p",useMLock:"use_mlock",useMMap:"use_mmap",vocabOnly:"vocab_only"};for(let[a,i]of Object.entries(e)){let e=r[a];e?t[e]=i:t[a]=i}return t}async _request(e){let{model:t,baseUrl:r,keepAlive:a,requestOptions:i}=this,n=r;n.startsWith("http://localhost:")&&(n=n.replace("http://localhost:","http://127.0.0.1:"));let s=await fetch(`${n}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify({prompt:e,model:t,keep_alive:a,options:i})});if(!s.ok)throw Error(`Request to Ollama server failed: ${s.status} ${s.statusText}`);return(await s.json()).embedding}async _embed(e){return await Promise.all(e.map(e=>this.caller.call(()=>this._request(e))))}async embedDocuments(e){return this._embed(e)}async embedQuery(e){return(await this.embedDocuments([e]))[0]}}},5415:(e,t,r)=>{"use strict";r.d(t,{H:()=>a.H,KX:()=>a.KX,Od:()=>a.Od,cM:()=>a.cM,ny:()=>a.ny,xc:()=>a.xc});var a=r(71150)},5890:e=>{"use strict";e.exports=e=>{let t=new Date(e);if(!isNaN(t))return t;throw TypeError("Invalid Datetime")}},6695:(e,t,r)=>{"use strict";let a,i,n,s,o,l,u,c,h,d,p,f,m,g,y,b,_;r.d(t,{Db:()=>sG,LD:()=>sV});var w,v,O,E,k,x,S,A,P,T,I,N,j,R,C,$,M,L,U,D,F,B,z,H,Z,q,G,W,K,J,Y,V,X,Q,ee,et,er,ea,ei,en,es,eo,el,eu,ec,eh,ed,ep,ef,em,eg,ey,eb,e_,ew,ev,eO,eE,ek,ex,eS,eA,eP={};r.r(eP),r.d(eP,{xX:()=>ez,qA:()=>eH,LG:()=>eF,cH:()=>eB,v3:()=>eq,v7:()=>eZ,fK:()=>eK,PO:()=>eV,m_:()=>eW,vc:()=>eD,Ll:()=>eG,OE:()=>eY,Is:()=>eJ});var eT={};r.r(eT),r.d(eT,{JsonPatchError:()=>nf,_areEquals:()=>nk,applyOperation:()=>n_,applyPatch:()=>nw,applyReducer:()=>nv,deepClone:()=>nm,getValueByPointer:()=>nb,validate:()=>nE,validator:()=>nO});let eI="4.33.0",eN=!1,ej=null,eR=null,eC=null,e$=null;function eM(e,t={auto:!1}){if(eN)throw Error(`you must \`import 'openai/shims/${e.kind}'\` before importing anything else from openai`);if(h)throw Error(`can't \`import 'openai/shims/${e.kind}'\` after \`import 'openai/shims/${h}'\``);eN=t.auto,h=e.kind,d=e.fetch,ej=e.Request,eR=e.Response,eC=e.Headers,p=e.FormData,e$=e.Blob,f=e.File,m=e.ReadableStream,g=e.getMultipartRequestOptions,y=e.getDefaultAgent,b=e.fileFromPath,_=e.isFsReadStream}class eL{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}function eU({manuallyImported:e}={}){let t,r,a,i;let n=e?"You may need to use polyfills":`Add one of these imports before your first \`import … from 'openai'\`: - \`import 'openai/shims/node'\` (if you're running on Node) - \`import 'openai/shims/web'\` (otherwise) `;try{t=fetch,r=Request,a=Response,i=Headers}catch(e){throw Error(`this environment is missing the following Web Fetch API type: ${e.message}. ${n}`)}return{kind:"web",fetch:t,Request:r,Response:a,Headers:i,FormData:"undefined"!=typeof FormData?FormData:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${n}`)}},Blob:"undefined"!=typeof Blob?Blob:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${n}`)}},File:"undefined"!=typeof File?File:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${n}`)}},ReadableStream:"undefined"!=typeof ReadableStream?ReadableStream:class{constructor(){throw Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${n}`)}},getMultipartRequestOptions:async(e,t)=>({...t,body:new eL(e)}),getDefaultAgent:e=>void 0,fileFromPath:()=>{throw Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:e=>!1}}h||eM(eU(),{auto:!0});class eD extends Error{}class eF extends eD{constructor(e,t,r,a){super(`${eF.makeMessage(e,t,r)}`),this.status=e,this.headers=a;let i=t;this.error=i,this.code=i?.code,this.param=i?.param,this.type=i?.type}static makeMessage(e,t,r){let a=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&a?`${e} ${a}`:e?`${e} status code (no body)`:a||"(no status code or body)"}static generate(e,t,r,a){if(!e)return new ez({cause:t$(t)});let i=t?.error;return 400===e?new eZ(e,i,r,a):401===e?new eq(e,i,r,a):403===e?new eG(e,i,r,a):404===e?new eW(e,i,r,a):409===e?new eK(e,i,r,a):422===e?new eJ(e,i,r,a):429===e?new eY(e,i,r,a):e>=500?new eV(e,i,r,a):new eF(e,i,r,a)}}class eB extends eF{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0),this.status=void 0}}class ez extends eF{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),this.status=void 0,t&&(this.cause=t)}}class eH extends ez{constructor({message:e}={}){super({message:e??"Request timed out."})}}class eZ extends eF{constructor(){super(...arguments),this.status=400}}class eq extends eF{constructor(){super(...arguments),this.status=401}}class eG extends eF{constructor(){super(...arguments),this.status=403}}class eW extends eF{constructor(){super(...arguments),this.status=404}}class eK extends eF{constructor(){super(...arguments),this.status=409}}class eJ extends eF{constructor(){super(...arguments),this.status=422}}class eY extends eF{constructor(){super(...arguments),this.status=429}}class eV extends eF{}var eX=r(44134).Buffer;class eQ{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let r=!1;return new eQ(async function*(){if(r)throw Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let a=!1;try{for await(let r of e0(e,t))if(!a){if(r.data.startsWith("[DONE]")){a=!0;continue}if(null===r.event){let e;try{e=JSON.parse(r.data)}catch(e){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),e}if(e&&e.error)throw new eF(void 0,e.error,void 0,void 0);yield e}else{let e;try{e=JSON.parse(r.data)}catch(e){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),e}if("error"==r.event)throw new eF(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}a=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{a||t.abort()}},t)}static fromReadableStream(e,t){let r=!1;async function*a(){let t=new e5;for await(let r of e3(e))for(let e of t.decode(r))yield e;for(let e of t.flush())yield e}return new eQ(async function*(){if(r)throw Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let e=!1;try{for await(let t of a())!e&&t&&(yield JSON.parse(t));e=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{e||t.abort()}},t)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),a=a=>({next:()=>{if(0===a.length){let a=r.next();e.push(a),t.push(a)}return a.shift()}});return[new eQ(()=>a(e),this.controller),new eQ(()=>a(t),this.controller)]}toReadableStream(){let e;let t=this,r=new TextEncoder;return new m({async start(){e=t[Symbol.asyncIterator]()},async pull(t){try{let{value:a,done:i}=await e.next();if(i)return t.close();let n=r.encode(JSON.stringify(a)+"\n");t.enqueue(n)}catch(e){t.error(e)}},async cancel(){await e.return?.()}})}}async function*e0(e,t){if(!e.body)throw t.abort(),new eD("Attempted to iterate over a response with no body");let r=new e4,a=new e5;for await(let t of e1(e3(e.body)))for(let e of a.decode(t)){let t=r.decode(e);t&&(yield t)}for(let e of a.flush()){let t=r.decode(e);t&&(yield t)}}async function*e1(e){let t=new Uint8Array;for await(let r of e){let e;if(null==r)continue;let a=r instanceof ArrayBuffer?new Uint8Array(r):"string"==typeof r?new TextEncoder().encode(r):r,i=new Uint8Array(t.length+a.length);for(i.set(t),i.set(a,t.length),t=i;-1!==(e=e2(t));)yield t.slice(0,e),t=t.slice(e)}t.length>0&&(yield t)}function e2(e){let t=10,r=13;for(let a=0;a0&&(a=[this.buffer.join("")+a[0],...a.slice(1)],this.buffer=[]),r||(this.buffer=[a.pop()||""]),a):(this.buffer.push(a[0]),[])}decodeText(e){if(null==e)return"";if("string"==typeof e)return e;if(void 0!==eX){if(e instanceof eX)return e.toString();if(e instanceof Uint8Array)return eX.from(e).toString();throw new eD(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new eD(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new eD("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}}function e9(e,t){let r=e.indexOf(t);return -1!==r?[e.substring(0,r),t,e.substring(r+t.length)]:[e,"",""]}function e3(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}e5.NEWLINE_CHARS=new Set(["\n","\r"]),e5.NEWLINE_REGEXP=/\r\n|[\n\r]/g;var e6=r(44134).Buffer;let e8=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,e7=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&te(e),te=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer,tt=e=>e7(e)||e8(e)||_(e);async function tr(e,t,r){if(e=await e,r??(r=e7(e)?{lastModified:e.lastModified,type:e.type}:{}),e8(e)){let a=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file"),new f([a],t,r)}let a=await ta(e);if(t||(t=tn(e)??"unknown_file"),!r.type){let e=a[0]?.type;"string"==typeof e&&(r={...r,type:e})}return new f(a,t,r)}async function ta(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(te(e))t.push(await e.arrayBuffer());else if(to(e))for await(let r of e)t.push(r);else throw Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${ti(e)}`);return t}function ti(e){let t=Object.getOwnPropertyNames(e);return`[${t.map(e=>`"${e}"`).join(", ")}]`}function tn(e){return ts(e.name)||ts(e.filename)||ts(e.path)?.split(/[\\/]/).pop()}let ts=e=>"string"==typeof e?e:void 0!==e6&&e instanceof e6?String(e):void 0,to=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],tl=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag],tu=async e=>{let t=await tc(e.body);return g(t,e)},tc=async e=>{let t=new p;return await Promise.all(Object.entries(e||{}).map(([e,r])=>td(t,e,r))),t},th=e=>{if(tt(e))return!0;if(Array.isArray(e))return e.some(th);if(e&&"object"==typeof e){for(let t in e)if(th(e[t]))return!0}return!1},td=async(e,t,r)=>{if(void 0!==r){if(null==r)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof r||"number"==typeof r||"boolean"==typeof r)e.append(t,String(r));else if(tt(r)){let a=await tr(r);e.append(t,a)}else if(Array.isArray(r))await Promise.all(r.map(r=>td(e,t+"[]",r)));else if("object"==typeof r)await Promise.all(Object.entries(r).map(([r,a])=>td(e,`${t}[${r}]`,a)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var tp=r(44134).Buffer,tf=r(49509),tm=function(e,t,r,a,i){if("m"===a)throw TypeError("Private method is not writable");if("a"===a&&!i)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===a?i.call(e,r):i?i.value=r:t.set(e,r),r},tg=function(e,t,r,a){if("a"===r&&!a)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!a:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?a:"a"===r?a.call(e):a?a.value:t.get(e)};async function ty(e){let{response:t}=e;if(e.options.stream)return(tF("response",t.status,t.url,t.headers,t.body),e.options.__streamClass)?e.options.__streamClass.fromSSEResponse(t,e.controller):eQ.fromSSEResponse(t,e.controller);if(204===t.status)return null;if(e.options.__binaryResponse)return t;let r=t.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){let e=await t.json();return tF("response",t.status,t.url,t.headers,e),e}let a=await t.text();return tF("response",t.status,t.url,t.headers,a),a}class tb extends Promise{constructor(e,t=ty){super(e=>{e(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new tb(this.responsePromise,async t=>e(await this.parseResponse(t)))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),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)}}class t_{constructor({baseURL:e,maxRetries:t=2,timeout:r=6e5,httpAgent:a,fetch:i}){this.baseURL=e,this.maxRetries=tC("maxRetries",t),this.timeout=tC("timeout",r),this.httpAgent=a,this.fetch=i??d}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...tT(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${tB()}`}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(r=>({method:e,path:t,...r})))}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}calculateContentLength(e){if("string"==typeof e){if(void 0!==tp)return tp.byteLength(e,"utf8").toString();if("undefined"!=typeof TextEncoder)return new TextEncoder().encode(e).length.toString()}return null}buildRequest(e){let{method:t,path:r,query:a,headers:i={}}=e,n=tl(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,s=this.calculateContentLength(n),o=this.buildURL(r,a);"timeout"in e&&tC("timeout",e.timeout);let l=e.timeout??this.timeout,u=e.httpAgent??this.httpAgent??y(o),c=l+1e3;"number"==typeof u?.options?.timeout&&c>(u.options.timeout??0)&&(u.options.timeout=c),this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);let h=this.buildHeaders({options:e,headers:i,contentLength:s});return{req:{method:t,...n&&{body:n},headers:h,...u&&{agent:u},signal:e.signal??null},url:o,timeout:l}}buildHeaders({options:e,headers:t,contentLength:r}){let a={};return r&&(a["content-length"]=r),tD(a,this.defaultHeaders(e)),tD(a,t),tl(e.body)&&"node"!==h&&delete a["content-type"],this.validateHeaders(a,t),a}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(e=>[...e])):{...e}:{}}makeStatusError(e,t,r,a){return eF.generate(e,t,r,a)}request(e,t=null){return new tb(this.makeRequest(e,t))}async makeRequest(e,t){let r=await e;null==t&&(t=r.maxRetries??this.maxRetries),await this.prepareOptions(r);let{req:a,url:i,timeout:n}=this.buildRequest(r);if(await this.prepareRequest(a,{url:i,options:r}),tF("request",i,r,a.headers),r.signal?.aborted)throw new eB;let s=new AbortController,o=await this.fetchWithTimeout(i,a,n,s).catch(t$);if(o instanceof Error){if(r.signal?.aborted)throw new eB;if(t)return this.retryRequest(r,t);if("AbortError"===o.name)throw new eH;throw new ez({cause:o})}let l=tO(o.headers);if(!o.ok){if(t&&this.shouldRetry(o)){let e=`retrying, ${t} attempts remaining`;return tF(`response (error; ${e})`,o.status,i,l),this.retryRequest(r,t,l)}let e=await o.text().catch(e=>t$(e).message),a=tI(e),n=a?void 0:e,s=t?"(error; no more retries left)":"(error; not retryable)";throw tF(`response (error; ${s})`,o.status,i,l,n),this.makeStatusError(o.status,a,n,l)}return{response:o,options:r,controller:s}}requestAPIList(e,t){return new tv(this,this.makeRequest(t,null),e)}buildURL(e,t){let r=new URL(tj(e)?e:this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return tL(a)||(t={...a,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}stringifyQuery(e){return Object.entries(e).filter(([e,t])=>void 0!==t).map(([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new eD(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,r,a){let{signal:i,...n}=t||{};i&&i.addEventListener("abort",()=>a.abort());let s=setTimeout(()=>a.abort(),r);return this.getRequestClient().fetch.call(void 0,e,{signal:a.signal,...n}).finally(()=>{clearTimeout(s)})}getRequestClient(){return{fetch:this.fetch}}shouldRetry(e){let t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||409===e.status||429===e.status||!!(e.status>=500))}async retryRequest(e,t,r){let a;let i=r?.["retry-after-ms"];if(i){let e=parseFloat(i);Number.isNaN(e)||(a=e)}let n=r?.["retry-after"];if(n&&!a){let e=parseFloat(n);a=Number.isNaN(e)?Date.parse(n)-Date.now():1e3*e}if(!(a&&0<=a&&a<6e4)){let r=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,r)}return await tR(a),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){return Math.min(.5*Math.pow(2,t-e),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${eI}`}}class tw{constructor(e,t,r,a){w.set(this,void 0),tm(this,w,e,"f"),this.options=a,this.response=t,this.body=r}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new eD("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let t={...this.options};if("params"in e&&"object"==typeof t.query)t.query={...t.query,...e.params};else if("url"in e){for(let[r,a]of[...Object.entries(t.query||{}),...e.url.searchParams.entries()])e.url.searchParams.set(r,a);t.query=void 0,t.path=e.url.toString()}return await tg(this,w,"f").requestAPIList(this.constructor,t)}async *iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async *[(w=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}class tv extends tb{constructor(e,t,r){super(t,async t=>new r(e,t.response,await ty(t),t.options))}async *[Symbol.asyncIterator](){for await(let e of(await this))yield e}}let tO=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){let r=t.toString();return e[r.toLowerCase()]||e[r]}}),tE={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryResponse:!0,__streamClass:!0},tk=e=>"object"==typeof e&&null!==e&&!tL(e)&&Object.keys(e).every(e=>tU(tE,e)),tx=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":eI,"X-Stainless-OS":tP(Deno.build.os),"X-Stainless-Arch":tA(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":eI,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":tf.version};if("[object process]"===Object.prototype.toString.call(void 0!==tf?tf:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":eI,"X-Stainless-OS":tP(tf.platform),"X-Stainless-Arch":tA(tf.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":tf.version};let e=tS();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":eI,"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":eI,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function tS(){if("undefined"==typeof navigator||!navigator)return null;for(let{key:e,pattern:t}of[{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/}]){let r=t.exec(navigator.userAgent);if(r){let t=r[1]||0,a=r[2]||0,i=r[3]||0;return{browser:e,version:`${t}.${a}.${i}`}}}return null}let tA=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",tP=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown",tT=()=>a??(a=tx()),tI=e=>{try{return JSON.parse(e)}catch(e){return}},tN=RegExp("^(?:[a-z]+:)?//","i"),tj=e=>tN.test(e),tR=e=>new Promise(t=>setTimeout(t,e)),tC=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new eD(`${e} must be an integer`);if(t<0)throw new eD(`${e} must be a positive integer`);return t},t$=e=>e instanceof Error?e:Error(e),tM=e=>void 0!==tf?tf.env?.[e]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e)?.trim():void 0;function tL(e){if(!e)return!0;for(let t in e)return!1;return!0}function tU(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function tD(e,t){for(let r in t){if(!tU(t,r))continue;let a=r.toLowerCase();if(!a)continue;let i=t[r];null===i?delete e[a]:void 0!==i&&(e[a]=i)}}function tF(e,...t){void 0!==tf&&tf?.env?.DEBUG==="true"&&console.log(`OpenAI:DEBUG:${e}`,...t)}let tB=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),tz=()=>"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator;function tH(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}class tZ extends tw{constructor(e,t,r,a){super(e,t,r,a),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class tq extends tw{constructor(e,t,r,a){super(e,t,r,a),this.data=r.data||[]}getPaginatedItems(){return this.data??[]}nextPageParams(){let e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;let t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){let e=this.getPaginatedItems();if(!e.length)return null;let t=e[e.length-1]?.id;return t?{params:{after:t}}:null}}class tG{constructor(e){this._client=e}}class tW extends tG{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}tW||(tW={});class tK extends tG{create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}}tK||(tK={});class tJ extends tG{constructor(){super(...arguments),this.completions=new tK(this._client)}}!function(e){e.Completions=tK}(tJ||(tJ={}));class tY extends tG{create(e,t){return this._client.post("/embeddings",{body:e,...t})}}tY||(tY={});class tV extends tG{create(e,t){return this._client.post("/files",tu({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return tk(e)?this.list({},e):this._client.getAPIList("/files",tX,{query:e,...t})}del(e,t){return this._client.delete(`/files/${e}`,t)}content(e,t){return this._client.get(`/files/${e}/content`,{...t,__binaryResponse:!0})}retrieveContent(e,t){return this._client.get(`/files/${e}/content`,{...t,headers:{Accept:"application/json",...t?.headers}})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=18e5}={}){let a=new Set(["processed","error","deleted"]),i=Date.now(),n=await this.retrieve(e);for(;!n.status||!a.has(n.status);)if(await tR(t),n=await this.retrieve(e),Date.now()-i>r)throw new eH({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return n}}class tX extends tZ{}!function(e){e.FileObjectsPage=tX}(tV||(tV={}));class tQ extends tG{createVariation(e,t){return this._client.post("/images/variations",tu({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",tu({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}tQ||(tQ={});class t0 extends tG{create(e,t){return this._client.post("/audio/speech",{body:e,...t,__binaryResponse:!0})}}t0||(t0={});class t1 extends tG{create(e,t){return this._client.post("/audio/transcriptions",tu({body:e,...t}))}}t1||(t1={});class t2 extends tG{create(e,t){return this._client.post("/audio/translations",tu({body:e,...t}))}}t2||(t2={});class t4 extends tG{constructor(){super(...arguments),this.transcriptions=new t1(this._client),this.translations=new t2(this._client),this.speech=new t0(this._client)}}!function(e){e.Transcriptions=t1,e.Translations=t2,e.Speech=t0}(t4||(t4={}));class t5 extends tG{create(e,t){return this._client.post("/moderations",{body:e,...t})}}t5||(t5={});class t9 extends tG{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",t3,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class t3 extends tZ{}!function(e){e.ModelsPage=t3}(t9||(t9={}));class t6 extends tG{create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return tk(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",t8,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return tk(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,t7,{query:t,...r})}}class t8 extends tq{}class t7 extends tq{}!function(e){e.FineTuningJobsPage=t8,e.FineTuningJobEventsPage=t7}(t6||(t6={}));class re extends tG{constructor(){super(...arguments),this.jobs=new t6(this._client)}}!function(e){e.Jobs=t6,e.FineTuningJobsPage=t8,e.FineTuningJobEventsPage=t7}(re||(re={}));class rt extends tG{create(e,t,r){return this._client.post(`/assistants/${e}/files`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v1",...r?.headers}})}retrieve(e,t,r){return this._client.get(`/assistants/${e}/files/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v1",...r?.headers}})}list(e,t={},r){return tk(t)?this.list(e,{},t):this._client.getAPIList(`/assistants/${e}/files`,rr,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v1",...r?.headers}})}del(e,t,r){return this._client.delete(`/assistants/${e}/files/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v1",...r?.headers}})}}class rr extends tq{}!function(e){e.AssistantFilesPage=rr}(rt||(rt={}));class ra extends tG{constructor(){super(...arguments),this.files=new rt(this._client)}create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v1",...t?.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v1",...t?.headers}})}update(e,t,r){return this._client.post(`/assistants/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v1",...r?.headers}})}list(e={},t){return tk(e)?this.list({},e):this._client.getAPIList("/assistants",ri,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v1",...t?.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v1",...t?.headers}})}}class ri extends tq{}function rn(e){return"function"==typeof e.parse}!function(e){e.AssistantsPage=ri,e.Files=rt,e.AssistantFilesPage=rr}(ra||(ra={}));let rs=e=>e?.role==="assistant",ro=e=>e?.role==="function",rl=e=>e?.role==="tool";var ru=function(e,t,r,a,i){if("m"===a)throw TypeError("Private method is not writable");if("a"===a&&!i)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===a?i.call(e,r):i?i.value=r:t.set(e,r),r},rc=function(e,t,r,a){if("a"===r&&!a)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!a:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?a:"a"===r?a.call(e):a?a.value:t.get(e)};let rh=10;class rd{constructor(){v.add(this),this.controller=new AbortController,O.set(this,void 0),E.set(this,()=>{}),k.set(this,()=>{}),x.set(this,void 0),S.set(this,()=>{}),A.set(this,()=>{}),P.set(this,{}),this._chatCompletions=[],this.messages=[],T.set(this,!1),I.set(this,!1),N.set(this,!1),j.set(this,!1),U.set(this,e=>{if(ru(this,I,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new eB),e instanceof eB)return ru(this,N,!0,"f"),this._emit("abort",e);if(e instanceof eD)return this._emit("error",e);if(e instanceof Error){let t=new eD(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new eD(String(e)))}),ru(this,O,new Promise((e,t)=>{ru(this,E,e,"f"),ru(this,k,t,"f")}),"f"),ru(this,x,new Promise((e,t)=>{ru(this,S,e,"f"),ru(this,A,t,"f")}),"f"),rc(this,O,"f").catch(()=>{}),rc(this,x,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},rc(this,U,"f"))},0)}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),(ro(e)||rl(e))&&e.content)this._emit("functionCallResult",e.content);else if(rs(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(rs(e)&&e.tool_calls)for(let t of e.tool_calls)"function"===t.type&&this._emit("functionCall",t.function)}}_connected(){this.ended||(rc(this,E,"f").call(this),this._emit("connect"))}get ended(){return rc(this,T,"f")}get errored(){return rc(this,I,"f")}get aborted(){return rc(this,N,"f")}abort(){this.controller.abort()}on(e,t){return(rc(this,P,"f")[e]||(rc(this,P,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=rc(this,P,"f")[e];if(!r)return this;let a=r.findIndex(e=>e.listener===t);return a>=0&&r.splice(a,1),this}once(e,t){return(rc(this,P,"f")[e]||(rc(this,P,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{ru(this,j,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)})}async done(){ru(this,j,!0,"f"),await rc(this,x,"f")}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new eD("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),rc(this,v,"m",R).call(this)}async finalMessage(){return await this.done(),rc(this,v,"m",C).call(this)}async finalFunctionCall(){return await this.done(),rc(this,v,"m",$).call(this)}async finalFunctionCallResult(){return await this.done(),rc(this,v,"m",M).call(this)}async totalUsage(){return await this.done(),rc(this,v,"m",L).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emit(e,...t){if(rc(this,T,"f"))return;"end"===e&&(ru(this,T,!0,"f"),rc(this,S,"f").call(this));let r=rc(this,P,"f")[e];if(r&&(rc(this,P,"f")[e]=r.filter(e=>!e.once),r.forEach(({listener:e})=>e(...t))),"abort"===e){let e=t[0];rc(this,j,"f")||r?.length||Promise.reject(e),rc(this,k,"f").call(this,e),rc(this,A,"f").call(this,e),this._emit("end");return}if("error"===e){let e=t[0];rc(this,j,"f")||r?.length||Promise.reject(e),rc(this,k,"f").call(this,e),rc(this,A,"f").call(this,e),this._emit("end")}}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=rc(this,v,"m",C).call(this);t&&this._emit("finalMessage",t);let r=rc(this,v,"m",R).call(this);r&&this._emit("finalContent",r);let a=rc(this,v,"m",$).call(this);a&&this._emit("finalFunctionCall",a);let i=rc(this,v,"m",M).call(this);null!=i&&this._emit("finalFunctionCallResult",i),this._chatCompletions.some(e=>e.usage)&&this._emit("totalUsage",rc(this,v,"m",L).call(this))}async _createChatCompletion(e,t,r){let a=r?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort())),rc(this,v,"m",D).call(this,t);let i=await e.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(i)}async _runChatCompletion(e,t,r){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,r)}async _runFunctions(e,t,r){let a="function",{function_call:i="auto",stream:n,...s}=t,o="string"!=typeof i&&i?.name,{maxChatCompletions:l=rh}=r||{},u={};for(let e of t.functions)u[e.name||e.function.name]=e;let c=t.functions.map(e=>({name:e.name||e.function.name,parameters:e.parameters,description:e.description}));for(let e of t.messages)this._addMessage(e,!1);for(let t=0;tJSON.stringify(e.name)).join(", ")}. Please try again`;this._addMessage({role:a,name:h,content:e});continue}try{t=rn(p)?await p.parse(d):d}catch(e){this._addMessage({role:a,name:h,content:e instanceof Error?e.message:String(e)});continue}let f=await p.function(t,this),m=rc(this,v,"m",F).call(this,f);if(this._addMessage({role:a,name:h,content:m}),o)return}}async _runTools(e,t,r){let a="tool",{tool_choice:i="auto",stream:n,...s}=t,o="string"!=typeof i&&i?.function?.name,{maxChatCompletions:l=rh}=r||{},u={};for(let e of t.tools)"function"===e.type&&(u[e.function.name||e.function.function.name]=e.function);let c="tools"in t?t.tools.map(e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description}}:e):void 0;for(let e of t.messages)this._addMessage(e,!1);for(let t=0;tJSON.stringify(e.function.name)).join(", ")}. Please try again`;this._addMessage({role:a,tool_call_id:r,content:e});continue}try{t=rn(s)?await s.parse(n):n}catch(t){let e=t instanceof Error?t.message:String(t);this._addMessage({role:a,tool_call_id:r,content:e});continue}let l=await s.function(t,this),h=rc(this,v,"m",F).call(this,l);if(this._addMessage({role:a,tool_call_id:r,content:h}),o)return}}}}O=new WeakMap,E=new WeakMap,k=new WeakMap,x=new WeakMap,S=new WeakMap,A=new WeakMap,P=new WeakMap,T=new WeakMap,I=new WeakMap,N=new WeakMap,j=new WeakMap,U=new WeakMap,v=new WeakSet,R=function(){return rc(this,v,"m",C).call(this).content??null},C=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(rs(t))return{...t,content:t.content??null}}throw new eD("stream ended without producing a ChatCompletionMessage with role=assistant")},$=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(rs(t)&&t?.function_call)return t.function_call;if(rs(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},M=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(ro(t)&&null!=t.content||rl(t)&&null!=t.content&&this.messages.some(e=>"assistant"===e.role&&e.tool_calls?.some(e=>"function"===e.type&&e.id===t.tool_call_id)))return t.content}},L=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},D=function(e){if(null!=e.n&&e.n>1)throw new eD("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},F=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class rp extends rd{static runFunctions(e,t,r){let a=new rp,i={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return a._run(()=>a._runFunctions(e,t,i)),a}static runTools(e,t,r){let a=new rp,i={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return a._run(()=>a._runTools(e,t,i)),a}_addMessage(e){super._addMessage(e),rs(e)&&e.content&&this._emit("content",e.content)}}var rf=function(e,t,r,a){if("a"===r&&!a)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!a:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?a:"a"===r?a.call(e):a?a.value:t.get(e)},rm=function(e,t,r,a,i){if("m"===a)throw TypeError("Private method is not writable");if("a"===a&&!i)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===a?i.call(e,r):i?i.value=r:t.set(e,r),r};class rg extends rd{constructor(){super(...arguments),B.add(this),z.set(this,void 0)}get currentChatCompletionSnapshot(){return rf(this,z,"f")}static fromReadableStream(e){let t=new rg;return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let a=new rg;return a._run(()=>a._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createChatCompletion(e,t,r){let a=r?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort())),rf(this,B,"m",H).call(this);let i=await e.create({...t,stream:!0},{...r,signal:this.controller.signal});for await(let e of(this._connected(),i))rf(this,B,"m",Z).call(this,e);if(i.controller.signal?.aborted)throw new eB;return this._addChatCompletion(rf(this,B,"m",q).call(this))}async _fromReadableStream(e,t){let r;let a=t?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort())),rf(this,B,"m",H).call(this),this._connected();let i=eQ.fromReadableStream(e,this.controller);for await(let e of i)r&&r!==e.id&&this._addChatCompletion(rf(this,B,"m",q).call(this)),rf(this,B,"m",Z).call(this,e),r=e.id;if(i.controller.signal?.aborted)throw new eB;return this._addChatCompletion(rf(this,B,"m",q).call(this))}[(z=new WeakMap,B=new WeakSet,H=function(){this.ended||rm(this,z,void 0,"f")},Z=function(e){if(this.ended)return;let t=rf(this,B,"m",G).call(this,e);this._emit("chunk",e,t);let r=e.choices[0]?.delta?.content,a=t.choices[0]?.message;null!=r&&a?.role==="assistant"&&a?.content&&this._emit("content",r,a.content)},q=function(){if(this.ended)throw new eD("stream has ended, this shouldn't happen");let e=rf(this,z,"f");if(!e)throw new eD("request ended without sending any chunks");return rm(this,z,void 0,"f"),ry(e)},G=function(e){var t,r,a;let i=rf(this,z,"f"),{choices:n,...s}=e;for(let{delta:n,finish_reason:o,index:l,logprobs:u=null,...c}of(i?Object.assign(i,s):i=rm(this,z,{...s,choices:[]},"f"),e.choices)){let e=i.choices[l];if(e||(e=i.choices[l]={finish_reason:o,index:l,message:{},logprobs:u,...c}),u){if(e.logprobs){let{content:r,...a}=u;Object.assign(e.logprobs,a),r&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...r))}else e.logprobs=Object.assign({},u)}if(o&&(e.finish_reason=o),Object.assign(e,c),!n)continue;let{content:s,function_call:h,role:d,tool_calls:p,...f}=n;if(Object.assign(e.message,f),s&&(e.message.content=(e.message.content||"")+s),d&&(e.message.role=d),h&&(e.message.function_call?(h.name&&(e.message.function_call.name=h.name),h.arguments&&((r=e.message.function_call).arguments??(r.arguments=""),e.message.function_call.arguments+=h.arguments)):e.message.function_call=h),p)for(let{index:t,id:r,type:i,function:n,...s}of(e.message.tool_calls||(e.message.tool_calls=[]),p)){let o=(a=e.message.tool_calls)[t]??(a[t]={});Object.assign(o,s),r&&(o.id=r),i&&(o.type=i),n&&(o.function??(o.function={arguments:""})),n?.name&&(o.function.name=n.name),n?.arguments&&(o.function.arguments+=n.arguments)}}return i},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",r=>{let a=t.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{for(let e of(r=!0,t))e.resolve(void 0);t.length=0}),this.on("abort",e=>{for(let a of(r=!0,t))a.reject(e);t.length=0}),this.on("error",e=>{for(let a of(r=!0,t))a.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((e,r)=>t.push({resolve:e,reject:r})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new eQ(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function ry(e){let{id:t,choices:r,created:a,model:i,system_fingerprint:n,...s}=e;return{...s,id:t,choices:r.map(({message:t,finish_reason:r,index:a,logprobs:i,...n})=>{if(!r)throw new eD(`missing finish_reason for choice ${a}`);let{content:s=null,function_call:o,tool_calls:l,...u}=t,c=t.role;if(!c)throw new eD(`missing role for choice ${a}`);if(o){let{arguments:e,name:t}=o;if(null==e)throw new eD(`missing function_call.arguments for choice ${a}`);if(!t)throw new eD(`missing function_call.name for choice ${a}`);return{...n,message:{content:s,function_call:{arguments:e,name:t},role:c},finish_reason:r,index:a,logprobs:i}}return l?{...n,index:a,finish_reason:r,logprobs:i,message:{...u,role:c,content:s,tool_calls:l.map((t,r)=>{let{function:i,type:n,id:s,...o}=t,{arguments:l,name:u,...c}=i||{};if(null==s)throw new eD(`missing choices[${a}].tool_calls[${r}].id ${rb(e)}`);if(null==n)throw new eD(`missing choices[${a}].tool_calls[${r}].type ${rb(e)}`);if(null==u)throw new eD(`missing choices[${a}].tool_calls[${r}].function.name ${rb(e)}`);if(null==l)throw new eD(`missing choices[${a}].tool_calls[${r}].function.arguments ${rb(e)}`);return{...o,id:s,type:n,function:{...c,name:u,arguments:l}}})}}:{...n,message:{...u,content:s,role:c},finish_reason:r,index:a,logprobs:i}}),created:a,model:i,object:"chat.completion",...n?{system_fingerprint:n}:{}}}function rb(e){return JSON.stringify(e)}class r_ extends rg{static fromReadableStream(e){let t=new r_;return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,r){let a=new r_,i={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return a._run(()=>a._runFunctions(e,t,i)),a}static runTools(e,t,r){let a=new r_,i={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return a._run(()=>a._runTools(e,t,i)),a}}class rw extends tG{runFunctions(e,t){return e.stream?r_.runFunctions(this._client.chat.completions,e,t):rp.runFunctions(this._client.chat.completions,e,t)}runTools(e,t){return e.stream?r_.runTools(this._client.chat.completions,e,t):rp.runTools(this._client.chat.completions,e,t)}stream(e,t){return rg.createChatCompletion(this._client.chat.completions,e,t)}}class rv extends tG{constructor(){super(...arguments),this.completions=new rw(this._client)}}!function(e){e.Completions=rw}(rv||(rv={}));var rO=function(e,t,r,a,i){if("m"===a)throw TypeError("Private method is not writable");if("a"===a&&!i)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===a?i.call(e,r):i?i.value=r:t.set(e,r),r},rE=function(e,t,r,a){if("a"===r&&!a)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!a:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?a:"a"===r?a.call(e):a?a.value:t.get(e)};class rk{constructor(){this.controller=new AbortController,W.set(this,void 0),K.set(this,()=>{}),J.set(this,()=>{}),Y.set(this,void 0),V.set(this,()=>{}),X.set(this,()=>{}),Q.set(this,{}),ee.set(this,!1),et.set(this,!1),er.set(this,!1),ea.set(this,!1),ei.set(this,e=>{if(rO(this,et,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new eB),e instanceof eB)return rO(this,er,!0,"f"),this._emit("abort",e);if(e instanceof eD)return this._emit("error",e);if(e instanceof Error){let t=new eD(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new eD(String(e)))}),rO(this,W,new Promise((e,t)=>{rO(this,K,e,"f"),rO(this,J,t,"f")}),"f"),rO(this,Y,new Promise((e,t)=>{rO(this,V,e,"f"),rO(this,X,t,"f")}),"f"),rE(this,W,"f").catch(()=>{}),rE(this,Y,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emit("end")},rE(this,ei,"f"))},0)}_addRun(e){return e}_connected(){this.ended||(rE(this,K,"f").call(this),this._emit("connect"))}get ended(){return rE(this,ee,"f")}get errored(){return rE(this,et,"f")}get aborted(){return rE(this,er,"f")}abort(){this.controller.abort()}on(e,t){return(rE(this,Q,"f")[e]||(rE(this,Q,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=rE(this,Q,"f")[e];if(!r)return this;let a=r.findIndex(e=>e.listener===t);return a>=0&&r.splice(a,1),this}once(e,t){return(rE(this,Q,"f")[e]||(rE(this,Q,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{rO(this,ea,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)})}async done(){rO(this,ea,!0,"f"),await rE(this,Y,"f")}_emit(e,...t){if(rE(this,ee,"f"))return;"end"===e&&(rO(this,ee,!0,"f"),rE(this,V,"f").call(this));let r=rE(this,Q,"f")[e];if(r&&(rE(this,Q,"f")[e]=r.filter(e=>!e.once),r.forEach(({listener:e})=>e(...t))),"abort"===e){let e=t[0];rE(this,ea,"f")||r?.length||Promise.reject(e),rE(this,J,"f").call(this,e),rE(this,X,"f").call(this,e),this._emit("end");return}if("error"===e){let e=t[0];rE(this,ea,"f")||r?.length||Promise.reject(e),rE(this,J,"f").call(this,e),rE(this,X,"f").call(this,e),this._emit("end")}}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,a){return await this._createAssistantStream(t,e,r,a)}async _runToolAssistantStream(e,t,r,a,i){return await this._createToolAssistantStream(r,e,t,a,i)}async _createThreadAssistantStream(e,t,r){let a=r?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));let i=await e.createAndRun({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addRun(i)}async _createToolAssistantStream(e,t,r,a,i){let n=i?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort()));let s=await e.submitToolOutputs(t,r,{...a,stream:!1},{...i,signal:this.controller.signal});return this._connected(),this._addRun(s)}async _createAssistantStream(e,t,r,a){let i=a?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let n=await e.create(t,{...r,stream:!1},{...a,signal:this.controller.signal});return this._connected(),this._addRun(n)}}W=new WeakMap,K=new WeakMap,J=new WeakMap,Y=new WeakMap,V=new WeakMap,X=new WeakMap,Q=new WeakMap,ee=new WeakMap,et=new WeakMap,er=new WeakMap,ea=new WeakMap,ei=new WeakMap;var rx=function(e,t,r,a){if("a"===r&&!a)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!a:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?a:"a"===r?a.call(e):a?a.value:t.get(e)},rS=function(e,t,r,a,i){if("m"===a)throw TypeError("Private method is not writable");if("a"===a&&!i)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===a?i.call(e,r):i?i.value=r:t.set(e,r),r};class rA extends rk{constructor(){super(...arguments),en.add(this),es.set(this,[]),eo.set(this,{}),el.set(this,{}),eu.set(this,void 0),ec.set(this,void 0),eh.set(this,void 0),ed.set(this,void 0),ep.set(this,void 0),ef.set(this,void 0),em.set(this,void 0),eg.set(this,void 0),ey.set(this,void 0)}[(es=new WeakMap,eo=new WeakMap,el=new WeakMap,eu=new WeakMap,ec=new WeakMap,eh=new WeakMap,ed=new WeakMap,ep=new WeakMap,ef=new WeakMap,em=new WeakMap,eg=new WeakMap,ey=new WeakMap,en=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",r=>{let a=t.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{for(let e of(r=!0,t))e.resolve(void 0);t.length=0}),this.on("abort",e=>{for(let a of(r=!0,t))a.reject(e);t.length=0}),this.on("error",e=>{for(let a of(r=!0,t))a.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((e,r)=>t.push({resolve:e,reject:r})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new rA;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();let a=eQ.fromReadableStream(e,this.controller);for await(let e of a)rx(this,en,"m",eb).call(this,e);if(a.controller.signal?.aborted)throw new eB;return this._addRun(rx(this,en,"m",e_).call(this))}toReadableStream(){return new eQ(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,a,i){let n=new rA;return n._run(()=>n._runToolAssistantStream(e,t,r,a,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createToolAssistantStream(e,t,r,a,i){let n=i?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort()));let s={...a,stream:!0},o=await e.submitToolOutputs(t,r,s,{...i,signal:this.controller.signal});for await(let e of(this._connected(),o))rx(this,en,"m",eb).call(this,e);if(o.controller.signal?.aborted)throw new eB;return this._addRun(rx(this,en,"m",e_).call(this))}static createThreadAssistantStream(e,t,r){let a=new rA;return a._run(()=>a._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),a}static createAssistantStream(e,t,r,a){let i=new rA;return i._run(()=>i._runAssistantStream(e,t,r,{...a,headers:{...a?.headers,"X-Stainless-Helper-Method":"stream"}})),i}currentEvent(){return rx(this,em,"f")}currentRun(){return rx(this,eg,"f")}currentMessageSnapshot(){return rx(this,eu,"f")}currentRunStepSnapshot(){return rx(this,ey,"f")}async finalRunSteps(){return await this.done(),Object.values(rx(this,eo,"f"))}async finalMessages(){return await this.done(),Object.values(rx(this,el,"f"))}async finalRun(){if(await this.done(),!rx(this,ec,"f"))throw Error("Final run was not received.");return rx(this,ec,"f")}async _createThreadAssistantStream(e,t,r){let a=r?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));let i={...t,stream:!0},n=await e.createAndRun(i,{...r,signal:this.controller.signal});for await(let e of(this._connected(),n))rx(this,en,"m",eb).call(this,e);if(n.controller.signal?.aborted)throw new eB;return this._addRun(rx(this,en,"m",e_).call(this))}async _createAssistantStream(e,t,r,a){let i=a?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let n={...r,stream:!0},s=await e.create(t,n,{...a,signal:this.controller.signal});for await(let e of(this._connected(),s))rx(this,en,"m",eb).call(this,e);if(s.controller.signal?.aborted)throw new eB;return this._addRun(rx(this,en,"m",e_).call(this))}static accumulateDelta(e,t){for(let[r,a]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=a;continue}let t=e[r];if(null==t||"index"===r||"type"===r){e[r]=a;continue}if("string"==typeof t&&"string"==typeof a)t+=a;else if("number"==typeof t&&"number"==typeof a)t+=a;else if(tH(t)&&tH(a))t=this.accumulateDelta(t,a);else if(Array.isArray(t)&&Array.isArray(a)){if(t.every(e=>"string"==typeof e||"number"==typeof e)){t.push(...a);continue}}else throw Error(`Unhandled record type: ${r}, deltaValue: ${a}, accValue: ${t}`);e[r]=t}return e}}eb=function(e){if(!this.ended)switch(rS(this,em,e,"f"),rx(this,en,"m",eO).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.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":rx(this,en,"m",eS).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":rx(this,en,"m",ev).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":rx(this,en,"m",ew).call(this,e);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier")}},e_=function(){if(this.ended)throw new eD("stream has ended, this shouldn't happen");if(!rx(this,ec,"f"))throw Error("Final run has not been received");return rx(this,ec,"f")},ew=function(e){let[t,r]=rx(this,en,"m",ek).call(this,e,rx(this,eu,"f"));for(let e of(rS(this,eu,t,"f"),rx(this,el,"f")[t.id]=t,r)){let r=t.content[e.index];r?.type=="text"&&this._emit("textCreated",r.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let r of e.data.delta.content){if("text"==r.type&&r.text){let e=r.text,a=t.content[r.index];if(a&&"text"==a.type)this._emit("textDelta",e,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(r.index!=rx(this,eh,"f")){if(rx(this,ed,"f"))switch(rx(this,ed,"f").type){case"text":this._emit("textDone",rx(this,ed,"f").text,rx(this,eu,"f"));break;case"image_file":this._emit("imageFileDone",rx(this,ed,"f").image_file,rx(this,eu,"f"))}rS(this,eh,r.index,"f")}rS(this,ed,t.content[r.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==rx(this,eh,"f")){let t=e.data.content[rx(this,eh,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,rx(this,eu,"f"));break;case"text":this._emit("textDone",t.text,rx(this,eu,"f"))}}rx(this,eu,"f")&&this._emit("messageDone",e.data),rS(this,eu,void 0,"f")}},ev=function(e){let t=rx(this,en,"m",eE).call(this,e);switch(rS(this,ey,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&"tool_calls"==r.step_details.type&&r.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(let e of r.step_details.tool_calls)e.index==rx(this,ep,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(rx(this,ef,"f")&&this._emit("toolCallDone",rx(this,ef,"f")),rS(this,ep,e.index,"f"),rS(this,ef,t.step_details.tool_calls[e.index],"f"),rx(this,ef,"f")&&this._emit("toolCallCreated",rx(this,ef,"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":rS(this,ey,void 0,"f"),"tool_calls"==e.data.step_details.type&&rx(this,ef,"f")&&(this._emit("toolCallDone",rx(this,ef,"f")),rS(this,ef,void 0,"f")),this._emit("runStepDone",e.data,t)}},eO=function(e){rx(this,es,"f").push(e),this._emit("event",e)},eE=function(e){switch(e.event){case"thread.run.step.created":return rx(this,eo,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=rx(this,eo,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let a=rA.accumulateDelta(t,r.delta);rx(this,eo,"f")[e.data.id]=a}return rx(this,eo,"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":rx(this,eo,"f")[e.data.id]=e.data}if(rx(this,eo,"f")[e.data.id])return rx(this,eo,"f")[e.data.id];throw Error("No snapshot available")},ek=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 a=e.data;if(a.delta.content)for(let e of a.delta.content)if(e.index in t.content){let r=t.content[e.index];t.content[e.index]=rx(this,en,"m",ex).call(this,e,r)}else t.content[e.index]=e,r.push(e);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")},ex=function(e,t){return rA.accumulateDelta(t,e)},eS=function(e){switch(rS(this,eg,e.data,"f"),e.event){case"thread.run.created":case"thread.run.queued":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":rS(this,ec,e.data,"f"),rx(this,ef,"f")&&(this._emit("toolCallDone",rx(this,ef,"f")),rS(this,ef,void 0,"f"))}};class rP extends tG{retrieve(e,t,r,a){return this._client.get(`/threads/${e}/messages/${t}/files/${r}`,{...a,headers:{"OpenAI-Beta":"assistants=v1",...a?.headers}})}list(e,t,r={},a){return tk(r)?this.list(e,t,{},r):this._client.getAPIList(`/threads/${e}/messages/${t}/files`,rT,{query:r,...a,headers:{"OpenAI-Beta":"assistants=v1",...a?.headers}})}}class rT extends tq{}!function(e){e.MessageFilesPage=rT}(rP||(rP={}));class rI extends tG{constructor(){super(...arguments),this.files=new rP(this._client)}create(e,t,r){return this._client.post(`/threads/${e}/messages`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v1",...r?.headers}})}retrieve(e,t,r){return this._client.get(`/threads/${e}/messages/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v1",...r?.headers}})}update(e,t,r,a){return this._client.post(`/threads/${e}/messages/${t}`,{body:r,...a,headers:{"OpenAI-Beta":"assistants=v1",...a?.headers}})}list(e,t={},r){return tk(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,rN,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v1",...r?.headers}})}}class rN extends tq{}!function(e){e.MessagesPage=rN,e.Files=rP,e.MessageFilesPage=rT}(rI||(rI={}));class rj extends tG{retrieve(e,t,r,a){return this._client.get(`/threads/${e}/runs/${t}/steps/${r}`,{...a,headers:{"OpenAI-Beta":"assistants=v1",...a?.headers}})}list(e,t,r={},a){return tk(r)?this.list(e,t,{},r):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,rR,{query:r,...a,headers:{"OpenAI-Beta":"assistants=v1",...a?.headers}})}}class rR extends tq{}!function(e){e.RunStepsPage=rR}(rj||(rj={}));class rC extends tG{constructor(){super(...arguments),this.steps=new rj(this._client)}create(e,t,r){return this._client.post(`/threads/${e}/runs`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v1",...r?.headers},stream:t.stream??!1})}retrieve(e,t,r){return this._client.get(`/threads/${e}/runs/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v1",...r?.headers}})}update(e,t,r,a){return this._client.post(`/threads/${e}/runs/${t}`,{body:r,...a,headers:{"OpenAI-Beta":"assistants=v1",...a?.headers}})}list(e,t={},r){return tk(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,r$,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v1",...r?.headers}})}cancel(e,t,r){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...r,headers:{"OpenAI-Beta":"assistants=v1",...r?.headers}})}async createAndPoll(e,t,r){let a=await this.create(e,t,r);return await this.poll(e,a.id,r)}createAndStream(e,t,r){return rA.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let a={...r?.headers,"X-Stainless-Poll-Helper":"true"};for(r?.pollIntervalMs&&(a["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){let{data:i,response:n}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...a}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let s=5e3;if(r?.pollIntervalMs)s=r.pollIntervalMs;else{let e=n.headers.get("openai-poll-after-ms");if(e){let t=parseInt(e);isNaN(t)||(s=t)}}await tR(s);break;case"requires_action":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,t,r){return rA.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r,a){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:r,...a,headers:{"OpenAI-Beta":"assistants=v1",...a?.headers},stream:r.stream??!1})}async submitToolOutputsAndPoll(e,t,r,a){let i=await this.submitToolOutputs(e,t,r,a);return await this.poll(e,i.id,a)}submitToolOutputsStream(e,t,r,a){return rA.createToolAssistantStream(e,t,this._client.beta.threads.runs,r,a)}}class r$ extends tq{}!function(e){e.RunsPage=r$,e.Steps=rj,e.RunStepsPage=rR}(rC||(rC={}));class rM extends tG{constructor(){super(...arguments),this.runs=new rC(this._client),this.messages=new rI(this._client)}create(e={},t){return tk(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v1",...t?.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v1",...t?.headers}})}update(e,t,r){return this._client.post(`/threads/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v1",...r?.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v1",...t?.headers}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v1",...t?.headers},stream:e.stream??!1})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.thread_id,r.id,t)}createAndRunStream(e,t){return rA.createThreadAssistantStream(e,this._client.beta.threads,t)}}!function(e){e.Runs=rC,e.RunsPage=r$,e.Messages=rI,e.MessagesPage=rN}(rM||(rM={}));class rL extends tG{constructor(){super(...arguments),this.chat=new rv(this._client),this.assistants=new ra(this._client),this.threads=new rM(this._client)}}!function(e){e.Chat=rv,e.Assistants=ra,e.AssistantsPage=ri,e.Threads=rM}(rL||(rL={}));class rU extends t_{constructor({baseURL:e=tM("OPENAI_BASE_URL"),apiKey:t=tM("OPENAI_API_KEY"),organization:r=tM("OPENAI_ORG_ID")??null,...a}={}){if(void 0===t)throw new eD("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let i={apiKey:t,organization:r,...a,baseURL:e||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&tz())throw new eD("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");super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new tW(this),this.chat=new tJ(this),this.embeddings=new tY(this),this.files=new tV(this),this.images=new tQ(this),this.audio=new t4(this),this.moderations=new t5(this),this.models=new t9(this),this.fineTuning=new re(this),this.beta=new rL(this),this._options=i,this.apiKey=t,this.organization=r}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}}eA=rU,rU.OpenAI=eA,rU.OpenAIError=eD,rU.APIError=eF,rU.APIConnectionError=ez,rU.APIConnectionTimeoutError=eH,rU.APIUserAbortError=eB,rU.NotFoundError=eW,rU.ConflictError=eK,rU.RateLimitError=eY,rU.BadRequestError=eZ,rU.AuthenticationError=eq,rU.InternalServerError=eV,rU.PermissionDeniedError=eG,rU.UnprocessableEntityError=eJ;let{vc:rD,LG:rF,xX:rB,qA:rz,cH:rH,m_:rZ,fK:rq,OE:rG,v7:rW,v3:rK,PO:rJ,Ll:rY,Is:rV}=eP;!function(e){e.toFile=tr,e.fileFromPath=b,e.Page=tZ,e.CursorPage=tq,e.Completions=tW,e.Chat=tJ,e.Embeddings=tY,e.Files=tV,e.FileObjectsPage=tX,e.Images=tQ,e.Audio=t4,e.Moderations=t5,e.Models=t9,e.ModelsPage=t3,e.FineTuning=re,e.Beta=rL}(rU||(rU={}));var rX=r(76591);function rQ(e,t){return t?.[e]||rX(e)}function r0(e,t,r){let a={};for(let i in e)Object.hasOwn(e,i)&&(a[t(i,r)]=e[i]);return a}function r1(e){return Array.isArray(e)?[...e]:{...e}}function r2(e,t){let r=r1(e);for(let[e,a]of Object.entries(t)){let[t,...i]=e.split(".").reverse(),n=r;for(let e of i.reverse()){if(void 0===n[e])break;n[e]=r1(n[e]),n=n[e]}void 0!==n[t]&&(n[t]={lc:1,type:"secret",id:[a]})}return r}function r4(e){let t=Object.getPrototypeOf(e);return"function"==typeof e.lc_name&&("function"!=typeof t.lc_name||e.lc_name()!==t.lc_name())?e.lc_name():e.name}r(85560);class r5{static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,r4(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}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_kwargs=e||{}}toJSON(){if(!this.lc_serializable||this.lc_kwargs instanceof r5||"object"!=typeof this.lc_kwargs||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let e={},t={},r=Object.keys(this.lc_kwargs).reduce((e,t)=>(e[t]=t in this?this[t]:this.lc_kwargs[t],e),{});for(let a=Object.getPrototypeOf(this);a;a=Object.getPrototypeOf(a))Object.assign(e,Reflect.get(a,"lc_aliases",this)),Object.assign(t,Reflect.get(a,"lc_secrets",this)),Object.assign(r,Reflect.get(a,"lc_attributes",this));return Object.keys(t).forEach(e=>{let t=this,a=r,[i,...n]=e.split(".").reverse();for(let e of n.reverse()){if(!(e in t)||void 0===t[e])return;e in a&&void 0!==a[e]||("object"==typeof t[e]&&null!=t[e]?a[e]={}:Array.isArray(t[e])&&(a[e]=[])),t=t[e],a=a[e]}i in t&&void 0!==t[i]&&(a[i]=a[i]||t[i])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:r0(Object.keys(t).length?r2(r,t):r,rQ,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}function r9(e,t){return"string"==typeof e?"string"==typeof t?e+t:[{type:"text",text:e},...t]:Array.isArray(t)?[...e,...t]:[...e,{type:"text",text:t}]}class r3 extends r5{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}get text(){return"string"==typeof this.content?this.content:""}constructor(e,t){"string"==typeof e&&(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}),this.name=e.name,this.content=e.content,this.additional_kwargs=e.additional_kwargs,this.response_metadata=e.response_metadata}toDict(){return{type:this._getType(),data:this.toJSON().kwargs}}toChunk(){let e=this._getType();if("human"===e)return new at({...this});if("ai"===e)return new aa({...this});if("system"===e)return new an({...this});if("function"===e)return new ao({...this});if(ac.isInstance(this))return new af({...this});else throw Error("Unknown message type.")}}function r6(e){return Array.isArray(e)&&e.every(e=>"number"==typeof e.index)}function r8(e,t){let r={...e};for(let[e,a]of Object.entries(t))if(null==r[e])r[e]=a;else if(null==a)continue;else if(typeof r[e]!=typeof a||Array.isArray(r[e])!==Array.isArray(a))throw Error(`field[${e}] already exists in the message chunk, but with a different type.`);else if("string"==typeof r[e])r[e]=r[e]+a;else if(Array.isArray(r[e])||"object"!=typeof r[e]){if("tool_calls"===e&&r6(r[e])&&r6(a))for(let t of a)r[e]?.[t.index]!==void 0?r[e]=r[e]?.map((e,r)=>r!==t.index?e:{...e,...t,function:{name:t.function.name??e.function.name,arguments:(e.function.arguments??"")+(t.function.arguments??"")}}):r[e][t.index]=t;else if(Array.isArray(r[e]))r[e]=r[e].concat(a);else{if(r[e]===a)continue;console.warn(`field[${e}] already exists in this message chunk and value has unsupported type.`)}}else r[e]=r8(r[e],a);return r}class r7 extends r3{}class ae extends r3{static lc_name(){return"HumanMessage"}_getType(){return"human"}}class at extends r7{static lc_name(){return"HumanMessageChunk"}_getType(){return"human"}concat(e){return new at({content:r9(this.content,e.content),additional_kwargs:r8(this.additional_kwargs,e.additional_kwargs),response_metadata:r8(this.response_metadata,e.response_metadata)})}}class ar extends r3{static lc_name(){return"AIMessage"}_getType(){return"ai"}}class aa extends r7{static lc_name(){return"AIMessageChunk"}_getType(){return"ai"}concat(e){return new aa({content:r9(this.content,e.content),additional_kwargs:r8(this.additional_kwargs,e.additional_kwargs),response_metadata:r8(this.response_metadata,e.response_metadata)})}}class ai extends r3{static lc_name(){return"SystemMessage"}_getType(){return"system"}}class an extends r7{static lc_name(){return"SystemMessageChunk"}_getType(){return"system"}concat(e){return new an({content:r9(this.content,e.content),additional_kwargs:r8(this.additional_kwargs,e.additional_kwargs),response_metadata:r8(this.response_metadata,e.response_metadata)})}}class as extends r3{static lc_name(){return"FunctionMessage"}constructor(e,t){"string"==typeof e&&(e={content:e,name:t}),super(e)}_getType(){return"function"}}class ao extends r7{static lc_name(){return"FunctionMessageChunk"}_getType(){return"function"}concat(e){return new ao({content:r9(this.content,e.content),additional_kwargs:r8(this.additional_kwargs,e.additional_kwargs),response_metadata:r8(this.response_metadata,e.response_metadata),name:this.name??""})}}class al extends r3{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}constructor(e,t,r){"string"==typeof e&&(e={content:e,name:r,tool_call_id:t}),super(e),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id}_getType(){return"tool"}static isInstance(e){return"tool"===e._getType()}}class au extends r7{constructor(e){super(e),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id}static lc_name(){return"ToolMessageChunk"}_getType(){return"tool"}concat(e){return new au({content:r9(this.content,e.content),additional_kwargs:r8(this.additional_kwargs,e.additional_kwargs),response_metadata:r8(this.response_metadata,e.response_metadata),tool_call_id:this.tool_call_id})}}class ac extends r3{static lc_name(){return"ChatMessage"}static _chatMessageClass(){return ac}constructor(e,t){"string"==typeof e&&(e={content:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){return"generic"}static isInstance(e){return"generic"===e._getType()}}function ah(e){return"function"==typeof e?._getType}function ad(e){return ah(e)&&"function"==typeof e.concat}function ap(e){if("string"==typeof e)return new ae(e);if(ah(e))return e;let[t,r]=e;if("human"===t||"user"===t)return new ae({content:r});if("ai"===t||"assistant"===t)return new ar({content:r});if("system"===t)return new ai({content:r});throw Error("Unable to coerce message from array: only human, AI, or system message coercion is currently supported.")}class af extends r7{static lc_name(){return"ChatMessageChunk"}constructor(e,t){"string"==typeof e&&(e={content:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){return"generic"}concat(e){return new af({content:r9(this.content,e.content),additional_kwargs:r8(this.additional_kwargs,e.additional_kwargs),response_metadata:r8(this.response_metadata,e.response_metadata),role:this.role})}}function am(e,t="Human",r="AI"){let a=[];for(let i of e){let e;if("human"===i._getType())e=t;else if("ai"===i._getType())e=r;else if("system"===i._getType())e="System";else if("function"===i._getType())e="Function";else if("tool"===i._getType())e="Tool";else if("generic"===i._getType())e=i.role;else throw Error(`Got unsupported message type: ${i._getType()}`);let n=i.name?`${i.name}, `:"";a.push(`${e}: ${n}${i.content}`)}return a.join("\n")}function ag(e){if(void 0!==e.data)return e;{let t=e;return{type:t.type,data:{content:t.text,role:t.role,name:void 0,tool_call_id:void 0}}}}let ay="__run";class ab{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 ab({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}}class a_ extends ab{constructor(e){super(e),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.message=e.message}concat(e){return new a_({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo},message:this.message.concat(e.message)})}}var aw=r(49509);let av=()=>"undefined"!=typeof window&&void 0!==window.document,aO=()=>"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name,aE=()=>"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")),ak=()=>"undefined"!=typeof Deno,ax=()=>void 0!==aw&&void 0!==aw.versions&&void 0!==aw.versions.node&&!ak(),aS=()=>{let e;return av()?"browser":ax()?"node":aO()?"webworker":aE()?"jsdom":ak()?"deno":"other"};async function aA(){return void 0===i&&(i={library:"langchain-js",runtime:aS()}),i}function aP(e){try{return void 0!==aw?aw.env?.[e]:void 0}catch(e){return}}var aT="object"==typeof window?window:{},aI="0123456789abcdef".split(""),aN=[-0x80000000,8388608,32768,128],aj=[24,16,8,0],aR=[];function aC(e){e?(aR[0]=aR[16]=aR[1]=aR[2]=aR[3]=aR[4]=aR[5]=aR[6]=aR[7]=aR[8]=aR[9]=aR[10]=aR[11]=aR[12]=aR[13]=aR[14]=aR[15]=0,this.blocks=aR):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.h0=0x67452301,this.h1=0xefcdab89,this.h2=0x98badcfe,this.h3=0x10325476,this.h4=0xc3d2e1f0,this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}aC.prototype.update=function(e){if(!this.finalized){var t="string"!=typeof e;t&&e.constructor===aT.ArrayBuffer&&(e=new Uint8Array(e));for(var r,a,i=0,n=e.length||0,s=this.blocks;i>2]|=e[i]<>2]|=r<>2]|=(192|r>>6)<=57344?s[a>>2]|=(224|r>>12)<>2]|=(240|r>>18)<>2]|=(128|r>>12&63)<>2]|=(128|r>>6&63)<>2]|=(128|63&r)<=64?(this.block=s[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>0xffffffff&&(this.hBytes+=this.bytes/0x100000000<<0,this.bytes=this.bytes%0x100000000),this}},aC.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>2]|=aN[3&t],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}},aC.prototype.hash=function(){var e,t,r,a=this.h0,i=this.h1,n=this.h2,s=this.h3,o=this.h4,l=this.blocks;for(t=16;t<80;++t)r=l[t-3]^l[t-8]^l[t-14]^l[t-16],l[t]=r<<1|r>>>31;for(t=0;t<20;t+=5)e=i&n|~i&s,o=(r=a<<5|a>>>27)+e+o+0x5a827999+l[t]<<0,e=a&(i=i<<30|i>>>2)|~a&n,s=(r=o<<5|o>>>27)+e+s+0x5a827999+l[t+1]<<0,e=o&(a=a<<30|a>>>2)|~o&i,n=(r=s<<5|s>>>27)+e+n+0x5a827999+l[t+2]<<0,e=s&(o=o<<30|o>>>2)|~s&a,i=(r=n<<5|n>>>27)+e+i+0x5a827999+l[t+3]<<0,e=n&(s=s<<30|s>>>2)|~n&o,a=(r=i<<5|i>>>27)+e+a+0x5a827999+l[t+4]<<0,n=n<<30|n>>>2;for(;t<40;t+=5)e=i^n^s,o=(r=a<<5|a>>>27)+e+o+0x6ed9eba1+l[t]<<0,e=a^(i=i<<30|i>>>2)^n,s=(r=o<<5|o>>>27)+e+s+0x6ed9eba1+l[t+1]<<0,e=o^(a=a<<30|a>>>2)^i,n=(r=s<<5|s>>>27)+e+n+0x6ed9eba1+l[t+2]<<0,e=s^(o=o<<30|o>>>2)^a,i=(r=n<<5|n>>>27)+e+i+0x6ed9eba1+l[t+3]<<0,e=n^(s=s<<30|s>>>2)^o,a=(r=i<<5|i>>>27)+e+a+0x6ed9eba1+l[t+4]<<0,n=n<<30|n>>>2;for(;t<60;t+=5)e=i&n|i&s|n&s,o=(r=a<<5|a>>>27)+e+o-0x70e44324+l[t]<<0,e=a&(i=i<<30|i>>>2)|a&n|i&n,s=(r=o<<5|o>>>27)+e+s-0x70e44324+l[t+1]<<0,e=o&(a=a<<30|a>>>2)|o&i|a&i,n=(r=s<<5|s>>>27)+e+n-0x70e44324+l[t+2]<<0,e=s&(o=o<<30|o>>>2)|s&a|o&a,i=(r=n<<5|n>>>27)+e+i-0x70e44324+l[t+3]<<0,e=n&(s=s<<30|s>>>2)|n&o|s&o,a=(r=i<<5|i>>>27)+e+a-0x70e44324+l[t+4]<<0,n=n<<30|n>>>2;for(;t<80;t+=5)e=i^n^s,o=(r=a<<5|a>>>27)+e+o-0x359d3e2a+l[t]<<0,e=a^(i=i<<30|i>>>2)^n,s=(r=o<<5|o>>>27)+e+s-0x359d3e2a+l[t+1]<<0,e=o^(a=a<<30|a>>>2)^i,n=(r=s<<5|s>>>27)+e+n-0x359d3e2a+l[t+2]<<0,e=s^(o=o<<30|o>>>2)^a,i=(r=n<<5|n>>>27)+e+i-0x359d3e2a+l[t+3]<<0,e=n^(s=s<<30|s>>>2)^o,a=(r=i<<5|i>>>27)+e+a-0x359d3e2a+l[t+4]<<0,n=n<<30|n>>>2;this.h0=this.h0+a<<0,this.h1=this.h1+i<<0,this.h2=this.h2+n<<0,this.h3=this.h3+s<<0,this.h4=this.h4+o<<0},aC.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,a=this.h3,i=this.h4;return aI[e>>28&15]+aI[e>>24&15]+aI[e>>20&15]+aI[e>>16&15]+aI[e>>12&15]+aI[e>>8&15]+aI[e>>4&15]+aI[15&e]+aI[t>>28&15]+aI[t>>24&15]+aI[t>>20&15]+aI[t>>16&15]+aI[t>>12&15]+aI[t>>8&15]+aI[t>>4&15]+aI[15&t]+aI[r>>28&15]+aI[r>>24&15]+aI[r>>20&15]+aI[r>>16&15]+aI[r>>12&15]+aI[r>>8&15]+aI[r>>4&15]+aI[15&r]+aI[a>>28&15]+aI[a>>24&15]+aI[a>>20&15]+aI[a>>16&15]+aI[a>>12&15]+aI[a>>8&15]+aI[a>>4&15]+aI[15&a]+aI[i>>28&15]+aI[i>>24&15]+aI[i>>20&15]+aI[i>>16&15]+aI[i>>12&15]+aI[i>>8&15]+aI[i>>4&15]+aI[15&i]},aC.prototype.toString=aC.prototype.hex,aC.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,a=this.h3,i=this.h4;return[e>>24&255,e>>16&255,e>>8&255,255&e,t>>24&255,t>>16&255,t>>8&255,255&t,r>>24&255,r>>16&255,r>>8&255,255&r,a>>24&255,a>>16&255,a>>8&255,255&a,i>>24&255,i>>16&255,i>>8&255,255&i]},aC.prototype.array=aC.prototype.digest,aC.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(20),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),e};let a$=e=>new aC(!0).update(e).hex(),aM=(...e)=>a$(e.join("_"));class aL{}let aU=new Map;class aD extends aL{constructor(e){super(),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cache=e??new Map}lookup(e,t){return Promise.resolve(this.cache.get(aM(e,t))??null)}async update(e,t,r){this.cache.set(aM(e,t),r)}static global(){return new aD(aU)}}class aF extends r5{}class aB extends aF{static lc_name(){return"StringPromptValue"}constructor(e){super({value:e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.value=e}toString(){return this.value}toChatMessages(){return[new ae(this.value)]}}class az extends aF{static lc_name(){return"ChatPromptValue"}constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.messages=e.messages}toString(){return am(this.messages)}toChatMessages(){return this.messages}}var aH=r(52813),aZ=r(52435);let aq=[400,401,402,403,404,405,406,407,409],aG=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||"AbortError"===e.name||e?.code==="ECONNABORTED")throw e;let t=e?.response?.status??e?.status;if(t&&aq.includes(+t))throw e;if(e?.error?.code==="insufficient_quota"){let t=Error(e?.message);throw t.name="InsufficientQuotaError",t}};class aW{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??aG;let t=aZ.default;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>aH(()=>e(...t).catch(e=>{if(e instanceof Error)throw e;throw Error(e)}),{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((t,r)=>{e.signal?.addEventListener("abort",()=>{r(Error("AbortError"))})})]):this.call(t,...r)}fetch(...e){return this.call(()=>fetch(...e).then(e=>e.ok?e:Promise.reject(e)))}}var aK=r(57719),aJ=Object.defineProperty,aY=(e,t,r)=>t in e?aJ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;function aV(e,t){let r=Array.from({length:e.length},(e,t)=>({start:t,end:t+1}));for(;r.length>1;){let a=null;for(let i=0;it.get(e.slice(r.start,r.end).join(","))).filter(e=>null!=e)}function aQ(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var a0=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,t){for(let[t,r]of(this.patStr=e.pat_str,Object.entries(e.bpe_ranks.split("\n").filter(Boolean).reduce((e,t)=>{let[r,a,...i]=t.split(" "),n=Number.parseInt(a,10);return i.forEach((t,r)=>e[t]=n+r),e},{})))){let e=aK.toByteArray(t);this.rankMap.set(e.join(","),r),this.textMap.set(r,e)}this.specialTokens={...e.special_tokens,...t},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((e,[t,r])=>(e[r]=this.textEncoder.encode(t),e),{})}encode(e,t=[],r="all"){let a=RegExp(this.patStr,"ug"),i=a0.specialTokenRegex(Object.keys(this.specialTokens)),n=[],s=new Set("all"===t?Object.keys(this.specialTokens):t),o=new Set("all"===r?Object.keys(this.specialTokens).filter(e=>!s.has(e)):r);if(o.size>0){let t=a0.specialTokenRegex([...o]),r=e.match(t);if(null!=r)throw Error(`The text contains a special token that is not allowed: ${r[0]}`)}let l=0;for(;;){let t=null,r=l;for(;i.lastIndex=r,!(null==(t=i.exec(e))||s.has(t[0]));)r=t.index+1;let o=t?.index??e.length;for(let t of e.substring(l,o).matchAll(a)){let e=this.textEncoder.encode(t[0]),r=this.rankMap.get(e.join(","));if(null!=r){n.push(r);continue}n.push(...aX(e,this.rankMap))}if(null==t)break;let u=this.specialTokens[t[0]];n.push(u),l=t.index+t[0].length}return n}decode(e){let t=[],r=0;for(let a=0;aaY(e,"symbol"!=typeof t?t+"":t,r))(a1,"specialTokenRegex",e=>RegExp(e.map(e=>aQ(e)).join("|"),"g"));let a4={},a5=new aW({});async function a9(e){return e in a4||(a4[e]=a5.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(e=>e.json()).then(e=>new a1(e)).catch(t=>{throw delete a4[e],t})),await a4[e]}async function a3(e){return a9(a2(e))}var a6=r(55594);let a8={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)},a7=new Uint8Array(16);function ie(){if(!n&&!(n="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return n(a7)}let it=[];for(let e=0;e<256;++e)it.push((e+256).toString(16).slice(1));function ir(e,t=0){return it[e[t+0]]+it[e[t+1]]+it[e[t+2]]+it[e[t+3]]+"-"+it[e[t+4]]+it[e[t+5]]+"-"+it[e[t+6]]+it[e[t+7]]+"-"+it[e[t+8]]+it[e[t+9]]+"-"+it[e[t+10]]+it[e[t+11]]+it[e[t+12]]+it[e[t+13]]+it[e[t+14]]+it[e[t+15]]}let ia=function(e,t,r){if(a8.randomUUID&&!t&&!e)return a8.randomUUID();let a=(e=e||{}).random||(e.rng||ie)();if(a[6]=15&a[6]|64,a[8]=63&a[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=a[e];return t}return ir(a)};class ii{}class is extends ii{get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,r4(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,"awaitHandlers",{enumerable:!0,configurable:!0,writable:!0,value:"true"!==aP("LANGCHAIN_CALLBACKS_BACKGROUND")}),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.awaitHandlers=e._awaitHandler??this.awaitHandlers)}copy(){return new this.constructor(this)}toJSON(){return r5.prototype.toJSON.call(this)}toJSONNotImplemented(){return r5.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends is{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:ia()}),Object.assign(this,e)}}return new t}}var io=r(14848);function il(e,t){return e&&!Array.isArray(e)&&"object"==typeof e?e:{[t]:e}}function iu(e){return e.replace(/[-:.]/g,"")}function ic(e,t){return iu(`${new Date(e).toISOString().slice(0,-1)}000Z`)+t}class ih extends is{constructor(e){super(...arguments),Object.defineProperty(this,"runMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}copy(){return this}stringifyError(e){return e instanceof Error?e.message+(e?.stack?` ${e.stack}`:""):"string"==typeof e?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}async _startTrace(e){let t=ic(e.start_time,e.id),r={...e};if(void 0!==r.parent_run_id){let e=this.runMap.get(r.parent_run_id);e&&(this._addChildRun(e,r),e.child_execution_order=Math.max(e.child_execution_order,r.child_execution_order),r.trace_id=e.trace_id,void 0!==e.dotted_order&&(r.dotted_order=[e.dotted_order,t].join(".")))}else r.trace_id=r.id,r.dotted_order=t;this.runMap.set(r.id,r),await this.onRunCreate?.(r)}async _endTrace(e){let t=void 0!==e.parent_run_id&&this.runMap.get(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),this.runMap.delete(e.id),await this.onRunUpdate?.(e)}_getExecutionOrder(e){let t=void 0!==e&&this.runMap.get(e);return t?t.child_execution_order+1:1}async handleLLMStart(e,t,r,a,i,n,s,o){let l=this._getExecutionOrder(a),u=Date.now(),c=s?{...i,metadata:s}:i,h={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:t},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:c??{},tags:n||[]};return await this._startTrace(h),await this.onLLMStart?.(h),h}async handleChatModelStart(e,t,r,a,i,n,s,o){let l=this._getExecutionOrder(a),u=Date.now(),c=s?{...i,metadata:s}:i,h={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:t},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:c??{},tags:n||[]};return await this._startTrace(h),await this.onLLMStart?.(h),h}async handleLLMEnd(e,t){let r=this.runMap.get(t);if(!r||r?.run_type!=="llm")throw Error("No LLM run to end.");return r.end_time=Date.now(),r.outputs=e,r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onLLMEnd?.(r),await this._endTrace(r),r}async handleLLMError(e,t){let r=this.runMap.get(t);if(!r||r?.run_type!=="llm")throw Error("No LLM 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.onLLMError?.(r),await this._endTrace(r),r}async handleChainStart(e,t,r,a,i,n,s,o){let l=this._getExecutionOrder(a),u=Date.now(),c={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:t,execution_order:l,child_execution_order:l,run_type:s??"chain",child_runs:[],extra:n?{metadata:n}:{},tags:i||[]};return await this._startTrace(c),await this.onChainStart?.(c),c}async handleChainEnd(e,t,r,a,i){let n=this.runMap.get(t);if(!n)throw Error("No chain run to end.");return n.end_time=Date.now(),n.outputs=il(e,"output"),n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),i?.inputs!==void 0&&(n.inputs=il(i.inputs,"input")),await this.onChainEnd?.(n),await this._endTrace(n),n}async handleChainError(e,t,r,a,i){let n=this.runMap.get(t);if(!n)throw Error("No chain run to end.");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),i?.inputs!==void 0&&(n.inputs=il(i.inputs,"input")),await this.onChainError?.(n),await this._endTrace(n),n}async handleToolStart(e,t,r,a,i,n,s){let o=this._getExecutionOrder(a),l=Date.now(),u={id:r,name:s??e.id[e.id.length-1],parent_run_id:a,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:t},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:n?{metadata:n}:{},tags:i||[]};return await this._startTrace(u),await this.onToolStart?.(u),u}async handleToolEnd(e,t){let r=this.runMap.get(t);if(!r||r?.run_type!=="tool")throw 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){let r=this.runMap.get(t);if(!r||r?.run_type!=="tool")throw 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){let r=this.runMap.get(t);if(!r||r?.run_type!=="chain")return;let a=r;a.actions=a.actions||[],a.actions.push(e),a.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(r)}async handleAgentEnd(e,t){let r=this.runMap.get(t);r&&r?.run_type==="chain"&&(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(r))}async handleRetrieverStart(e,t,r,a,i,n,s){let o=this._getExecutionOrder(a),l=Date.now(),u={id:r,name:s??e.id[e.id.length-1],parent_run_id:a,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{query:t},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:n?{metadata:n}:{},tags:i||[]};return await this._startTrace(u),await this.onRetrieverStart?.(u),u}async handleRetrieverEnd(e,t){let r=this.runMap.get(t);if(!r||r?.run_type!=="retriever")throw 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){let r=this.runMap.get(t);if(!r||r?.run_type!=="retriever")throw 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){let r=this.runMap.get(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,a,i,n){let s=this.runMap.get(r);if(!s||s?.run_type!=="llm")throw Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return s.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:n?.chunk}}),await this.onLLMNewToken?.(s,e,{chunk:n?.chunk}),s}}function id(e,t){return`${e.open}${t}${e.close}`}function ip(e,t){try{return JSON.stringify(e,null,2)}catch(e){return t}}function im(e){if(!e.end_time)return"";let t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}let{color:ig}=io;class iy extends ih{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"console_callback_handler"})}persistRun(e){return Promise.resolve()}getParents(e){let t=[],r=e;for(;r.parent_run_id;){let e=this.runMap.get(r.parent_run_id);if(e)t.push(e),r=e;else break}return t}getBreadcrumbs(e){let t=[...this.getParents(e).reverse(),e].map((e,t,r)=>{let a=`${e.execution_order}:${e.run_type}:${e.name}`;return t===r.length-1?id(io.bold,a):a}).join(" > ");return id(ig.grey,t)}onChainStart(e){let t=this.getBreadcrumbs(e);console.log(`${id(ig.green,"[chain/start]")} [${t}] Entering Chain run with input: ${ip(e.inputs,"[inputs]")}`)}onChainEnd(e){let t=this.getBreadcrumbs(e);console.log(`${id(ig.cyan,"[chain/end]")} [${t}] [${im(e)}] Exiting Chain run with output: ${ip(e.outputs,"[outputs]")}`)}onChainError(e){let t=this.getBreadcrumbs(e);console.log(`${id(ig.red,"[chain/error]")} [${t}] [${im(e)}] Chain run errored with error: ${ip(e.error,"[error]")}`)}onLLMStart(e){let t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(e=>e.trim())}:e.inputs;console.log(`${id(ig.green,"[llm/start]")} [${t}] Entering LLM run with input: ${ip(r,"[inputs]")}`)}onLLMEnd(e){let t=this.getBreadcrumbs(e);console.log(`${id(ig.cyan,"[llm/end]")} [${t}] [${im(e)}] Exiting LLM run with output: ${ip(e.outputs,"[response]")}`)}onLLMError(e){let t=this.getBreadcrumbs(e);console.log(`${id(ig.red,"[llm/error]")} [${t}] [${im(e)}] LLM run errored with error: ${ip(e.error,"[error]")}`)}onToolStart(e){let t=this.getBreadcrumbs(e);console.log(`${id(ig.green,"[tool/start]")} [${t}] Entering Tool run with input: "${e.inputs.input?.trim()}"`)}onToolEnd(e){let t=this.getBreadcrumbs(e);console.log(`${id(ig.cyan,"[tool/end]")} [${t}] [${im(e)}] Exiting Tool run with output: "${e.outputs?.output?.trim()}"`)}onToolError(e){let t=this.getBreadcrumbs(e);console.log(`${id(ig.red,"[tool/error]")} [${t}] [${im(e)}] Tool run errored with error: ${ip(e.error,"[error]")}`)}onRetrieverStart(e){let t=this.getBreadcrumbs(e);console.log(`${id(ig.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${ip(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){let t=this.getBreadcrumbs(e);console.log(`${id(ig.cyan,"[retriever/end]")} [${t}] [${im(e)}] Exiting Retriever run with output: ${ip(e.outputs,"[outputs]")}`)}onRetrieverError(e){let t=this.getBreadcrumbs(e);console.log(`${id(ig.red,"[retriever/error]")} [${t}] [${im(e)}] Retriever run errored with error: ${ip(e.error,"[error]")}`)}onAgentAction(e){let t=e,r=this.getBreadcrumbs(e);console.log(`${id(ig.blue,"[agent/action]")} [${r}] Agent selected action: ${ip(t.actions[t.actions.length-1],"[action]")}`)}}let ib=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,i_=function(e){return"string"==typeof e&&ib.test(e)},iw={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)},iv=new Uint8Array(16);function iO(){if(!s&&!(s="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return s(iv)}let iE=[];for(let e=0;e<256;++e)iE.push((e+256).toString(16).slice(1));function ik(e,t=0){return iE[e[t+0]]+iE[e[t+1]]+iE[e[t+2]]+iE[e[t+3]]+"-"+iE[e[t+4]]+iE[e[t+5]]+"-"+iE[e[t+6]]+iE[e[t+7]]+"-"+iE[e[t+8]]+iE[e[t+9]]+"-"+iE[e[t+10]]+iE[e[t+11]]+iE[e[t+12]]+iE[e[t+13]]+iE[e[t+14]]+iE[e[t+15]]}let ix=function(e,t,r){if(iw.randomUUID&&!t&&!e)return iw.randomUUID();let a=(e=e||{}).random||(e.rng||iO)();if(a[6]=15&a[6]|64,a[8]=63&a[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=a[e];return t}return ik(a)},iS=[400,401,403,404,405,406,407,408],iA=[409];class iP{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;let t=aZ.default;this.queue=new t({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){let r=this.onFailedResponseHook;return this.queue.add(()=>aH(()=>e(...t).catch(e=>{if(e instanceof Error)throw e;throw Error(e)}),{async onFailedAttempt(e){if(e.message.startsWith("Cancel")||e.message.startsWith("TimeoutError")||e.message.startsWith("AbortError")||e?.code==="ECONNABORTED")throw e;let t=e?.response,a=t?.status;if(a){if(iS.includes(+a))throw e;if(iA.includes(+a))return;r&&await r(t)}},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise((t,r)=>{e.signal?.addEventListener("abort",()=>{r(Error("AbortError"))})})]):this.call(t,...r)}fetch(...e){return this.call(()=>fetch(...e).then(e=>e.ok?e:Promise.reject(e)))}}function iT(e){return"function"==typeof e?._getType}function iI(e){let t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}var iN=r(49509);let ij=()=>"undefined"!=typeof window&&void 0!==window.document,iR=()=>"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name,iC=()=>"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")),i$=()=>"undefined"!=typeof Deno,iM=()=>void 0!==iN&&void 0!==iN.versions&&void 0!==iN.versions.node&&!i$(),iL=()=>o||(o=ij()?"browser":iM()?"node":iR()?"webworker":iC()?"jsdom":i$()?"deno":"other");async function iU(){return void 0===l&&(l={library:"langsmith",runtime:iL(),sdk:"langsmith-js",sdk_version:i0,...iz()}),l}function iD(){let e=iF()||{},t={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION"];for(let[a,i]of Object.entries(e))!a.startsWith("LANGCHAIN_")||"string"!=typeof i||r.includes(a)||a.toLowerCase().includes("key")||a.toLowerCase().includes("secret")||a.toLowerCase().includes("token")||("LANGCHAIN_REVISION_ID"===a?t.revision_id=i:t[a]=i);return t}function iF(){try{if(void 0!==iN&&iN.env)return Object.entries(iN.env).reduce((e,[t,r])=>(e[t]=String(r),e),{});return}catch(e){return}}function iB(e){try{return void 0!==iN?iN.env?.[e]:void 0}catch(e){return}}function iz(){if(void 0!==u)return u;let e={};for(let t of["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"]){let r=iB(t);void 0!==r&&(e[t]=r)}return u=e,e}async function iH(e){let t=await iU(),r=iD();return e.map(e=>{let a=e.extra??{},i=a.metadata;return e.extra={...a,runtime:{...t,...a?.runtime},metadata:{...r,...r.revision_id||e.revision_id?{revision_id:e.revision_id??r.revision_id}:{},...i}},e})}let iZ=()=>{let e=iB("LANGCHAIN_TRACING_SAMPLING_RATE");if(void 0===e)return;let t=parseFloat(e);if(t<0||t>1)throw Error(`LANGCHAIN_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${t}`);return t},iq=e=>{let t=e.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return"localhost"===t||"127.0.0.1"===t||"::1"===t},iG=async(e,t)=>{let r=await e.text();if(!e.ok)throw Error(`Failed to ${t}: ${e.status} ${e.statusText} ${r}`)};async function iW(e){let t=[];for await(let r of e)t.push(r);return t}function iK(e){if(void 0!==e)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}function iJ(e){if(!i_(e))throw Error(`Invalid UUID: ${e}`)}let iY=async e=>{if(e?.status===429){let t=1e3*parseInt(e.headers.get("retry-after")??"30",10);if(t>0)return await new Promise(e=>setTimeout(e,t)),!0}return!1};class iV{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]})}get size(){return this.items.length}push(e){return new Promise(t=>{this.items.push([e,t])})}pop(e){if(e<1)throw Error("Number of items to pop off may not be less than 1.");let t=[];for(;t.lengthe[0]),()=>t.forEach(e=>e[1]())]}}let iX=0x1400000;class iQ{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,"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,"sampledPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"batchEndpointSupported",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:new iV}),Object.defineProperty(this,"pendingAutoBatchedRunLimit",{enumerable:!0,configurable:!0,writable:!0,value:100}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchInitialDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:50}),Object.defineProperty(this,"serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let t=iQ.getDefaultClientConfig();this.tracingSampleRate=iZ(),this.apiUrl=iK(e.apiUrl??t.apiUrl)??"",this.apiKey=iK(e.apiKey??t.apiKey),this.webUrl=iK(e.webUrl??t.webUrl),this.timeout_ms=e.timeout_ms??12e3,this.caller=new iP(e.callerOptions??{}),this.batchIngestCaller=new iP({...e.callerOptions??{},onFailedResponseHook:iY}),this.hideInputs=e.hideInputs??t.hideInputs,this.hideOutputs=e.hideOutputs??t.hideOutputs,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.pendingAutoBatchedRunLimit=e.pendingAutoBatchedRunLimit??this.pendingAutoBatchedRunLimit,this.fetchOptions=e.fetchOptions||{}}static getDefaultClientConfig(){let e=iB("LANGCHAIN_API_KEY"),t=iB("LANGCHAIN_ENDPOINT")??"https://api.smith.langchain.com";return{apiUrl:t,apiKey:e,webUrl:void 0,hideInputs:"true"===iB("LANGCHAIN_HIDE_INPUTS"),hideOutputs:"true"===iB("LANGCHAIN_HIDE_OUTPUTS")}}getHostUrl(){return this.webUrl?this.webUrl:iq(this.apiUrl)?(this.webUrl="http://localhost","http://localhost"):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","https://dev.smith.langchain.com"):(this.webUrl="https://smith.langchain.com","https://smith.langchain.com")}get headers(){let e={"User-Agent":`langsmith-js/${i0}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),e}processInputs(e){return!1===this.hideInputs?e:!0===this.hideInputs?{}:"function"==typeof this.hideInputs?this.hideInputs(e):e}processOutputs(e){return!1===this.hideOutputs?e:!0===this.hideOutputs?{}:"function"==typeof this.hideOutputs?this.hideOutputs(e):e}prepareRunCreateOrUpdateInputs(e){let t={...e};return void 0!==t.inputs&&(t.inputs=this.processInputs(t.inputs)),void 0!==t.outputs&&(t.outputs=this.processOutputs(t.outputs)),t}async _getResponse(e,t){let r=t?.toString()??"",a=`${this.apiUrl}${e}?${r}`,i=await this.caller.call(fetch,a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(!i.ok)throw Error(`Failed to fetch ${e}: ${i.status} ${i.statusText}`);return i}async _get(e,t){return(await this._getResponse(e,t)).json()}async *_getPaginated(e,t=new URLSearchParams){let r=Number(t.get("offset"))||0,a=Number(t.get("limit"))||100;for(;;){t.set("offset",String(r)),t.set("limit",String(a));let i=`${this.apiUrl}${e}?${t}`,n=await this.caller.call(fetch,i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(!n.ok)throw Error(`Failed to fetch ${e}: ${n.status} ${n.statusText}`);let s=await n.json();if(0===s.length||(yield s,s.length=0;){let[e,t]=this.autoBatchQueue.pop(this.pendingAutoBatchedRunLimit);if(!e.length){t();return}try{await this.batchIngestRuns({runCreates:e.filter(e=>"create"===e.action).map(e=>e.item),runUpdates:e.filter(e=>"update"===e.action).map(e=>e.item)})}finally{t()}}}async processRunOperation(e,t){let r=this.autoBatchTimeout;clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0;let a=this.autoBatchQueue.push(e);return(t||this.autoBatchQueue.size>this.pendingAutoBatchedRunLimit)&&await this.drainAutoBatchQueue(),this.autoBatchQueue.size>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue().catch(console.error)},r?this.autoBatchAggregationDelayMs:this.autoBatchInitialDelayMs)),a}async _getServerInfo(){let e=await fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(!e.ok)throw await e.text(),Error("Failed to retrieve server info.");return e.json()}async batchEndpointIsSupported(){try{this.serverInfo=await this._getServerInfo()}catch(e){return!1}return!0}async createRun(e){if(!this._filterForSampling([e]).length)return;let t={...this.headers,"Content-Type":"application/json"},r=e.project_name;delete e.project_name;let a=this.prepareRunCreateOrUpdateInputs({session_name:r,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&void 0!==a.trace_id&&void 0!==a.dotted_order){this.processRunOperation({action:"create",item:a}).catch(console.error);return}let i=await iH([a]),n=await this.caller.call(fetch,`${this.apiUrl}/runs`,{method:"POST",headers:t,body:JSON.stringify(i[0]),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await iG(n,"create run")}async batchIngestRuns({runCreates:e,runUpdates:t}){if(void 0===e&&void 0===t)return;let r=e?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[],a=t?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[];if(r.length>0&&a.length>0){let e=r.reduce((e,t)=>(t.id&&(e[t.id]=t),e),{}),t=[];for(let r of a)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);r=Object.values(e),a=t}let i={post:this._filterForSampling(r),patch:this._filterForSampling(a,!0)};if(!i.post.length&&!i.patch.length)return;if(r=await iH(r),void 0===this.batchEndpointSupported&&(this.batchEndpointSupported=await this.batchEndpointIsSupported()),!this.batchEndpointSupported){for(let e of(this.autoBatchTracing=!1,i.post))await this.createRun(e);for(let e of i.patch)void 0!==e.id&&await this.updateRun(e.id,e);return}let n=this.serverInfo?.batch_ingest_config?.size_limit_bytes??iX,s={post:[],patch:[]},o=0;for(let e of["post","patch"]){let t=e,r=i[t].reverse(),a=r.pop();for(;void 0!==a;){let e=JSON.stringify(a);o>0&&o+e.length>n&&(await this._postBatchIngestRuns(JSON.stringify(s)),o=0,s.post=[],s.patch=[]),o+=e.length,s[t].push(a),a=r.pop()}}(s.post.length>0||s.patch.length>0)&&await this._postBatchIngestRuns(JSON.stringify(s))}async _postBatchIngestRuns(e){let t={...this.headers,"Content-Type":"application/json",Accept:"application/json"},r=await this.batchIngestCaller.call(fetch,`${this.apiUrl}/runs/batch`,{method:"POST",headers:t,body:e,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await iG(r,"batch create run")}async updateRun(e,t){iJ(e),t.inputs&&(t.inputs=this.processInputs(t.inputs)),t.outputs&&(t.outputs=this.processOutputs(t.outputs));let r={...t,id:e};if(!this._filterForSampling([r],!0).length)return;if(this.autoBatchTracing&&void 0!==r.trace_id&&void 0!==r.dotted_order){void 0!==t.end_time&&void 0===r.parent_run_id?await this.processRunOperation({action:"update",item:r},!0):this.processRunOperation({action:"update",item:r}).catch(console.error);return}let a={...this.headers,"Content-Type":"application/json"},i=await this.caller.call(fetch,`${this.apiUrl}/runs/${e}`,{method:"PATCH",headers:a,body:JSON.stringify(t),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await iG(i,"update run")}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){iJ(e);let r=await this._get(`/runs/${e}`);return t&&r.child_run_ids&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:t,projectOpts:r}){if(void 0!==t){let e;e=t.session_id?t.session_id:r?.projectName?(await this.readProject({projectName:r?.projectName})).id:r?.projectId?r?.projectId:(await this.readProject({projectName:iB("LANGCHAIN_PROJECT")||"default"})).id;let a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${e}/r/${t.id}?poll=true`}if(void 0!==e){let t=await this.readRun(e);if(!t.app_path)throw Error(`Run ${e} has no app_path`);let r=this.getHostUrl();return`${r}${t.app_path}`}throw Error("Must provide either runId or run")}async _loadChildRuns(e){let t=await iW(this.listRuns({id:e.child_run_ids})),r={},a={};for(let e of(t.sort((e,t)=>(e?.dotted_order??"").localeCompare(t?.dotted_order??"")),t)){if(null===e.parent_run_id||void 0===e.parent_run_id)throw Error(`Child run ${e.id} has no parent`);e.parent_run_id in r||(r[e.parent_run_id]=[]),r[e.parent_run_id].push(e),a[e.id]=e}for(let t in e.child_runs=r[e.id]||[],r)t!==e.id&&(a[t].child_runs=r[t]);return e}async *listRuns(e){let{projectId:t,projectName:r,parentRunId:a,traceId:i,referenceExampleId:n,startTime:s,executionOrder:o,runType:l,error:u,id:c,query:h,filter:d,traceFilter:p,treeFilter:f,limit:m}=e,g=[];if(t&&(g=Array.isArray(t)?t:[t]),r){let e=Array.isArray(r)?r:[r],t=await Promise.all(e.map(e=>this.readProject({projectName:e}).then(e=>e.id)));g.push(...t)}let y={session:g.length?g:null,run_type:l,reference_example:n,query:h,filter:d,trace_filter:p,tree_filter:f,execution_order:o,parent_run:a,start_time:s?s.toISOString():null,error:u,id:c,limit:m,trace:i};for await(let e of this._getCursorPaginatedList("/runs/query",y))yield*e}async shareRun(e,{shareId:t}={}){let r={run_id:e,share_token:t||ix()};iJ(e);let a=await this.caller.call(fetch,`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),i=await a.json();if(null===i||!("share_token"in i))throw Error("Invalid response from server");return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(e){iJ(e);let t=await this.caller.call(fetch,`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await iG(t,"unshare run")}async readRunSharedLink(e){iJ(e);let t=await this.caller.call(fetch,`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),r=await t.json();if(null!==r&&"share_token"in r)return`${this.getHostUrl()}/public/${r.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){let r=new URLSearchParams({share_token:e});if(void 0!==t)for(let e of t)r.append("id",e);iJ(e);let a=await this.caller.call(fetch,`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await a.json()}async readDatasetSharedSchema(e,t){if(!e&&!t)throw Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id),iJ(e);let r=await this.caller.call(fetch,`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),a=await r.json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async shareDataset(e,t){if(!e&&!t)throw Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id);let r={dataset_id:e};iJ(e);let a=await this.caller.call(fetch,`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),i=await a.json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){iJ(e);let t=await this.caller.call(fetch,`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await iG(t,"unshare dataset")}async readSharedDataset(e){iJ(e);let t=await this.caller.call(fetch,`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await t.json()}async createProject({projectName:e,description:t=null,metadata:r=null,upsert:a=!1,projectExtra:i=null,referenceDatasetId:n=null}){let s=a?"?upsert=true":"",o=`${this.apiUrl}/sessions${s}`,l=i||{};r&&(l.metadata=r);let u={name:e,extra:l,description:t};null!==n&&(u.reference_dataset_id=n);let c=await this.caller.call(fetch,o,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),h=await c.json();if(!c.ok)throw Error(`Failed to create session ${e}: ${c.status} ${c.statusText}`);return h}async updateProject(e,{name:t=null,description:r=null,metadata:a=null,projectExtra:i=null,endTime:n=null}){let s=`${this.apiUrl}/sessions/${e}`,o=i;a&&(o={...o||{},metadata:a});let l={name:t,extra:o,description:r,end_time:n?new Date(n).toISOString():null},u=await this.caller.call(fetch,s,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),c=await u.json();if(!u.ok)throw Error(`Failed to update project ${e}: ${u.status} ${u.statusText}`);return c}async hasProject({projectId:e,projectName:t}){let r="/sessions",a=new URLSearchParams;if(void 0!==e&&void 0!==t)throw Error("Must provide either projectName or projectId, not both");if(void 0!==e)iJ(e),r+=`/${e}`;else if(void 0!==t)a.append("name",t);else throw Error("Must provide projectName or projectId");let i=await this.caller.call(fetch,`${this.apiUrl}${r}?${a}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});try{let e=await i.json();if(!i.ok)return!1;if(Array.isArray(e))return e.length>0;return!0}catch(e){return!1}}async readProject({projectId:e,projectName:t,includeStats:r}){let a,i="/sessions",n=new URLSearchParams;if(void 0!==e&&void 0!==t)throw Error("Must provide either projectName or projectId, not both");if(void 0!==e)iJ(e),i+=`/${e}`;else if(void 0!==t)n.append("name",t);else throw Error("Must provide projectName or projectId");void 0!==r&&n.append("include_stats",r.toString());let s=await this._get(i,n);if(Array.isArray(s)){if(0===s.length)throw Error(`Project[id=${e}, name=${t}] not found`);a=s[0]}else a=s;return a}async _getTenantId(){if(null!==this._tenantId)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let t of this._getPaginated("/sessions",e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw Error("No projects found to resolve tenant.")}async *listProjects({projectIds:e,name:t,nameContains:r,referenceDatasetId:a,referenceDatasetName:i,referenceFree:n}={}){let s=new URLSearchParams;if(void 0!==e)for(let t of e)s.append("id",t);if(void 0!==t&&s.append("name",t),void 0!==r&&s.append("name_contains",r),void 0!==a)s.append("reference_dataset",a);else if(void 0!==i){let e=await this.readDataset({datasetName:i});s.append("reference_dataset",e.id)}for await(let e of(void 0!==n&&s.append("reference_free",n.toString()),this._getPaginated("/sessions",s)))yield*e}async deleteProject({projectId:e,projectName:t}){let r;if(void 0===e&&void 0===t)throw Error("Must provide projectName or projectId");if(void 0!==e&&void 0!==t)throw Error("Must provide either projectName or projectId, not both");iJ(r=void 0===e?(await this.readProject({projectName:t})).id:e);let a=await this.caller.call(fetch,`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await iG(a,`delete session ${r} (${t})`)}async uploadCsv({csvFile:e,fileName:t,inputKeys:r,outputKeys:a,description:i,dataType:n,name:s}){let o=`${this.apiUrl}/datasets/upload`,l=new FormData;l.append("file",e,t),r.forEach(e=>{l.append("input_keys",e)}),a.forEach(e=>{l.append("output_keys",e)}),i&&l.append("description",i),n&&l.append("data_type",n),s&&l.append("name",s);let u=await this.caller.call(fetch,o,{method:"POST",headers:this.headers,body:l,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(!u.ok){let e=await u.json();if(e.detail&&e.detail.includes("already exists"))throw Error(`Dataset ${t} already exists`);throw Error(`Failed to upload CSV: ${u.status} ${u.statusText}`)}return await u.json()}async createDataset(e,{description:t,dataType:r}={}){let a={name:e,description:t};r&&(a.data_type=r);let i=await this.caller.call(fetch,`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(!i.ok){let t=await i.json();if(t.detail&&t.detail.includes("already exists"))throw Error(`Dataset ${e} already exists`);throw Error(`Failed to create dataset ${i.status} ${i.statusText}`)}return await i.json()}async readDataset({datasetId:e,datasetName:t}){let r,a="/datasets",i=new URLSearchParams({limit:"1"});if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==e)iJ(e),a+=`/${e}`;else if(void 0!==t)i.append("name",t);else throw Error("Must provide datasetName or datasetId");let n=await this._get(a,i);if(Array.isArray(n)){if(0===n.length)throw Error(`Dataset[id=${e}, name=${t}] not found`);r=n[0]}else r=n;return r}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:r,toVersion:a}){let i=e;if(void 0===i&&void 0===t)throw Error("Must provide either datasetName or datasetId");if(void 0!==i&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");void 0===i&&(i=(await this.readDataset({datasetName:t})).id);let n=new URLSearchParams({from_version:"string"==typeof r?r:r.toISOString(),to_version:"string"==typeof a?a:a.toISOString()});return await this._get(`/datasets/${i}/versions/diff`,n)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){let r="/datasets";if(void 0!==e);else if(void 0!==t)e=(await this.readDataset({datasetName:t})).id;else throw Error("Must provide datasetName or datasetId");let a=await this._getResponse(`${r}/${e}/openai_ft`);return(await a.text()).trim().split("\n").map(e=>JSON.parse(e))}async *listDatasets({limit:e=100,offset:t=0,datasetIds:r,datasetName:a,datasetNameContains:i}={}){let n="/datasets",s=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(void 0!==r)for(let e of r)s.append("id",e);for await(let e of(void 0!==a&&s.append("name",a),void 0!==i&&s.append("name_contains",i),this._getPaginated(n,s)))yield*e}async deleteDataset({datasetId:e,datasetName:t}){let r="/datasets",a=e;if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==t&&(a=(await this.readDataset({datasetName:t})).id),void 0!==a)iJ(a),r+=`/${a}`;else throw Error("Must provide datasetName or datasetId");let i=await this.caller.call(fetch,this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(!i.ok)throw Error(`Failed to delete ${r}: ${i.status} ${i.statusText}`);await i.json()}async createExample(e,t,{datasetId:r,datasetName:a,createdAt:i,exampleId:n}){let s=r;if(void 0===s&&void 0===a)throw Error("Must provide either datasetName or datasetId");if(void 0!==s&&void 0!==a)throw Error("Must provide either datasetName or datasetId, not both");void 0===s&&(s=(await this.readDataset({datasetName:a})).id);let o=i||new Date,l={dataset_id:s,inputs:e,outputs:t,created_at:o?.toISOString(),id:n},u=await this.caller.call(fetch,`${this.apiUrl}/examples`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(!u.ok)throw Error(`Failed to create example: ${u.status} ${u.statusText}`);return await u.json()}async createExamples(e){let{inputs:t,outputs:r,sourceRunIds:a,exampleIds:i,datasetId:n,datasetName:s}=e,o=n;if(void 0===o&&void 0===s)throw Error("Must provide either datasetName or datasetId");if(void 0!==o&&void 0!==s)throw Error("Must provide either datasetName or datasetId, not both");void 0===o&&(o=(await this.readDataset({datasetName:s})).id);let l=t.map((e,t)=>({dataset_id:o,inputs:e,outputs:r?r[t]:void 0,id:i?i[t]:void 0,source_run_id:a?a[t]:void 0})),u=await this.caller.call(fetch,`${this.apiUrl}/examples/bulk`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(!u.ok)throw Error(`Failed to create examples: ${u.status} ${u.statusText}`);return await u.json()}async createLLMExample(e,t,r){return this.createExample({input:e},{output:t},r)}async createChatExample(e,t,r){let a=e.map(e=>iT(e)?iI(e):e),i=iT(t)?iI(t):t;return this.createExample({input:a},{output:i},r)}async readExample(e){iJ(e);let t=`/examples/${e}`;return await this._get(t)}async *listExamples({datasetId:e,datasetName:t,exampleIds:r,asOf:a,inlineS3Urls:i}={}){let n;if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==e)n=e;else if(void 0!==t)n=(await this.readDataset({datasetName:t})).id;else throw Error("Must provide a datasetName or datasetId");let s=new URLSearchParams({dataset:n}),o=a?"string"==typeof a?a:a?.toISOString():void 0;o&&s.append("as_of",o);let l=i??!0;if(s.append("inline_s3_urls",l.toString()),void 0!==r)for(let e of r)s.append("id",e);for await(let e of this._getPaginated("/examples",s))yield*e}async deleteExample(e){iJ(e);let t=`/examples/${e}`,r=await this.caller.call(fetch,this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(!r.ok)throw Error(`Failed to delete ${t}: ${r.status} ${r.statusText}`);await r.json()}async updateExample(e,t){iJ(e);let r=await this.caller.call(fetch,`${this.apiUrl}/examples/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(!r.ok)throw Error(`Failed to update example ${e}: ${r.status} ${r.statusText}`);return await r.json()}async evaluateRun(e,t,{sourceInfo:r,loadChildRuns:a,referenceExample:i}={loadChildRuns:!1}){let n;if("string"==typeof e)n=await this.readRun(e,{loadChildRuns:a});else if("object"==typeof e&&"id"in e)n=e;else throw Error(`Invalid run type: ${typeof e}`);null!==n.reference_example_id&&void 0!==n.reference_example_id&&(i=await this.readExample(n.reference_example_id));let s=await t.evaluateRun(n,i),o=r??{};s.evaluatorInfo&&(o={...o,...s.evaluatorInfo});let l=s.targetRunId??n.id;return await this.createFeedback(l,s.key,{score:s?.score,value:s?.value,comment:s?.comment,correction:s?.correction,sourceInfo:o,feedbackSourceType:"model",sourceRunId:s?.sourceRunId})}async createFeedback(e,t,{score:r,value:a,correction:i,comment:n,sourceInfo:s,feedbackSourceType:o="api",sourceRunId:l,feedbackId:u,feedbackConfig:c}){let h={type:o??"api",metadata:s??{}};void 0===l||h?.metadata===void 0||h.metadata.__run||(h.metadata.__run={run_id:l}),h?.metadata!==void 0&&h.metadata.__run?.run_id!==void 0&&iJ(h.metadata.__run.run_id);let d={id:u??ix(),run_id:e,key:t,score:r,value:a,correction:i,comment:n,feedback_source:h,feedbackConfig:c},p=`${this.apiUrl}/feedback`,f=await this.caller.call(fetch,p,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(d),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await iG(f,"create feedback"),d}async updateFeedback(e,{score:t,value:r,correction:a,comment:i}){let n={};null!=t&&(n.score=t),null!=r&&(n.value=r),null!=a&&(n.correction=a),null!=i&&(n.comment=i),iJ(e);let s=await this.caller.call(fetch,`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await iG(s,"update feedback")}async readFeedback(e){iJ(e);let t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){iJ(e);let t=`/feedback/${e}`,r=await this.caller.call(fetch,this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(!r.ok)throw Error(`Failed to delete ${t}: ${r.status} ${r.statusText}`);await r.json()}async *listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:r}={}){let a=new URLSearchParams;if(e&&a.append("run",e.join(",")),t)for(let e of t)a.append("key",e);if(r)for(let e of r)a.append("source",e);for await(let e of this._getPaginated("/feedback",a))yield*e}async createPresignedFeedbackToken(e,t,{expiration:r,feedbackConfig:a}={}){let i={run_id:e,feedback_key:t,feedback_config:a};r?"string"==typeof r?i.expires_at=r:(r?.hours||r?.minutes||r?.days)&&(i.expires_in=r):i.expires_in={hours:3};let n=await this.caller.call(fetch,`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await n.json()}async *listPresignedFeedbackTokens(e){iJ(e);let t=new URLSearchParams({run_id:e});for await(let e of this._getPaginated("/feedback/tokens",t))yield*e}}let i0="0.1.14";class i1 extends ih{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});let{exampleId:t,projectName:r,client:a}=e;this.projectName=r??aP("LANGCHAIN_PROJECT")??aP("LANGCHAIN_SESSION"),this.exampleId=t,this.client=a??new iQ({})}async _convertToCreate(e,t){return{...e,extra:{...e.extra,runtime:await aA()},child_runs:void 0,session_name:this.projectName,reference_example_id:e.parent_run_id?void 0:t}}async persistRun(e){}async onRunCreate(e){let t=await this._convertToCreate(e,this.exampleId);await this.client.createRun(t)}async onRunUpdate(e){let t={end_time:e.end_time,error:e.error,outputs:e.outputs,events:e.events,inputs:e.inputs,trace_id:e.trace_id,dotted_order:e.dotted_order,parent_run_id:e.parent_run_id};await this.client.updateRun(e.id,t)}getRun(e){return this.runMap.get(e)}}async function i2(){return new i1}function i4(){return new aZ.default({autoStart:!0,concurrency:1})}async function i5(e,t){!0===t?await e():(void 0===c&&(c=i4()),c.add(e))}function i9(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}class i3{setHandler(e){return this.setHandlers([e])}}class i6{constructor(e,t,r,a,i,n,s,o){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:a}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:o})}async handleText(e){await Promise.all(this.handlers.map(t=>i5(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(e){console.error(`Error in handler ${t.constructor.name}, handleText: ${e}`)}},t.awaitHandlers)))}}class i8 extends i6{getChild(e){let t=new nr(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=>i5(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){console.error(`Error in handler ${t.constructor.name}, handleRetriever`)}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>i5(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(e){console.error(`Error in handler ${t.constructor.name}, handleRetrieverError: ${e}`)}},t.awaitHandlers)))}}class i7 extends i6{async handleLLMNewToken(e,t,r,a,i,n){await Promise.all(this.handlers.map(r=>i5(async()=>{if(!r.ignoreLLM)try{await r.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,n)}catch(e){console.error(`Error in handler ${r.constructor.name}, handleLLMNewToken: ${e}`)}},r.awaitHandlers)))}async handleLLMError(e){await Promise.all(this.handlers.map(t=>i5(async()=>{if(!t.ignoreLLM)try{await t.handleLLMError?.(e,this.runId,this._parentRunId,this.tags)}catch(e){console.error(`Error in handler ${t.constructor.name}, handleLLMError: ${e}`)}},t.awaitHandlers)))}async handleLLMEnd(e){await Promise.all(this.handlers.map(t=>i5(async()=>{if(!t.ignoreLLM)try{await t.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){console.error(`Error in handler ${t.constructor.name}, handleLLMEnd: ${e}`)}},t.awaitHandlers)))}}class ne extends i6{getChild(e){let t=new nr(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,a,i){await Promise.all(this.handlers.map(t=>i5(async()=>{if(!t.ignoreChain)try{await t.handleChainError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){console.error(`Error in handler ${t.constructor.name}, handleChainError: ${e}`)}},t.awaitHandlers)))}async handleChainEnd(e,t,r,a,i){await Promise.all(this.handlers.map(t=>i5(async()=>{if(!t.ignoreChain)try{await t.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){console.error(`Error in handler ${t.constructor.name}, handleChainEnd: ${e}`)}},t.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>i5(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(e){console.error(`Error in handler ${t.constructor.name}, handleAgentAction: ${e}`)}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>i5(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){console.error(`Error in handler ${t.constructor.name}, handleAgentEnd: ${e}`)}},t.awaitHandlers)))}}class nt extends i6{getChild(e){let t=new nr(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=>i5(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(e){console.error(`Error in handler ${t.constructor.name}, handleToolError: ${e}`)}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>i5(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){console.error(`Error in handler ${t.constructor.name}, handleToolEnd: ${e}`)}},t.awaitHandlers)))}}class nr extends i3{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,a,i,n,s,o){return Promise.all(t.map(async(t,a)=>{let n=0===a&&r?r:ia();return await Promise.all(this.handlers.map(r=>i5(async()=>{if(!r.ignoreLLM)try{await r.handleLLMStart?.(e,[t],n,this._parentRunId,i,this.tags,this.metadata,o)}catch(e){console.error(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`)}},r.awaitHandlers))),new i7(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,r,a,i,n,s,o){return Promise.all(t.map(async(t,a)=>{let n=0===a&&r?r:ia();return await Promise.all(this.handlers.map(r=>i5(async()=>{if(!r.ignoreLLM)try{if(r.handleChatModelStart)await r.handleChatModelStart?.(e,[t],n,this._parentRunId,i,this.tags,this.metadata,o);else if(r.handleLLMStart){let a=am(t);await r.handleLLMStart?.(e,[a],n,this._parentRunId,i,this.tags,this.metadata,o)}}catch(e){console.error(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`)}},r.awaitHandlers))),new i7(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,r=ia(),a,i,n,s){return await Promise.all(this.handlers.map(i=>i5(async()=>{if(!i.ignoreChain)try{await i.handleChainStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,a,s)}catch(e){console.error(`Error in handler ${i.constructor.name}, handleChainStart: ${e}`)}},i.awaitHandlers))),new ne(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,r=ia(),a,i,n,s){return await Promise.all(this.handlers.map(a=>i5(async()=>{if(!a.ignoreAgent)try{await a.handleToolStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,s)}catch(e){console.error(`Error in handler ${a.constructor.name}, handleToolStart: ${e}`)}},a.awaitHandlers))),new nt(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,r=ia(),a,i,n,s){return await Promise.all(this.handlers.map(a=>i5(async()=>{if(!a.ignoreRetriever)try{await a.handleRetrieverStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,s)}catch(e){console.error(`Error in handler ${a.constructor.name}, handleRetrieverStart: ${e}`)}},a.awaitHandlers))),new i8(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}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){for(let r of(this.handlers=[],this.inheritableHandlers=[],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(let t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(e=[],t=!0){let r=new nr(this._parentRunId);for(let e of this.handlers){let t=this.inheritableHandlers.includes(e);r.addHandler(e,t)}for(let e of this.tags){let t=this.inheritableTags.includes(e);r.addTags([e],t)}for(let e of Object.keys(this.metadata)){let t=Object.keys(this.inheritableMetadata).includes(e);r.addMetadata({[e]:this.metadata[e]},t)}for(let a of e)!r.handlers.filter(e=>"console_callback_handler"===e.name).some(e=>e.name===a.name)&&r.addHandler(a,t);return r}static fromHandlers(e){class t extends is{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:ia()}),Object.assign(this,e)}}let r=new this;return r.addHandler(new t),r}static async configure(e,t,r,a,i,n,s){let o;(e||t)&&(Array.isArray(e)||!e?(o=new nr).setHandlers(e?.map(na)??[],!0):o=e,o=o.copy(Array.isArray(t)?t.map(na):t?.handlers,!1));let l="true"===aP("LANGCHAIN_VERBOSE")||s?.verbose,u="true"===aP("LANGCHAIN_TRACING_V2"),c=u||(aP("LANGCHAIN_TRACING")??!1);if(l||c){if(o||(o=new nr),l&&!o.handlers.some(e=>e.name===iy.prototype.name)){let e=new iy;o.addHandler(e,!0)}c&&!o.handlers.some(e=>"langchain_tracer"===e.name)&&u&&o.addHandler(await i2(),!0)}return(r||a)&&o&&(o.addTags(r??[]),o.addTags(a??[],!1)),(i||n)&&o&&(o.addMetadata(i??{}),o.addMetadata(n??{},!1)),o}}function na(e){return"name"in e?e:is.fromMethods(e)}let ni=Object.prototype.hasOwnProperty;function nn(e,t){return ni.call(e,t)}function ns(e){if(Array.isArray(e)){let t=Array(e.length);for(let e=0;e=48&&t<=57){r++;continue}return!1}return!0}function nu(e){return -1===e.indexOf("/")&&-1===e.indexOf("~")?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function nc(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function nh(e){if(void 0===e)return!0;if(e){if(Array.isArray(e)){for(let t=0,r=e.length;t0&&"constructor"==u[h-1]))throw TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&void 0===l&&(void 0===c[s]?l=u.slice(0,h).join("/"):h==d-1&&(l=t.path),void 0!==l&&o(t,0,e,l)),h++,Array.isArray(c)){if("-"===s)s=c.length;else{if(r&&!nl(s))throw new nf("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",n,t,e);nl(s)&&(s=~~s)}if(h>=d){if(r&&"add"===t.op&&s>c.length)throw new nf("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",n,t,e);let a=ny[t.op].call(t,c,s,e);if(!1===a.test)throw new nf("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return a}}else if(h>=d){let r=ng[t.op].call(t,c,s,e);if(!1===r.test)throw new nf("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return r}if(c=c[s],r&&h0)throw new nf('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);else if(("move"===e.op||"copy"===e.op)&&"string"!=typeof e.from)throw new nf("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);else if(("add"===e.op||"replace"===e.op||"test"===e.op)&&void 0===e.value)throw new nf("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);else if(("add"===e.op||"replace"===e.op||"test"===e.op)&&nh(e.value))throw new nf("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);else if(r){if("add"==e.op){var i=e.path.split("/").length,n=a.split("/").length;if(i!==n+1&&i!==n)throw new nf("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if("replace"===e.op||"remove"===e.op||"_get"===e.op){if(e.path!==a)throw new nf("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if("move"===e.op||"copy"===e.op){var s=nE([{op:"_get",path:e.from,value:void 0}],r);if(s&&"OPERATION_PATH_UNRESOLVABLE"===s.name)throw new nf("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}}else throw new nf("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,r)}function nE(e,t,r){try{if(!Array.isArray(e))throw new nf("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)nw(no(t),no(e),r||!0);else{r=r||nO;for(var a=0;a=0;l--){var u=s[l],c=e[u];if(nn(t,u)&&(void 0!==t[u]||void 0===c||!1!==Array.isArray(t))){var h=t[u];"object"==typeof c&&null!=c&&"object"==typeof h&&null!=h&&Array.isArray(c)===Array.isArray(h)?nS(c,h,r,a+"/"+nu(u),i):c!==h&&(i&&r.push({op:"test",path:a+"/"+nu(u),value:no(c)}),r.push({op:"replace",path:a+"/"+nu(u),value:no(h)}))}else Array.isArray(e)===Array.isArray(t)?(i&&r.push({op:"test",path:a+"/"+nu(u),value:no(c)}),r.push({op:"remove",path:a+"/"+nu(u)}),o=!0):(i&&r.push({op:"test",path:a,value:e}),r.push({op:"replace",path:a,value:t}))}if(o||n.length!=s.length)for(var l=0;l{if(t){e.close();return}return e.enqueue(a),r()})}},cancel(){t.releaseLock()}})}static fromAsyncGenerator(e){return new nP({async pull(t){let{value:r,done:a}=await e.next();a&&t.close(),t.enqueue(r)},async cancel(t){await e.return(t)}})}}function nT(e,t=2){let r=Array.from({length:t},()=>[]);return r.map(async function*(t){for(;;)if(0===t.length){let t=await e.next();for(let e of r)e.push(t)}else{if(t[0].done)return;yield t.shift().value}})}function nI(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if("string"==typeof e&&"string"==typeof t)return e+t;if("number"==typeof e&&"number"==typeof t)return e+t;if("concat"in e&&"function"==typeof e.concat)return e.concat(t);if("object"==typeof e&&"object"==typeof t){let r={...e};for(let[e,a]of Object.entries(t))e in r&&!Array.isArray(r[e])?r[e]=nI(r[e],a):r[e]=a;return r}else throw Error(`Cannot concat ${typeof e} and ${typeof t}`)}class nN{constructor(e,t){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,"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,this.setup=new Promise((r,a)=>{this.firstResult=e.next(),t?this.firstResult.then(t).then(r,a):this.firstResult.then(e=>r(void 0),a)})}async next(...e){return this.firstResultUsed?this.generator.next(...e):(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 function nj(e,t,r,...a){let i=new nN(t,r),n=await i.setup;return{output:e(i,n,...a),setup:n}}class nR{constructor(e){Object.defineProperty(this,"ops",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),r=nw({},t);return new nC({ops:t,state:r[r.length-1].newDocument})}}class nC extends nR{constructor(e){super(e),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.state=e.state}concat(e){let t=this.ops.concat(e.ops),r=nw(this.state,e.ops);return new nC({ops:t,state:r[r.length-1].newDocument})}static fromRunLogPatch(e){let t=nw({},e.ops);return new nC({ops:e.ops,state:t[t.length-1].newDocument})}}async function n$(e,t){if("original"===t)throw Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");let{inputs:r}=e;return["retriever","llm","prompt"].includes(e.run_type)?r:1!==Object.keys(r).length||r?.input!==""?r.input:void 0}async function nM(e,t){let{outputs:r}=e;return"original"===t||["retriever","llm","prompt"].includes(e.run_type)?r:void 0!==r&&1===Object.keys(r).length&&r?.output!==void 0?r.output:r}function nL(e){return void 0!==e&&void 0!==e.message}class nU extends ih{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"}),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=nP.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;let t=e.tags??[],r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.run_type)),void 0!==this.includeTags&&(r=r||void 0!==t.find(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.run_type)),void 0!==this.excludeTags&&(r=r&&t.every(e=>!this.excludeTags?.includes(e))),r}async *tapOutputIterable(e,t){for await(let r of t){if(e!==this.rootId){let t=this.keyMapByRunId[e];t&&await this.writer.write(new nR({ops:[{op:"add",path:`/logs/${t}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(void 0===this.rootId&&(this.rootId=e.id,await this.writer.write(new nR({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;void 0===this.counterMapByRunName[e.name]&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;let t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=1===t?e.name:`${e.name}:${t}`;let 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};"streaming_events"===this._schemaFormat&&(r.inputs=await n$(e,this._schemaFormat)),await this.writer.write(new nR({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(void 0===t)return;let r=[];"streaming_events"===this._schemaFormat&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await n$(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await nM(e,this._schemaFormat)}),void 0!==e.end_time&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let a=new nR({ops:r});await this.writer.write(a)}finally{if(e.id===this.rootId){let t=new nR({ops:[{op:"replace",path:"/final_output",value:await nM(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){let a;let i=this.keyMapByRunId[e.id];if(void 0===i)return;a=void 0!==e.inputs.messages?nL(r?.chunk)?r?.chunk:new aa(t):t;let n=new nR({ops:[{op:"add",path:`/logs/${i}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${i}/streamed_output/-`,value:a}]});await this.writer.write(n)}}class nD{getStore(){}run(e,t){t()}}class nF{constructor(){Object.defineProperty(this,"asyncLocalStorage",{enumerable:!0,configurable:!0,writable:!0,value:new nD}),Object.defineProperty(this,"hasBeenInitialized",{enumerable:!0,configurable:!0,writable:!0,value:!1})}getInstance(){return this.asyncLocalStorage}initializeGlobalInstance(e){this.hasBeenInitialized||(this.hasBeenInitialized=!0,this.asyncLocalStorage=e)}}let nB=new nF,nz=25;async function nH(e){return nr.configure(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function nZ(...e){let t={};for(let r of e.filter(e=>!!e))for(let e of Object.keys(r))if("metadata"===e)t[e]={...t[e],...r[e]};else if("tags"===e){let a=t[e]??[];t[e]=[...new Set(a.concat(r[e]??[]))]}else if("configurable"===e)t[e]={...t[e],...r[e]};else if("callbacks"===e){let e=t.callbacks,a=r.callbacks;if(Array.isArray(a)){if(e){if(Array.isArray(e))t.callbacks=e.concat(a);else{let r=e.copy();for(let e of a)r.addHandler(na(e),!0);t.callbacks=r}}else t.callbacks=a}else if(a){if(e){if(Array.isArray(e)){let r=a.copy();for(let t of e)r.addHandler(na(t),!0);t.callbacks=r}else t.callbacks=new nr(a._parentRunId,{handlers:e.handlers.concat(a.handlers),inheritableHandlers:e.inheritableHandlers.concat(a.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(a.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(a.inheritableTags))),metadata:{...e.metadata,...a.metadata}})}else t.callbacks=a}}else{let a=e;t[a]=r[a]??t[a]}return t}let nq=new Set(["string","number","boolean"]);function nG(e){let t=e??nB.getInstance().getStore(),r={tags:[],metadata:{},callbacks:void 0,recursionLimit:25,runId:void 0};if(t&&(r={...r,...t}),t?.configurable)for(let e of Object.keys(t.configurable))nq.has(typeof t.configurable[e])&&!r.metadata?.[e]&&(r.metadata||(r.metadata={}),r.metadata[e]=t.configurable[e]);return r}function nW(e={},{callbacks:t,maxConcurrency:r,recursionLimit:a,runName:i,configurable:n,runId:s}={}){let o=nG(e);return void 0!==t&&(delete o.runName,o.callbacks=t),void 0!==a&&(o.recursionLimit=a),void 0!==r&&(o.maxConcurrency=r),void 0!==i&&(o.runName=i),void 0!==n&&(o.configurable={...o.configurable,...n}),void 0!==s&&delete o.runId,o}class nK extends ih{constructor({config:e,onStart:t,onEnd:r,onError:a}){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=a}persistRun(e){return Promise.resolve()}async onRunCreate(e){!this.rootId&&(this.rootId=e.id,this.argOnStart&&(1===this.argOnStart.length?await this.argOnStart(e):2===this.argOnStart.length&&await this.argOnStart(e,this.config)))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&(1===this.argOnError.length?await this.argOnError(e):2===this.argOnError.length&&await this.argOnError(e,this.config)):this.argOnEnd&&(1===this.argOnEnd.length?await this.argOnEnd(e):2===this.argOnEnd.length&&await this.argOnEnd(e,this.config)))}}function nJ(e){return!!e&&e.lc_runnable}class nY{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=void 0===this.includeNames&&void 0===this.includeTypes&&void 0===this.includeTags,a=e.tags??[];return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(t)),void 0!==this.includeTags&&(r=r||a.some(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(t)),void 0!==this.excludeTags&&(r=r&&a.every(e=>!this.excludeTags?.includes(e))),r}}var nV=r(50084);let nX=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,nQ=function(e){return"string"==typeof e&&nX.test(e)};function n0(e){return nJ(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...(0,nV.Ik)(e.data.schema),title:e.data.name}}}class n1{constructor(){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]})}toJSON(){let e={};return Object.values(this.nodes).forEach((t,r)=>{e[t.id]=nQ(t.id)?r:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...n0(t)})),edges:this.edges.map(t=>t.data?{source:e[t.source],target:e[t.target],data:t.data}:{source:e[t.source],target:e[t.target]})}}addNode(e,t){if(void 0!==t&&void 0!==this.nodes[t])throw Error(`Node with id ${t} already exists`);let r=t||ia(),a={id:r,data:e};return this.nodes[r]=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){if(void 0===this.nodes[e.id])throw Error(`Source node ${e.id} not in graph`);if(void 0===this.nodes[t.id])throw Error(`Target node ${t.id} not in graph`);let a={source:e.id,target:t.id,data:r};return this.edges.push(a),a}firstNode(){let e=new Set(this.edges.map(e=>e.target)),t=[];return Object.values(this.nodes).forEach(r=>{e.has(r.id)||t.push(r)}),t[0]}lastNode(){let e=new Set(this.edges.map(e=>e.source)),t=[];return Object.values(this.nodes).forEach(r=>{e.has(r.id)||t.push(r)}),t[0]}extend(e){Object.entries(e.nodes).forEach(([e,t])=>{this.nodes[e]=t}),this.edges=[...this.edges,...e.edges]}trimFirstNode(){let e=this.firstNode();if(e){let t=this.edges.filter(t=>t.source===e.id);(1===Object.keys(this.nodes).length||1===t.length)&&this.removeNode(e)}}trimLastNode(){let e=this.lastNode();if(e){let t=this.edges.filter(t=>t.target===e.id);(1===Object.keys(this.nodes).length||1===t.length)&&this.removeNode(e)}}}function n2(e,t){return!e||Array.isArray(e)||e instanceof Date||"object"!=typeof e?{[t]:e}:e}class n4 extends r5{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(e){let t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}bind(e){return new n5({bound:this,kwargs:e,config:{}})}map(){return new n9({bound:this})}withRetry(e){return new n3({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new n5({bound:this,config:e,kwargs:{}})}withFallbacks(e){return new se({runnable:this,fallbacks:e.fallbacks})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw 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(nG);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");let r=Object.fromEntries(Object.entries(e).filter(([e])=>"runId"!==e));return Array.from({length:t},(t,a)=>nG(0===a?e:r))}return Array.from({length:t},()=>nG(e))}async batch(e,t,r){let a=this._getOptionsList(t??{},e.length),i=new aW({maxConcurrency:a[0]?.maxConcurrency??r?.maxConcurrency,onFailedAttempt:e=>{throw e}});return Promise.all(e.map((e,t)=>i.call(async()=>{try{return await this.invoke(e,a[t])}catch(e){if(r?.returnExceptions)return e;throw e}})))}async *_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){let r=new nN(this._streamIterator(e,nG(t)));return await r.setup,nP.fromAsyncGenerator(r)}_separateRunnableConfigFromCallOptions(e){let t;t=void 0===e?nG(e):nG({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId});let 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,[t,r]}async _callWithConfig(e,t,r){let a;let i=nG(r),n=await nH(i),s=await n?.handleChainStart(this.toJSON(),n2(t,"input"),i.runId,i?.runType,void 0,void 0,i?.runName??this.getName());delete i.runId;try{a=await e.call(this,t,i,s)}catch(e){throw await s?.handleChainError(e),e}return await s?.handleChainEnd(n2(a,"output")),a}async _batchWithConfig(e,t,r,a){let i;let n=this._getOptionsList(r??{},t.length),s=await Promise.all(n.map(nH)),o=await Promise.all(s.map(async(e,r)=>{let a=await e?.handleChainStart(this.toJSON(),n2(t[r],"input"),n[r].runId,n[r].runType,void 0,void 0,n[r].runName??this.getName());return delete n[r].runId,a}));try{i=await e.call(this,t,n,o,a)}catch(e){throw await Promise.all(o.map(t=>t?.handleChainError(e))),e}return await Promise.all(o.map(e=>e?.handleChainEnd(n2(i,"output")))),i}async *_transformStreamWithConfig(e,t,r){let a,i,n;let s=!0,o=!0,l=nG(r),u=await nH(l);async function*c(){for await(let t of e){if(s){if(void 0===a)a=t;else try{a=nI(a,t)}catch{a=void 0,s=!1}}yield t}}try{let e=await nj(t.bind(this),c(),async()=>u?.handleChainStart(this.toJSON(),{input:""},l.runId,l.runType,void 0,void 0,l.runName??this.getName()),l);delete l.runId,n=e.setup;let r=e=>"log_stream_tracer"===e.name,a=n?.handlers.find(r),s=e.output;for await(let t of(void 0!==a&&void 0!==n&&(s=await a.tapOutputIterable(n.runId,e.output)),s))if(yield t,o){if(void 0===i)i=t;else try{i=nI(i,t)}catch{i=void 0,o=!1}}}catch(e){throw await n?.handleChainError(e,void 0,void 0,void 0,{inputs:n2(a,"input")}),e}await n?.handleChainEnd(i??{},void 0,void 0,void 0,{inputs:n2(a,"input")})}getGraph(e){let t=new n1,r=t.addNode({name:`${this.getName()}Input`,schema:a6.z.any()}),a=t.addNode(this),i=t.addNode({name:`${this.getName()}Output`,schema:a6.z.any()});return t.addEdge(r,a),t.addEdge(a,i),t}pipe(e){return new n6({first:this,last:st(e)})}pick(e){return this.pipe(new sa(e))}assign(e){return this.pipe(new sr(new n8({steps:e})))}async *transform(e,t){let r;for await(let t of e)r=void 0===r?t:nI(r,t);yield*this._streamIterator(r,nG(t))}async *streamLog(e,t,r){let a=new nU({...r,autoClose:!1,_schemaFormat:"original"}),i=nG(t);yield*this._streamLog(e,a,i)}async *_streamLog(e,t,r){let{callbacks:a}=r;if(void 0===a)r.callbacks=[t];else if(Array.isArray(a))r.callbacks=a.concat([t]);else{let e=a.copy();e.inheritableHandlers.push(t),r.callbacks=e}let i=this.stream(e,r),n=async function(){try{for await(let e of(await i)){let r=new nR({ops:[{op:"add",path:"/streamed_output/-",value:e}]});await t.writer.write(r)}}finally{await t.writer.close()}}();try{for await(let e of t)yield e}finally{await n}}async *streamEvents(e,t,r){let a;if("v1"!==t.version)throw Error('Only version "v1" of the events schema is currently supported.');let i=!1,n=nG(t),s=n.tags??[],o=n.metadata??{},l=n.runName??this.getName(),u=new nU({...r,autoClose:!1,_schemaFormat:"streaming_events"}),c=new nY({...r});for await(let t of this._streamLog(e,u,n)){if(void 0===(a=a?a.concat(t):nC.fromRunLogPatch(t)).state)throw Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!i){i=!0;let t={...a.state},r={run_id:t.id,event:`on_${t.type}_start`,name:l,tags:s,metadata:o,data:{input:e}};c.includeEvent(r,t.type)&&(yield r)}for(let e of[...new Set(t.ops.filter(e=>e.path.startsWith("/logs/")).map(e=>e.path.split("/")[2]))]){let t;let r={},i=a.state.logs[e];if("start"==(t=void 0===i.end_time?i.streamed_output.length>0?"stream":"start":"end"))void 0!==i.inputs&&(r.input=i.inputs);else if("end"===t)void 0!==i.inputs&&(r.input=i.inputs),r.output=i.final_output;else if("stream"===t){let e=i.streamed_output.length;if(1!==e)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${i.name}"`);r={chunk:i.streamed_output[0]},i.streamed_output=[]}yield{event:`on_${i.type}_${t}`,name:i.name,run_id:i.id,tags:i.tags,metadata:i.metadata,data:r}}let{state:r}=a;if(r.streamed_output.length>0){let e=r.streamed_output.length;if(1!==e)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${r.name}"`);let t={chunk:r.streamed_output[0]};r.streamed_output=[];let a={event:`on_${r.type}_stream`,run_id:r.id,tags:s,metadata:o,name:l,data:t};c.includeEvent(a,r.type)&&(yield a)}}let h=a?.state;if(void 0!==h){let e={event:`on_${h.type}_end`,name:l,run_id:h.id,tags:s,metadata:o,data:{output:h.final_output}};c.includeEvent(e,h.type)&&(yield e)}}static isRunnable(e){return nJ(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new n5({bound:this,config:{},configFactories:[a=>({callbacks:[new nK({config:a,onStart:e,onEnd:t,onError:r})]})]})}}class n5 extends n4{static lc_name(){return"RunnableBinding"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"configFactories",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){let t=nZ(this.config,...e);return nZ(t,...this.configFactories?await Promise.all(this.configFactories.map(async e=>await e(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 this.constructor({bound:this.bound.withRetry(e),kwargs:this.kwargs,config:this.config})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(nG(t),this.kwargs))}async batch(e,t,r){let a=Array.isArray(t)?await Promise.all(t.map(async e=>this._mergeConfig(nG(e),this.kwargs))):await this._mergeConfig(nG(t),this.kwargs);return this.bound.batch(e,a,r)}async *_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(nG(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(nG(t),this.kwargs))}async *transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(nG(t),this.kwargs))}async *streamEvents(e,t,r){yield*this.bound.streamEvents(e,{...await this._mergeConfig(nG(t),this.kwargs),version:t.version},r)}static isRunnableBinding(e){return e.bound&&n4.isRunnable(e.bound)}withListeners({onStart:e,onEnd:t,onError:r}){return new n5({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[a=>({callbacks:[new nK({config:a,onStart:e,onEnd:t,onError:r})]})]})}}class n9 extends n4{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 n9({bound:this.bound.bind(e)})}async invoke(e,t){return this._callWithConfig(this._invoke,e,t)}async _invoke(e,t,r){return this.bound.batch(e,nW(t,{callbacks:r?.getChild()}))}withListeners({onStart:e,onEnd:t,onError:r}){return new n9({bound:this.bound.withListeners({onStart:e,onEnd:t,onError:r})})}}class n3 extends n5{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){let a=e>1?`retry:attempt:${e}`:void 0;return nW(t,{callbacks:r?.getChild(a)})}async _invoke(e,t,r){return aH(a=>super.invoke(e,this._patchConfigForRetry(a,t,r)),{onFailedAttempt:this.onFailedAttempt,retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke,e,t)}async _batch(e,t,r,a){let i={};try{await aH(async n=>{let s;let o=e.map((e,t)=>t).filter(e=>void 0===i[e.toString()]||i[e.toString()]instanceof Error),l=o.map(t=>e[t]),u=o.map(e=>this._patchConfigForRetry(n,t?.[e],r?.[e])),c=await super.batch(l,u,{...a,returnExceptions:!0});for(let e=0;eparseInt(e,10)-parseInt(t,10)).map(e=>i[parseInt(e,10)])}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}}class n6 extends n4{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,"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}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){let r;let a=nG(t),i=await nH(a),n=await i?.handleChainStart(this.toJSON(),n2(e,"input"),a.runId,void 0,void 0,void 0,a?.runName);delete a.runId;let s=e;try{let e=[this.first,...this.middle];for(let t=0;t{let i=await t?.handleChainStart(this.toJSON(),n2(e[r],"input"),a[r].runId,void 0,void 0,void 0,a[r].runName);return delete a[r].runId,i})),s=e;try{for(let e=0;e{let i=t?.getChild(`seq:step:${e+1}`);return nW(a[r],{callbacks:i})}),r)}}catch(e){throw await Promise.all(n.map(t=>t?.handleChainError(e))),e}return await Promise.all(n.map(e=>e?.handleChainEnd(n2(s,"output")))),s}async *_streamIterator(e,t){let r;let a=await nH(t),i=await a?.handleChainStart(this.toJSON(),n2(e,"input"),void 0,void 0,void 0,void 0,t?.runName),n=[this.first,...this.middle,this.last],s=!0;async function*o(){yield e}try{let e=n[0].transform(o(),nW(t,{callbacks:i?.getChild("seq:step:1")}));for(let r=1;r{let n=a.getGraph(e);0!==i&&n.trimFirstNode(),i!==this.steps.length-1&&n.trimLastNode(),t.extend(n);let s=n.firstNode();if(!s)throw Error(`Runnable ${a} has no first node`);r&&t.addEdge(r,s),r=n.lastNode()}),t}pipe(e){return new n6(n6.isRunnableSequence(e)?{first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}:{first:this.first,middle:[...this.middle,this.last],last:st(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&n4.isRunnable(e)}static from([e,...t],r){return new n6({first:st(e),middle:t.slice(0,-1).map(st),last:st(t[t.length-1]),name:r})}}class n8 extends n4{static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}constructor(e){for(let[t,r]of(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={},Object.entries(e.steps)))this.steps[t]=st(r)}static from(e){return new n8({steps:e})}async invoke(e,t){let r=nG(t),a=await nH(r),i=await a?.handleChainStart(this.toJSON(),{input:e},r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;let n={};try{await Promise.all(Object.entries(this.steps).map(async([t,a])=>{n[t]=await a.invoke(e,nW(r,{callbacks:i?.getChild(`map:key:${t}`)}))}))}catch(e){throw await i?.handleChainError(e),e}return await i?.handleChainEnd(n),n}async *_transform(e,t,r){let a={...this.steps},i=nT(e,Object.keys(a).length),n=new Map(Object.entries(a).map(([e,a],n)=>{let s=a.transform(i[n],nW(r,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,s.next().then(t=>({key:e,gen:s,result:t}))]}));for(;n.size;){let{key:e,result:t,gen:r}=await Promise.race(n.values());n.delete(e),t.done||(yield{[e]:t.value},n.set(e,r.next().then(t=>({key:e,gen:r,result:t}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let a=new nN(this.transform(r(),t));return await a.setup,nP.fromAsyncGenerator(a)}}class n7 extends n4{static lc_name(){return"RunnableLambda"}constructor(e){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}),this.func=e.func}static from(e){return new n7({func:e})}async _invoke(e,t,r){return new Promise((a,i)=>{let n=nW(t,{callbacks:r?.getChild(),recursionLimit:(t?.recursionLimit??nz)-1});nB.getInstance().run(n,async()=>{try{let r=await this.func(e,{...n,config:n});if(r&&n4.isRunnable(r)){if(t?.recursionLimit===0)throw Error("Recursion limit reached.");r=await r.invoke(e,{...n,recursionLimit:(n.recursionLimit??nz)-1})}a(r)}catch(e){i(e)}})})}async invoke(e,t){return this._callWithConfig(this._invoke,e,t)}async *_transform(e,t,r){let a;for await(let t of e)if(void 0===a)a=t;else try{a=nI(a,t)}catch(e){a=t}let i=await new Promise((e,t)=>{nB.getInstance().run(r,async()=>{try{let t=await this.func(a,{...r,config:r});e(t)}catch(e){t(e)}})});if(i&&n4.isRunnable(i)){if(r?.recursionLimit===0)throw Error("Recursion limit reached.");for await(let e of(await i.stream(a,nW(r,{callbacks:t?.getChild(),recursionLimit:(r?.recursionLimit??nz)-1}))))yield e}else yield i}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let a=new nN(this.transform(r(),t));return await a.setup,nP.fromAsyncGenerator(a)}}class se extends n4{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(){for(let e of(yield this.runnable,this.fallbacks))yield e}async invoke(e,t){let r;let a=await nr.configure(t?.callbacks,void 0,t?.tags,void 0,t?.metadata),i=await a?.handleChainStart(this.toJSON(),n2(e,"input"),t?.runId,void 0,void 0,void 0,t?.runName);for(let a of(delete t?.runId,this.runnables()))try{let r=await a.invoke(e,nW(t,{callbacks:i?.getChild()}));return await i?.handleChainEnd(n2(r,"output")),r}catch(e){void 0===r&&(r=e)}if(void 0===r)throw Error("No error stored at end of fallback.");throw await i?.handleChainError(r),r}async batch(e,t,r){let a;if(r?.returnExceptions)throw Error("Not implemented.");let i=this._getOptionsList(t??{},e.length),n=await Promise.all(i.map(e=>nr.configure(e?.callbacks,void 0,e?.tags,void 0,e?.metadata))),s=await Promise.all(n.map(async(t,r)=>{let a=await t?.handleChainStart(this.toJSON(),n2(e[r],"input"),i[r].runId,void 0,void 0,void 0,i[r].runName);return delete i[r].runId,a}));for(let t of this.runnables())try{let a=await t.batch(e,s.map((e,t)=>nW(i[t],{callbacks:e?.getChild()})),r);return await Promise.all(s.map((e,t)=>e?.handleChainEnd(n2(a[t],"output")))),a}catch(e){void 0===a&&(a=e)}if(!a)throw Error("No error stored at end of fallbacks.");throw await Promise.all(s.map(e=>e?.handleChainError(a))),a}}function st(e){if("function"==typeof e)return new n7({func:e});if(n4.isRunnable(e))return e;if(Array.isArray(e)||"object"!=typeof e)throw Error(`Expected a Runnable, function or object. Instead got an unsupported type.`);{let t={};for(let[r,a]of Object.entries(e))t[r]=st(a);return new n8({steps:t})}}class sr extends n4{static lc_name(){return"RunnableAssign"}constructor(e){e instanceof n8&&(e={mapper:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mapper=e.mapper}async invoke(e,t){let r=await this.mapper.invoke(e,t);return{...e,...r}}async *_transform(e,t,r){let a=this.mapper.getStepsKeys(),[i,n]=nT(e),s=this.mapper.transform(n,nW(r,{callbacks:t?.getChild()})),o=s.next();for await(let e of i){if("object"!=typeof e||Array.isArray(e))throw Error(`RunnableAssign can only be used with objects as input, got ${typeof e}`);let t=Object.fromEntries(Object.entries(e).filter(([e])=>!a.includes(e)));Object.keys(t).length>0&&(yield t)}for await(let e of(yield(await o).value,s))yield e}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let a=new nN(this.transform(r(),t));return await a.setup,nP.fromAsyncGenerator(a)}}class sa extends n4{static lc_name(){return"RunnablePick"}constructor(e){("string"==typeof e||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("string"==typeof this.keys)return e[this.keys];{let t=this.keys.map(t=>[t,e[t]]).filter(e=>void 0!==e[1]);return 0===t.length?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async *_transform(e){for await(let t of e){let e=await this._pick(t);void 0!==e&&(yield e)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let a=new nN(this.transform(r(),t));return await a.setup,nP.fromAsyncGenerator(a)}}let si=e=>e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e,sn=()=>!1;class ss extends n4{get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.verbose=e.verbose??sn(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}}class so extends ss{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}constructor({callbacks:e,callbackManager:t,...r}){super({callbacks:e??t,...r}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_encoding",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),"object"==typeof r.cache?this.cache=r.cache:r.cache?this.cache=aD.global():this.cache=void 0,this.caller=new aW(r??{})}async getNumTokens(e){if("string"!=typeof e)return 0;let t=Math.ceil(e.length/4);if(!this._encoding)try{this._encoding=await a3("modelName"in this?si(this.modelName):"gpt2")}catch(e){console.warn("Failed to calculate number of tokens, falling back to approximate count",e)}if(this._encoding)try{t=this._encoding.encode(e).length}catch(e){console.warn("Failed to calculate number of tokens, falling back to approximate count",e)}return t}static _convertInputToPromptValue(e){return"string"==typeof e?new aB(e):Array.isArray(e)?new az(e.map(ap)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall(e){return Object.entries({...this._identifyingParams(),...e,_type:this._llmType(),_model:this._modelType()}).filter(([e,t])=>void 0!==t).map(([e,t])=>`${e}:${JSON.stringify(t)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw Error("Use .toJSON() instead")}}class sl extends so{constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","chat_models",this._llmType()]})}_separateRunnableConfigFromCallOptions(e){let[t,r]=super._separateRunnableConfigFromCallOptions(e);return r?.timeout&&!r.signal&&(r.signal=AbortSignal.timeout(r.timeout)),[t,r]}async invoke(e,t){let r=sl._convertInputToPromptValue(e);return(await this.generatePrompt([r],t,t?.callbacks)).generations[0][0].message}async *_streamResponseChunks(e,t,r){throw Error("Not implemented.")}async *_streamIterator(e,t){if(this._streamResponseChunks===sl.prototype._streamResponseChunks)yield this.invoke(e,t);else{let r;let a=sl._convertInputToPromptValue(e).toChatMessages(),[i,n]=this._separateRunnableConfigFromCallOptions(t),s=await nr.configure(i.callbacks,this.callbacks,i.tags,this.tags,i.metadata,this.metadata,{verbose:this.verbose}),o={options:n,invocation_params:this?.invocationParams(n),batch_size:1},l=await s?.handleChatModelStart(this.toJSON(),[a],i.runId,void 0,o,void 0,void 0,i.runName);try{for await(let e of this._streamResponseChunks(a,n,l?.[0]))e.message.response_metadata={...e.generationInfo,...e.message.response_metadata},yield e.message,r=r?r.concat(e):e}catch(e){throw await Promise.all((l??[]).map(t=>t?.handleLLMError(e))),e}await Promise.all((l??[]).map(e=>e?.handleLLMEnd({generations:[[r]]})))}}async _generateUncached(e,t,r){let a=e.map(e=>e.map(ap)),i=await nr.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}),n={options:t,invocation_params:this?.invocationParams(t),batch_size:1},s=await i?.handleChatModelStart(this.toJSON(),a,r.runId,void 0,n,void 0,void 0,r.runName),o=await Promise.allSettled(a.map((e,r)=>this._generate(e,{...t,promptIndex:r},s?.[r]))),l=[],u=[];await Promise.all(o.map(async(e,t)=>{if("fulfilled"!==e.status)return await s?.[t]?.handleLLMError(e.reason),Promise.reject(e.reason);{let r=e.value;for(let e of r.generations)e.message.response_metadata={...e.generationInfo,...e.message.response_metadata};return 1===r.generations.length&&(r.generations[0].message.response_metadata={...r.llmOutput,...r.generations[0].message.response_metadata}),l[t]=r.generations,u[t]=r.llmOutput,s?.[t]?.handleLLMEnd({generations:[r.generations],llmOutput:r.llmOutput})}}));let c={generations:l,llmOutput:u.length?this._combineLLMOutput?.(...u):void 0};return Object.defineProperty(c,ay,{value:s?{runIds:s?.map(e=>e.runId)}:void 0,configurable:!0}),c}async _generateCached({messages:e,cache:t,llmStringKey:r,parsedOptions:a,handledOptions:i}){let n=e.map(e=>e.map(ap)),s=await nr.configure(i.callbacks,this.callbacks,i.tags,this.tags,i.metadata,this.metadata,{verbose:this.verbose}),o={options:a,invocation_params:this?.invocationParams(a),batch_size:1,cached:!0},l=await s?.handleChatModelStart(this.toJSON(),n,i.runId,void 0,o,void 0,void 0,i.runName),u=[],c=(await Promise.allSettled(n.map(async(e,a)=>{let i=sl._convertInputToPromptValue(e).toString(),n=await t.lookup(i,r);return null==n&&u.push(a),n}))).map((e,t)=>({result:e,runManager:l?.[t]})).filter(({result:e})=>"fulfilled"===e.status&&null!=e.value||"rejected"===e.status),h=[];await Promise.all(c.map(async({result:e,runManager:t},r)=>{if("fulfilled"!==e.status)return await t?.handleLLMError(e.reason),Promise.reject(e.reason);{let a=e.value;return h[r]=a,a.length&&await t?.handleLLMNewToken(a[0].text),t?.handleLLMEnd({generations:[a]})}}));let d={generations:h,missingPromptIndices:u};return Object.defineProperty(d,ay,{value:l?{runIds:l?.map(e=>e.runId)}:void 0,configurable:!0}),d}async generate(e,t,r){let a;a=Array.isArray(t)?{stop:t}:t;let i=e.map(e=>e.map(ap)),[n,s]=this._separateRunnableConfigFromCallOptions(a);if(n.callbacks=n.callbacks??r,!this.cache)return this._generateUncached(i,s,n);let{cache:o}=this,l=this._getSerializedCacheKeyParametersForCall(s),{generations:u,missingPromptIndices:c}=await this._generateCached({messages:i,cache:o,llmStringKey:l,parsedOptions:s,handledOptions:n}),h={};if(c.length>0){let e=await this._generateUncached(c.map(e=>i[e]),s,n);await Promise.all(e.generations.map(async(e,t)=>{let r=c[t];u[r]=e;let a=sl._convertInputToPromptValue(i[r]).toString();return o.update(a,l,e)})),h=e.llmOutput??{}}return{generations:u,llmOutput:h}}invocationParams(e){return{}}_modelType(){return"base_chat_model"}serialize(){return{...this.invocationParams(),_type:this._llmType(),_model:this._modelType()}}async generatePrompt(e,t,r){let a=e.map(e=>e.toChatMessages());return this.generate(a,t,r)}async call(e,t,r){return(await this.generate([e.map(ap)],t,r)).generations[0][0].message}async callPrompt(e,t,r){let a=e.toChatMessages();return this.call(a,t,r)}async predictMessages(e,t,r){return this.call(e,t,r)}async predict(e,t,r){let a=new ae(e),i=await this.call([a],t,r);if("string"!=typeof i.content)throw Error("Cannot use predict when output is not a string.");return i.content}}function su(e){return{name:e.name,description:e.description,parameters:(0,nV.Ik)(e.schema)}}function sc(e){return{type:"function",function:su(e)}}class sh extends n4{static lc_name(){return"RunnablePassthrough"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e&&(this.func=e.func)}async invoke(e,t){let r=nG(t);return this.func&&await this.func(e,r),this._callWithConfig(e=>Promise.resolve(e),e,r)}async *transform(e,t){let r;let a=nG(t),i=!0;for await(let t of this._transformStreamWithConfig(e,e=>e,a))if(yield t,i){if(void 0===r)r=t;else try{r=nI(r,t)}catch{r=void 0,i=!1}}this.func&&void 0!==r&&await this.func(r,a)}static assign(e){return new sr(new n8({steps:e}))}}class sd extends n4{parseResultWithPrompt(e,t,r){return this.parseResult(e,r)}_baseMessageToString(e){return"string"==typeof e.content?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return"string"==typeof e?this._callWithConfig(async(e,t)=>this.parseResult([{text:e}],t?.callbacks),e,{...t,runType:"parser"}):this._callWithConfig(async(e,t)=>this.parseResult([{message:e,text:this._baseMessageToString(e)}],t?.callbacks),e,{...t,runType:"parser"})}}class sp extends sd{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,r){return this.parse(e,r)}_type(){throw Error("_type not implemented")}}class sf extends Error{constructor(e,t,r,a=!1){if(super(e),Object.defineProperty(this,"llmOutput",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"observation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sendToLLM",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.llmOutput=t,this.observation=r,this.sendToLLM=a,a&&(void 0===r||void 0===t))throw Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true")}}function sm(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=e.length;if(r!==t.length)return!1;for(let a=0;a=1&&a<=12&&i>=1&&i<=(2==a&&s_(r)?29:sy[a])}function sv(e,t){let r=t.match(sb);if(!r)return!1;let a=+r[1],i=+r[2],n=+r[3],s=!!r[5];return(a<=23&&i<=59&&n<=59||23==a&&59==i&&60==n)&&(!e||s)}let sO=/t|\s/i,sE=/\/|:/,sk=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,sx=/[^\\]\\Z/;class sS extends sp{async *_transform(e){for await(let t of e)"string"==typeof t?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async *transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:"parser"})}}class sA extends sS{constructor(e){super(e),Object.defineProperty(this,"diff",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.diff=e?.diff??this.diff}async *_transform(e){let t,r;for await(let a of e){let e;if("string"!=typeof a&&"string"!=typeof a.content)throw Error("Cannot handle non-string output.");if(ad(a)){if("string"!=typeof a.content)throw Error("Cannot handle non-string message output.");e=new a_({message:a,text:a.content})}else if(ah(a)){if("string"!=typeof a.content)throw Error("Cannot handle non-string message output.");e=new a_({message:a.toChunk(),text:a.content})}else e=new ab({text:a});r=void 0===r?e:r.concat(e);let i=await this.parsePartialResult([r]);null==i||sm(i,t)||(this.diff?yield this._diff(t,i):yield i,t=i)}}}class sP extends sp{static lc_name(){return"StructuredOutputParser"}toJSON(){return this.toJSONNotImplemented()}constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","structured"]})}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){return new this(a6.z.object(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,a6.z.string().describe(t)]))))}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance. "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents. For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}}} would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings. Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted. Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas! Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock: \`\`\`json ${JSON.stringify((0,nV.Ik)(this.schema))} \`\`\` `}async parse(e){try{let t=e.includes("```")?e.trim().split(/```(?:json)?/)[1]:e.trim();return await this.schema.parseAsync(JSON.parse(t))}catch(t){throw new sf(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}}class sT extends sA{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}static lc_name(){return"JsonOutputParser"}_diff(e,t){return t?e?nA(e,t):[{op:"replace",path:"",value:t}]:void 0}async parsePartialResult(e){return sI(e[0].text)}async parse(e){return sI(e,JSON.parse)}getFormatInstructions(){return""}}function sI(e,t=sN){e=e.trim();let r=/```(json)?(.*)```/s.exec(e);return t(r?r[2]:e)}function sN(e){if(void 0===e)return null;try{return JSON.parse(e)}catch(e){}let t="",r=[],a=!1,i=!1;for(let n of e){if(a)'"'!==n||i?"\n"!==n||i?i="\\"===n&&!i:n="\\n":a=!1;else if('"'===n)a=!0,i=!1;else if("{"===n)r.push("}");else if("["===n)r.push("]");else if("}"===n||"]"===n){if(!r||r[r.length-1]!==n)return null;r.pop()}t+=n}a&&(t+='"');for(let e=r.length-1;e>=0;e-=1)t+=r[e];try{return JSON.parse(t)}catch(e){return null}}let sj=e=>{if(0===Object.keys(e).length)return{};let t={};return e.children.length>0?t[e.name]=e.children.map(sj):t[e.name]=e.text??void 0,t};class sR extends sd{static lc_name(){return"JsonOutputToolsParser"}constructor(e){super(e),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.returnId=e?.returnId??this.returnId}async parseResult(e){let t=e[0].message.additional_kwargs.tool_calls;if(!t)throw Error(`No tools_call in message ${JSON.stringify(e)}`);let r=JSON.parse(JSON.stringify(t)),a=[];for(let e of r)if(void 0!==e.function){let t={type:e.function.name,args:JSON.parse(e.function.arguments)};this.returnId&&(t.id=e.id),Object.defineProperty(t,"name",{get(){return this.type}}),Object.defineProperty(t,"arguments",{get(){return this.args}}),a.push(t)}return a}}class sC extends sd{static lc_name(){return"JsonOutputKeyToolsParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"initialParser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.initialParser=new sR(e),this.zodSchema=e.zodSchema}async _validateResult(e){if(void 0===this.zodSchema)return e;let t=await this.zodSchema.safeParseAsync(e);if(t.success)return t.data;throw new sf(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error.errors)}`,JSON.stringify(e,null,2))}async parseResult(e){let t=(await this.initialParser.parseResult(e)).filter(e=>e.type===this.keyName),r=t;return(this.returnId||(r=t.map(e=>e.args)),this.returnSingle)?this._validateResult(r[0]):await Promise.all(r.map(e=>this._validateResult(e)))}}function s$(e){let{azureOpenAIApiDeploymentName:t,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:a,azureOpenAIBasePath:i,baseURL:n}=e;if(a&&i&&t)return`${i}/${t}`;if(a){if(!r)throw Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!t)throw Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${r}.openai.azure.com/openai/deployments/${t}`}return n}function sM(e){let t;return e.constructor.name===rz.name?(t=Error(e.message)).name="TimeoutError":e.constructor.name===rH.name?(t=Error(e.message)).name="AbortError":t=e,t}function sL(e){return void 0!==e.anyOf&&Array.isArray(e.anyOf)}function sU(e){let t=["namespace functions {",""];for(let r of e)r.description&&t.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(t.push(`type ${r.name} = (_: {`),t.push(sD(r.parameters,0)),t.push("}) => any;")):t.push(`type ${r.name} = () => any;`),t.push("");return t.push("} // namespace functions"),t.join("\n")}function sD(e,t){let r=[];for(let[a,i]of Object.entries(e.properties??{}))i.description&&t<2&&r.push(`// ${i.description}`),e.required?.includes(a)?r.push(`${a}: ${sF(i,t)},`):r.push(`${a}?: ${sF(i,t)},`);return r.map(e=>" ".repeat(t)+e).join("\n")}function sF(e,t){if(sL(e))return e.anyOf.map(e=>sF(e,t)).join(" | ");switch(e.type){case"string":if(e.enum)return e.enum.map(e=>`"${e}"`).join(" | ");return"string";case"number":if(e.enum)return e.enum.map(e=>`${e}`).join(" | ");return"number";case"integer":if(e.enum)return e.enum.map(e=>`${e}`).join(" | ");return"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",sD(e,t+2),"}"].join("\n");case"array":if(e.items)return`${sF(e.items,t)}[]`;return"any[]";default:return""}}function sB(e){return"system"!==e.role&&"assistant"!==e.role&&"user"!==e.role&&"function"!==e.role&&"tool"!==e.role&&console.warn(`Unknown message role: ${e.role}`),e.role}function sz(e){let t=e._getType();switch(t){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!ac.isInstance(e))throw Error("Invalid generic chat message");return sB(e);default:throw Error(`Unknown message type: ${t}`)}}function sH(e){return"assistant"===e.role?new ar(e.content||"",{function_call:e.function_call,tool_calls:e.tool_calls}):new ac(e.content||"",e.role??"unknown")}function sZ(e,t){let r;let a=e.role??t,i=e.content??"";if(r=e.function_call?{function_call:e.function_call}:e.tool_calls?{tool_calls:e.tool_calls}:{},"user"===a)return new at({content:i});if("assistant"===a)return new aa({content:i,additional_kwargs:r});if("system"===a)return new an({content:i});if("function"===a)return new ao({content:i,additional_kwargs:r,name:e.name});if("tool"===a)return new au({content:i,additional_kwargs:r,tool_call_id:e.tool_call_id});else return new af({content:i,role:a})}function sq(e){return e.map(e=>{let t={role:sz(e),content:e.content};return null!=e.name&&(t.name=e.name),null!=e.additional_kwargs.function_call&&(t.function_call=e.additional_kwargs.function_call),null!=e.additional_kwargs.tool_calls&&(t.tool_calls=e.additional_kwargs.tool_calls),null!=e.tool_call_id&&(t.tool_call_id=e.tool_call_id),t})}class sG extends sl{static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed"]}get lc_secrets(){return{openAIApiKey:"OPENAI_API_KEY",azureOpenAIApiKey:"AZURE_OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{modelName:"model",openAIApiKey:"openai_api_key",azureOpenAIApiVersion:"azure_openai_api_version",azureOpenAIApiKey:"azure_openai_api_key",azureOpenAIApiInstanceName:"azure_openai_api_instance_name",azureOpenAIApiDeploymentName:"azure_openai_api_deployment_name"}}constructor(e,t){if(super(e??{}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"frequencyPenalty",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"presencePenalty",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"logitBias",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:"gpt-3.5-turbo"}),Object.defineProperty(this,"modelKwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logprobs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topLogprobs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"openAIApiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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,"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}),Object.defineProperty(this,"organization",{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}),this.openAIApiKey=e?.openAIApiKey??aP("OPENAI_API_KEY"),this.azureOpenAIApiKey=e?.azureOpenAIApiKey??aP("AZURE_OPENAI_API_KEY"),!this.azureOpenAIApiKey&&!this.openAIApiKey)throw Error("OpenAI or Azure OpenAI API key not found");if(this.azureOpenAIApiInstanceName=e?.azureOpenAIApiInstanceName??aP("AZURE_OPENAI_API_INSTANCE_NAME"),this.azureOpenAIApiDeploymentName=e?.azureOpenAIApiDeploymentName??aP("AZURE_OPENAI_API_DEPLOYMENT_NAME"),this.azureOpenAIApiVersion=e?.azureOpenAIApiVersion??aP("AZURE_OPENAI_API_VERSION"),this.azureOpenAIBasePath=e?.azureOpenAIBasePath??aP("AZURE_OPENAI_BASE_PATH"),this.organization=e?.configuration?.organization??aP("OPENAI_ORGANIZATION"),this.modelName=e?.modelName??this.modelName,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.maxTokens=e?.maxTokens,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stop,this.user=e?.user,this.streaming=e?.streaming??!1,this.azureOpenAIApiKey){if(!this.azureOpenAIApiInstanceName&&!this.azureOpenAIBasePath)throw Error("Azure OpenAI API instance name not found");if(!this.azureOpenAIApiDeploymentName)throw Error("Azure OpenAI API deployment name not found");if(!this.azureOpenAIApiVersion)throw Error("Azure OpenAI API version not found");this.openAIApiKey=this.openAIApiKey??""}this.clientConfig={apiKey:this.openAIApiKey,organization:this.organization,baseURL:t?.basePath??e?.configuration?.basePath,dangerouslyAllowBrowser:!0,defaultHeaders:t?.baseOptions?.headers??e?.configuration?.baseOptions?.headers,defaultQuery:t?.baseOptions?.params??e?.configuration?.baseOptions?.params,...t,...e?.configuration}}invocationParams(e){function t(e){return void 0!==e&&e.every(e=>Array.isArray(e.lc_namespace))}return{model:this.modelName,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,max_tokens:-1===this.maxTokens?void 0:this.maxTokens,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:e?.stop??this.stop,user:this.user,stream:this.streaming,functions:e?.functions,function_call:e?.function_call,tools:t(e?.tools)?e?.tools.map(sc):e?.tools,tool_choice:e?.tool_choice,response_format:e?.response_format,seed:e?.seed,...this.modelKwargs}}_identifyingParams(){return{model_name:this.modelName,...this.invocationParams(),...this.clientConfig}}async *_streamResponseChunks(e,t,r){let a;let i=sq(e),n={...this.invocationParams(t),messages:i,stream:!0};for await(let e of(await this.completionWithRetry(n,t))){let i=e?.choices[0];if(!i)continue;let{delta:n}=i;if(!n)continue;let s=sZ(n,a);a=n.role??a;let o={prompt:t.promptIndex??0,completion:i.index??0};if("string"!=typeof s.content){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let l={...o};void 0!==i.finish_reason&&(l.finish_reason=i.finish_reason),this.logprobs&&(l.logprobs=i.logprobs);let u=new a_({message:s,text:s.content,generationInfo:l});yield u,r?.handleLLMNewToken(u.text??"",o,void 0,void 0,void 0,{chunk:u})}if(t.signal?.aborted)throw Error("AbortError")}identifyingParams(){return this._identifyingParams()}async _generate(e,t,r){let a={},i=this.invocationParams(t),n=sq(e);if(i.stream){let i=this._streamResponseChunks(e,t,r),n={};for await(let e of i){e.message.response_metadata={...e.generationInfo,...e.message.response_metadata};let t=e.generationInfo?.completion??0;void 0===n[t]?n[t]=e:n[t]=n[t].concat(e)}let s=Object.entries(n).sort(([e],[t])=>parseInt(e,10)-parseInt(t,10)).map(([e,t])=>t),{functions:o,function_call:l}=this.invocationParams(t),u=await this.getEstimatedTokenCountFromPrompt(e,o,l),c=await this.getNumTokensFromGenerations(s);return a.promptTokens=u,a.completionTokens=c,a.totalTokens=u+c,{generations:s,llmOutput:{estimatedTokenUsage:a}}}{let e=await this.completionWithRetry({...i,stream:!1,messages:n},{signal:t?.signal,...t?.options}),{completion_tokens:r,prompt_tokens:s,total_tokens:o}=e?.usage??{};r&&(a.completionTokens=(a.completionTokens??0)+r),s&&(a.promptTokens=(a.promptTokens??0)+s),o&&(a.totalTokens=(a.totalTokens??0)+o);let l=[];for(let t of e?.choices??[]){let e={text:t.message?.content??"",message:sH(t.message??{role:"assistant"})};e.generationInfo={...t.finish_reason?{finish_reason:t.finish_reason}:{},...t.logprobs?{logprobs:t.logprobs}:{}},l.push(e)}return{generations:l,llmOutput:{tokenUsage:a}}}}async getEstimatedTokenCountFromPrompt(e,t,r){let a=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&"auto"!==r){let e=sU(t);a+=await this.getNumTokens(e),a+=9}return t&&e.find(e=>"system"===e._getType())&&(a-=4),"none"===r?a+=1:"object"==typeof r&&(a+=await this.getNumTokens(r.name)+4),a}async getNumTokensFromGenerations(e){return(await Promise.all(e.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,t)=>e+t,0)}async getNumTokensFromMessages(e){let t=0,r=0,a=0;"gpt-3.5-turbo-0301"===this.modelName?(r=4,a=-1):(r=3,a=1);let i=await Promise.all(e.map(async e=>{let i=await this.getNumTokens(e.content),n=await this.getNumTokens(sz(e)),s=void 0!==e.name?a+await this.getNumTokens(e.name):0,o=i+r+n+s,l=e;if("function"===l._getType()&&(o-=2),l.additional_kwargs?.function_call&&(o+=3),l?.additional_kwargs.function_call?.name&&(o+=await this.getNumTokens(l.additional_kwargs.function_call?.name)),l.additional_kwargs.function_call?.arguments)try{o+=await this.getNumTokens(JSON.stringify(JSON.parse(l.additional_kwargs.function_call?.arguments)))}catch(e){console.error("Error parsing function arguments",e,JSON.stringify(l.additional_kwargs.function_call)),o+=await this.getNumTokens(l.additional_kwargs.function_call?.arguments)}return t+=o,o}));return{totalCount:t+=3,countPerMessage:i}}async completionWithRetry(e,t){let r=this._getClientOptions(t);return this.caller.call(async()=>{try{return await this.client.chat.completions.create(e,r)}catch(e){throw sM(e)}})}_getClientOptions(e){if(!this.client){let e=s$({azureOpenAIApiDeploymentName:this.azureOpenAIApiDeploymentName,azureOpenAIApiInstanceName:this.azureOpenAIApiInstanceName,azureOpenAIApiKey:this.azureOpenAIApiKey,azureOpenAIBasePath:this.azureOpenAIBasePath,baseURL:this.clientConfig.baseURL}),t={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};t.baseURL||delete t.baseURL,this.client=new rU(t)}let t={...this.clientConfig,...e};return this.azureOpenAIApiKey&&(t.headers={"api-key":this.azureOpenAIApiKey,...t.headers},t.query={"api-version":this.azureOpenAIApiVersion,...t.query}),t}_llmType(){return"openai"}_combineLLMOutput(...e){return e.reduce((e,t)=>(t&&t.tokenUsage&&(e.tokenUsage.completionTokens+=t.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=t.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=t.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}withStructuredOutput(e,t){let r,a,i,n,s,o;if(sK(e)?(r=e.schema,a=e.name,i=e.method,n=e.includeRaw):(r=e,a=t?.name,i=t?.method,n=t?.includeRaw),"jsonMode"===i)s=this.bind({response_format:{type:"json_object"}}),o=sW(r)?sP.fromZodSchema(r):new sT;else{let e=a??"extract";if(sW(r)){let t=(0,nV.Ik)(r);s=this.bind({tools:[{type:"function",function:{name:e,description:t.description,parameters:t}}],tool_choice:{type:"function",function:{name:e}}}),o=new sC({returnSingle:!0,keyName:e,zodSchema:r})}else{let t;"string"==typeof r.name&&"object"==typeof r.parameters&&null!=r.parameters?(t=r,e=r.name):t={name:e=r.title??e,description:r.description??"",parameters:r},s=this.bind({tools:[{type:"function",function:t}],tool_choice:{type:"function",function:{name:e}}}),o=new sC({returnSingle:!0,keyName:e})}}if(!n)return s.pipe(o);let l=sh.assign({parsed:(e,t)=>o.invoke(e.raw,t)}),u=sh.assign({parsed:()=>null}),c=l.withFallbacks({fallbacks:[u]});return n6.from([{raw:s},c])}}function sW(e){return"function"==typeof e?.parse}function sK(e){return void 0!==e&&"object"==typeof e.schema}let sJ=(e,t)=>e.reduce((e,r,a)=>{let i=Math.floor(a/t),n=e[i]||[];return e[i]=n.concat([r]),e},[]);class sY{constructor(e){Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.caller=new aW(e??{})}}class sV extends sY{constructor(e,t){let r={maxConcurrency:2,...e};super(r),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:"text-embedding-ada-002"}),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,"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,"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}),Object.defineProperty(this,"organization",{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});let a=r?.openAIApiKey??aP("OPENAI_API_KEY"),i=r?.azureOpenAIApiKey??aP("AZURE_OPENAI_API_KEY");if(!i&&!a)throw Error("OpenAI or Azure OpenAI API key not found");let n=r?.azureOpenAIApiInstanceName??aP("AZURE_OPENAI_API_INSTANCE_NAME"),s=(r?.azureOpenAIApiEmbeddingsDeploymentName||r?.azureOpenAIApiDeploymentName)??(aP("AZURE_OPENAI_API_EMBEDDINGS_DEPLOYMENT_NAME")||aP("AZURE_OPENAI_API_DEPLOYMENT_NAME")),o=r?.azureOpenAIApiVersion??aP("AZURE_OPENAI_API_VERSION");if(this.azureOpenAIBasePath=r?.azureOpenAIBasePath??aP("AZURE_OPENAI_BASE_PATH"),this.organization=r?.configuration?.organization??aP("OPENAI_ORGANIZATION"),this.modelName=r?.modelName??this.modelName,this.batchSize=r?.batchSize??(i?1:this.batchSize),this.stripNewLines=r?.stripNewLines??this.stripNewLines,this.timeout=r?.timeout,this.dimensions=r?.dimensions,this.azureOpenAIApiVersion=o,this.azureOpenAIApiKey=i,this.azureOpenAIApiInstanceName=n,this.azureOpenAIApiDeploymentName=s,this.azureOpenAIApiKey){if(!this.azureOpenAIApiInstanceName&&!this.azureOpenAIBasePath)throw Error("Azure OpenAI API instance name not found");if(!this.azureOpenAIApiDeploymentName)throw Error("Azure OpenAI API deployment name not found");if(!this.azureOpenAIApiVersion)throw Error("Azure OpenAI API version not found");a=a??""}this.clientConfig={apiKey:a,organization:this.organization,baseURL:t?.basePath,dangerouslyAllowBrowser:!0,defaultHeaders:t?.baseOptions?.headers,defaultQuery:t?.baseOptions?.params,...t,...e?.configuration}}async embedDocuments(e){let t=sJ(this.stripNewLines?e.map(e=>e.replace(/\n/g," ")):e,this.batchSize),r=t.map(e=>{let t={model:this.modelName,input:e};return this.dimensions&&(t.dimensions=this.dimensions),this.embeddingWithRetry(t)}),a=await Promise.all(r),i=[];for(let e=0;e{try{return await this.client.embeddings.create(e,t)}catch(e){throw sM(e)}})}}class sX extends Error{constructor(e,t){super(e),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=t}}class sQ extends ss{get lc_namespace(){return["langchain","tools"]}constructor(e){super(e??{}),Object.defineProperty(this,"returnDirect",{enumerable:!0,configurable:!0,writable:!0,value:!1})}async invoke(e,t){return this.call(e,nG(t))}async call(e,t,r){let a,i;try{a=await this.schema.parseAsync(e)}catch(t){throw new sX("Received tool input did not match expected schema",JSON.stringify(e))}let n=i9(t),s=await nr.configure(n.callbacks,this.callbacks,n.tags||r,this.tags,n.metadata,this.metadata,{verbose:this.verbose}),o=await s?.handleToolStart(this.toJSON(),"string"==typeof a?a:JSON.stringify(a),n.runId,void 0,void 0,void 0,n.runName);delete n.runId;try{i=await this._call(a,o,n)}catch(e){throw await o?.handleToolError(e),e}return await o?.handleToolEnd(i),i}}class s0 extends sQ{constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:a6.z.object({input:a6.z.string().optional()}).transform(e=>e.input)})}call(e,t){return super.call("string"!=typeof e&&e?e:{input:e},t)}}class s1 extends s0{static lc_name(){return"DallEAPIWrapper"}constructor(e){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:"A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description."}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:"dall-e-3"}),Object.defineProperty(this,"style",{enumerable:!0,configurable:!0,writable:!0,value:"vivid"}),Object.defineProperty(this,"quality",{enumerable:!0,configurable:!0,writable:!0,value:"standard"}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:"1024x1024"}),Object.defineProperty(this,"responseFormat",{enumerable:!0,configurable:!0,writable:!0,value:"url"}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let t={apiKey:e?.openAIApiKey??aP("OPENAI_API_KEY"),organization:e?.organization??aP("OPENAI_ORGANIZATION"),dangerouslyAllowBrowser:!0};this.client=new rU(t),this.modelName=e?.modelName??this.modelName,this.style=e?.style??this.style,this.quality=e?.quality??this.quality,this.n=e?.n??this.n,this.size=e?.size??this.size,this.responseFormat=e?.responseFormat??this.responseFormat,this.user=e?.user}async _call(e){let t=await this.client.images.generate({model:this.modelName,prompt:e,n:this.n,size:this.size,response_format:this.responseFormat,style:this.style,quality:this.quality,user:this.user}),r="";return"url"===this.responseFormat?[r]=t.data.map(e=>e.url).filter(e=>"undefined"!==e):[r]=t.data.map(e=>e.b64_json).filter(e=>"undefined"!==e),r}}Object.defineProperty(s1,"toolName",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"})},8044:(e,t,r)=>{let a=r(36053);e.exports=(e,t,r)=>{let i=new a(e,r),n=new a(t,r);return i.compare(n)||i.compareBuild(n)}},11259:(e,t,r)=>{"use strict";r.d(t,{gk:()=>d,m5:()=>p});var a=r(79737),i=r(69988),n=r(13196);let s=e=>void 0!==e?e:!!["TRACING_V2","TRACING"].find(e=>"true"===(0,i.Jz)(e));var o=r(55165);let l=Symbol.for("lc:context_variables");function u(e){return e.replace(/[-:.]/g,"")}function c(e,t,r=1){let a=r.toFixed(0).slice(0,3).padStart(3,"0");return u(`${new Date(e).toISOString().slice(0,-1)}${a}Z`)+t}class h{constructor(e,t){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}),this.metadata=e,this.tags=t}static fromHeader(e){let t=e.split(","),r={},a=[];for(let e of t){let[t,i]=e.split("="),n=decodeURIComponent(i);"langsmith-metadata"===t?r=JSON.parse(n):"langsmith-tags"===t&&(a=n.split(","))}return new h(r,a)}toHeader(){let e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),e.join(",")}}class d{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,"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}),p(e)){Object.assign(this,{...e});return}let t=d.getDefaultConfig(),{metadata:r,...a}=e,i=a.client??d.getSharedClient(),n={...r,...a?.extra?.metadata};if(a.extra={...a.extra,metadata:n},Object.assign(this,{...t,...a,client:i}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){let e=c(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+e:this.dotted_order=e}}static getDefaultConfig(){return{id:a.A(),run_type:"chain",project_name:(0,i.Jz)("PROJECT")??(0,i.Az)("LANGCHAIN_SESSION")??"default",child_runs:[],api_url:(0,i.Az)("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:(0,i.Az)("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return d.sharedClient||(d.sharedClient=new n.Kj),d.sharedClient}createChild(e){let t=this.child_execution_order+1,r=new d({...e,parent_run:this,project_name:this.project_name,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:t,child_execution_order:t});l in this&&(r[l]=this[l]);let a=Symbol.for("lc:child_config"),i=e.extra?.[a]??this.extra[a];if(y(i)){let e={...i},t=g(e.callbacks)?e.callbacks.copy?.():void 0;t&&(Object.assign(t,{_parentRunId:r.id}),t.handlers?.find(f)?.updateFromRunTree?.(r),e.callbacks=t),r.extra[a]=e}let n=new Set,s=this;for(;null!=s&&!n.has(s.id);)n.add(s.id),s.child_execution_order=Math.max(s.child_execution_order,t),s=s.parent_run;return this.child_runs.push(r),r}async end(e,t,r=Date.now(),a){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??r,a&&Object.keys(a).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...a}}:{metadata:a})}_convertToCreate(e,t,r=!0){let a,i;let n=e.extra??{};if(n.runtime||(n.runtime={}),t)for(let[e,r]of Object.entries(t))n.runtime[e]||(n.runtime[e]=r);return r?(i=e.parent_run?.id,a=[]):(a=e.child_runs.map(e=>this._convertToCreate(e,t,r)),i=void 0),{id:e.id,name:e.name,start_time:e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:n,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}}async postRun(e=!0){try{let t=(0,i.Ec)(),r=await this._convertToCreate(this,t,!0);if(await this.client.createRun(r),!e)for(let e of((0,o.m)("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."),this.child_runs))await e.postRun(!1)}catch(e){console.error(`Error in postRun for run ${this.id}:`,e)}}async patchRun(){try{let e={end_time:this.end_time,error:this.error,inputs:this.inputs,outputs:this.outputs,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};await this.client.updateRun(this.id,e)}catch(e){console.error(`Error in patchRun for run ${this.id}`,e)}}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),"string"==typeof e?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,t){let r,a,i;let n=e?.callbacks,o=s();if(n){let e=n?.getParentRunId?.()??"",t=n?.handlers?.find(e=>e?.name=="langchain_tracer");r=t?.getRun?.(e),a=t?.projectName,i=t?.client,o=o||!!t}return r?new d({name:r.name,id:r.id,trace_id:r.trace_id,dotted_order:r.dotted_order,client:i,tracingEnabled:o,project_name:a,tags:[...new Set((r?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...r?.extra?.metadata,...e?.metadata}}}).createChild(t):new d({...t,client:i,tracingEnabled:o,project_name:a})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){let r="get"in e&&"function"==typeof e.get?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,a=r["langsmith-trace"];if(!a||"string"!=typeof a)return;let i=a.trim(),n=i.split(".").map(e=>{let[t,r]=e.split("Z");return{strTime:t,time:Date.parse(t+"Z"),uuid:r}}),s=n[0].uuid,o={...t,name:t?.name??"parent",run_type:t?.run_type??"chain",start_time:t?.start_time??Date.now(),id:n.at(-1)?.uuid,trace_id:s,dotted_order:i};if(r.baggage&&"string"==typeof r.baggage){let e=h.fromHeader(r.baggage);o.metadata=e.metadata,o.tags=e.tags}return new d(o)}toHeaders(e){let t={"langsmith-trace":this.dotted_order,baggage:new h(this.extra?.metadata,this.tags).toHeader()};if(e)for(let[r,a]of Object.entries(t))e.set(r,a);return t}}function p(e){return void 0!==e&&"function"==typeof e.createChild&&"function"==typeof e.postRun}function f(e){return"object"==typeof e&&null!=e&&"string"==typeof e.name&&"langchain_tracer"===e.name}function m(e){return Array.isArray(e)&&e.some(e=>f(e))}function g(e){return"object"==typeof e&&null!=e&&Array.isArray(e.handlers)}function y(e){return void 0!==e&&"object"==typeof e.callbacks&&(m(e.callbacks?.handlers)||m(e.callbacks))}Object.defineProperty(d,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null})},11813:e=>{"use strict";e.exports=function e(e,t){if(null==e.pos||null==e.line)return e;let r=e.message;if(r+=` at row ${e.line+1}, col ${e.col+1}, pos ${e.pos}: `,t&&t.split){let a=t.split(/\n/),i=String(Math.min(a.length,e.line+3)).length,n=" ";for(;n.length "+a[t]+"\n",r+=n+" ";for(let t=0;t{"use strict";r.d(t,{Kj:()=>z});var a=r(79737),i=r(52813),n=r(52435),s=r(25822);let o=[400,401,403,404,405,406,407,408],l=[409];class u{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,this.queue=new n.default({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){let r=this.onFailedResponseHook;return this.queue.add(()=>i(()=>e(...t).catch(e=>{if(e instanceof Error)throw e;throw Error(e)}),{async onFailedAttempt(e){if(e.message.startsWith("Cancel")||e.message.startsWith("TimeoutError")||e.message.startsWith("AbortError")||e?.code==="ECONNABORTED")throw e;let t=e?.response,a=t?.status;if(a){if(o.includes(+a))throw e;if(l.includes(+a))return;r&&await r(t)}},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise((t,r)=>{e.signal?.addEventListener("abort",()=>{r(Error("AbortError"))})})]):this.call(t,...r)}fetch(...e){return this.call(()=>(0,s.Y)()(...e).then(e=>e.ok?e:Promise.reject(e)))}}function c(e){return"function"==typeof e?._getType}function h(e){let t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}var d=r(69988),p=r(53909),f=r(18056);function m(e,t){if(!f.A(e))throw Error(void 0!==t?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`);return e}var g=r(55165);function y(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw Error(`Invalid identifier format: ${e}`);let[t,r]=e.split(":"),a=r||"latest";if(t.includes("/")){let[r,i]=t.split("/",2);if(!r||!i)throw Error(`Invalid identifier format: ${e}`);return[r,i,a]}if(!t)throw Error(`Invalid identifier format: ${e}`);return["-",t,a]}r(99548);class b extends Error{constructor(e){super(e),this.name="LangSmithConflictError"}}async function _(e,t,r){let a;if(e.ok){r&&(a=await e.text());return}a=await e.text();let i=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Server response: ${a}`;if(409===e.status)throw new b(i);throw Error(i)}var w="[...]",v={result:"[Circular]"},O=[],E=[];let k=new TextEncoder;function x(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function S(e){return k.encode(e)}function A(e,t,r,a){try{let a=JSON.stringify(e,t,r);return S(a)}catch(n){let i;if(!n.message?.includes("Converting circular structure to JSON"))return console.warn("[WARNING]: LangSmith received unserializable value."),S("[Unserializable]");console.warn("[WARNING]: LangSmith received circular JSON. This will decrease tracer performance."),void 0===a&&(a=x()),T(e,"",0,[],void 0,0,a);try{i=0===E.length?JSON.stringify(e,t,r):JSON.stringify(e,N(t),r)}catch(e){return S("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==O.length;){let e=O.pop();4===e.length?Object.defineProperty(e[0],e[1],e[3]):e[0][e[1]]=e[2]}}return S(i)}}function P(e,t,r,a){var i=Object.getOwnPropertyDescriptor(a,r);void 0!==i.get?i.configurable?(Object.defineProperty(a,r,{value:e}),O.push([a,r,t,i])):E.push([t,r,e]):(a[r]=e,O.push([a,r,t]))}function T(e,t,r,a,i,n,s){if(n+=1,"object"==typeof e&&null!==e){for(o=0;os.depthLimit||void 0!==s.edgesLimit&&r+1>s.edgesLimit){P(w,e,t,i);return}if(a.push(e),Array.isArray(e))for(o=0;ot)}function N(e){return e=void 0!==e?e:function(e,t){return t},function(t,r){if(E.length>0)for(var a=0;a{let t=e?.toString()??(0,d.Jz)("TRACING_SAMPLING_RATE");if(void 0===t)return;let r=parseFloat(t);if(r<0||r>1)throw Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},C=e=>{let t=e.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return"localhost"===t||"127.0.0.1"===t||"::1"===t};async function $(e){let t=[];for await(let r of e)t.push(r);return t}function M(e){if(void 0!==e)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}let L=async e=>{if(e?.status===429){let t=1e3*parseInt(e.headers.get("retry-after")??"30",10);if(t>0)return await new Promise(e=>setTimeout(e,t)),!0}return!1};function U(e){return"number"==typeof e?Number(e.toFixed(4)):e}class D{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;let r=new Promise(e=>{t=e}),a=A(e.item).length;return this.items.push({action:e.action,payload:e.item,itemPromiseResolve:t,itemPromise:r,size:a}),this.sizeBytes+=a,r}pop(e){if(e<1)throw Error("Number of bytes to pop off may not be less than 1.");let t=[],r=0;for(;r+(this.peek()?.size??0)0;){let e=this.items.shift();e&&(t.push(e),r+=e.size,this.sizeBytes-=e.size)}if(0===t.length&&this.items.length>0){let e=this.items.shift();t.push(e),r+=e.size,this.sizeBytes-=e.size}return[t.map(e=>({action:e.action,item:e.payload})),()=>t.forEach(e=>e.itemPromiseResolve())]}}let F=0x1400000,B=2500;class z{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,"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 D}),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,"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:"false"===(0,d.Az)("LANGSMITH_TRACING_BACKGROUND")}),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});let t=z.getDefaultClientConfig();if(this.tracingSampleRate=R(e.tracingSamplingRate),this.apiUrl=M(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=M(e.apiKey??t.apiKey),this.webUrl=M(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.timeout_ms=e.timeout_ms??9e4,this.caller=new u(e.callerOptions??{}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw Error("Trace batch concurrency must be positive.");this.batchIngestCaller=new u({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:L}),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.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode}static getDefaultClientConfig(){let e=(0,d.Jz)("API_KEY"),t=(0,d.Jz)("ENDPOINT")??"https://api.smith.langchain.com";return{apiUrl:t,apiKey:e,webUrl:void 0,hideInputs:"true"===(0,d.Jz)("HIDE_INPUTS"),hideOutputs:"true"===(0,d.Jz)("HIDE_OUTPUTS")}}getHostUrl(){if(this.webUrl)return this.webUrl;if(C(this.apiUrl))return this.webUrl="http://localhost:3000",this.webUrl;if(this.apiUrl.endsWith("/api/v1"))return this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl;if(this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api"))return this.webUrl=this.apiUrl.replace("/api",""),this.webUrl;if(this.apiUrl.split(".",1)[0].includes("dev"))return this.webUrl="https://dev.smith.langchain.com",this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("eu"))return this.webUrl="https://eu.smith.langchain.com",this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("beta"))return this.webUrl="https://beta.smith.langchain.com",this.webUrl;else return this.webUrl="https://smith.langchain.com",this.webUrl}get headers(){let e={"User-Agent":`langsmith-js/${p.Ls}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),e}processInputs(e){return!1===this.hideInputs?e:!0===this.hideInputs?{}:"function"==typeof this.hideInputs?this.hideInputs(e):e}processOutputs(e){return!1===this.hideOutputs?e:!0===this.hideOutputs?{}:"function"==typeof this.hideOutputs?this.hideOutputs(e):e}prepareRunCreateOrUpdateInputs(e){let t={...e};return void 0!==t.inputs&&(t.inputs=this.processInputs(t.inputs)),void 0!==t.outputs&&(t.outputs=this.processOutputs(t.outputs)),t}async _getResponse(e,t){let r=t?.toString()??"",a=`${this.apiUrl}${e}?${r}`,i=await this.caller.call((0,s.Y)(),a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(i,`Failed to fetch ${e}`),i}async _get(e,t){return(await this._getResponse(e,t)).json()}async *_getPaginated(e,t=new URLSearchParams,r){let a=Number(t.get("offset"))||0,i=Number(t.get("limit"))||100;for(;;){t.set("offset",String(a)),t.set("limit",String(i));let n=`${this.apiUrl}${e}?${t}`,o=await this.caller.call((0,s.Y)(),n,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(o,`Failed to fetch ${e}`);let l=r?r(await o.json()):await o.json();if(0===l.length||(yield l,l.length0;){let[r,a]=this.autoBatchQueue.pop(e);if(!r.length){a();break}let i=this._processBatch(r,a).catch(console.error);t.push(i)}return Promise.all(t)}async _processBatch(e,t){if(!e.length){t();return}try{let t={runCreates:e.filter(e=>"create"===e.action).map(e=>e.item),runUpdates:e.filter(e=>"update"===e.action).map(e=>e.item)},r=await this._ensureServerInfo();r?.batch_ingest_config?.use_multipart_endpoint?await this.multipartIngestRuns(t):await this.batchIngestRuns(t)}finally{t()}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,"create"===e.action&&(e.item=j(e.item));let t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;let r=await this._getBatchSizeLimitBytes();return this.autoBatchQueue.sizeBytes>r&&this.drainAutoBatchQueue(r),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue(r)},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){let e=await (0,s.Y)()(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(B),...this.fetchOptions});return await _(e,"get server info"),e.json()}async _ensureServerInfo(){return void 0===this._getServerInfoPromise&&(this._getServerInfoPromise=(async()=>{if(void 0===this._serverInfo)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn("[WARNING]: LangSmith failed to fetch info on supported operations. Falling back to batch operations and default limits.")}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(void 0===this._serverInfo&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes();await this.drainAutoBatchQueue(e)}async createRun(e){if(!this._filterForSampling([e]).length)return;let t={...this.headers,"Content-Type":"application/json"},r=e.project_name;delete e.project_name;let a=this.prepareRunCreateOrUpdateInputs({session_name:r,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&void 0!==a.trace_id&&void 0!==a.dotted_order){this.processRunOperation({action:"create",item:a}).catch(console.error);return}let i=j(a),n=await this.caller.call((0,s.Y)(),`${this.apiUrl}/runs`,{method:"POST",headers:t,body:A(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(n,"create run",!0)}async batchIngestRuns({runCreates:e,runUpdates:t}){if(void 0===e&&void 0===t)return;let r=e?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[],a=t?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[];if(r.length>0&&a.length>0){let e=r.reduce((e,t)=>(t.id&&(e[t.id]=t),e),{}),t=[];for(let r of a)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);r=Object.values(e),a=t}let i={post:r,patch:a};if(!i.post.length&&!i.patch.length)return;let n={post:[],patch:[]};for(let e of["post","patch"]){let t=e,r=i[t].reverse(),a=r.pop();for(;void 0!==a;)n[t].push(a),a=r.pop()}(n.post.length>0||n.patch.length>0)&&await this._postBatchIngestRuns(A(n))}async _postBatchIngestRuns(e){let t={...this.headers,"Content-Type":"application/json",Accept:"application/json"},r=await this.batchIngestCaller.call((0,s.Y)(),`${this.apiUrl}/runs/batch`,{method:"POST",headers:t,body:e,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(r,"batch create run",!0)}async multipartIngestRuns({runCreates:e,runUpdates:t}){if(void 0===e&&void 0===t)return;let r={},a=[];for(let t of e??[]){let e=this.prepareRunCreateOrUpdateInputs(t);void 0!==e.id&&void 0!==e.attachments&&(r[e.id]=e.attachments),delete e.attachments,a.push(e)}let i=[];for(let e of t??[])i.push(this.prepareRunCreateOrUpdateInputs(e));if(void 0!==a.find(e=>void 0===e.trace_id||void 0===e.dotted_order))throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(void 0!==i.find(e=>void 0===e.trace_id||void 0===e.dotted_order))throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(a.length>0&&i.length>0){let e=a.reduce((e,t)=>(t.id&&(e[t.id]=t),e),{}),t=[];for(let r of i)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);a=Object.values(e),i=t}if(0===a.length&&0===i.length)return;let n=[],s=[];for(let[e,t]of[["post",a],["patch",i]])for(let a of t){let{inputs:t,outputs:i,events:o,attachments:l,...u}=a,c={inputs:t,outputs:i,events:o},h=A(u);for(let[t,r]of(s.push({name:`${e}.${u.id}`,payload:new Blob([h],{type:`application/json; length=${h.length}`})}),Object.entries(c))){if(void 0===r)continue;let a=A(r);s.push({name:`${e}.${u.id}.${t}`,payload:new Blob([a],{type:`application/json; length=${a.length}`})})}if(void 0!==u.id){let e=r[u.id];if(e)for(let[t,a]of(delete r[u.id],Object.entries(e))){let e,r;if(Array.isArray(a)?[e,r]=a:(e=a.mimeType,r=a.data),t.includes(".")){console.warn(`Skipping attachment '${t}' for run ${u.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}s.push({name:`attachment.${u.id}.${t}`,payload:new Blob([r],{type:`${e}; length=${r.byteLength}`})})}}n.push(`trace=${u.trace_id},id=${u.id}`)}await this._sendMultipartRequest(s,n.join("; "))}async _sendMultipartRequest(e,t){try{let t="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),r=[];for(let a of e)r.push(new Blob([`--${t}\r `])),r.push(new Blob([`Content-Disposition: form-data; name="${a.name}"\r `,`Content-Type: ${a.payload.type}\r \r `])),r.push(a.payload),r.push(new Blob(["\r\n"]));r.push(new Blob([`--${t}--\r `]));let a=new Blob(r),i=await a.arrayBuffer(),n=await this.batchIngestCaller.call((0,s.Y)(),`${this.apiUrl}/runs/multipart`,{method:"POST",headers:{...this.headers,"Content-Type":`multipart/form-data; boundary=${t}`},body:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(n,"ingest multipart runs",!0)}catch(e){console.warn(`${e.message.trim()} Context: ${t}`)}}async updateRun(e,t){m(e),t.inputs&&(t.inputs=this.processInputs(t.inputs)),t.outputs&&(t.outputs=this.processOutputs(t.outputs));let r={...t,id:e};if(!this._filterForSampling([r],!0).length)return;if(this.autoBatchTracing&&void 0!==r.trace_id&&void 0!==r.dotted_order){void 0!==t.end_time&&void 0===r.parent_run_id&&this.blockOnRootRunFinalization&&!this.manualFlushMode?await this.processRunOperation({action:"update",item:r}).catch(console.error):this.processRunOperation({action:"update",item:r}).catch(console.error);return}let a={...this.headers,"Content-Type":"application/json"},i=await this.caller.call((0,s.Y)(),`${this.apiUrl}/runs/${e}`,{method:"PATCH",headers:a,body:A(t),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(i,"update run",!0)}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){m(e);let r=await this._get(`/runs/${e}`);return t&&r.child_run_ids&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:t,projectOpts:r}){if(void 0!==t){let e;e=t.session_id?t.session_id:r?.projectName?(await this.readProject({projectName:r?.projectName})).id:r?.projectId?r?.projectId:(await this.readProject({projectName:(0,d.Jz)("PROJECT")||"default"})).id;let a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${e}/r/${t.id}?poll=true`}if(void 0!==e){let t=await this.readRun(e);if(!t.app_path)throw Error(`Run ${e} has no app_path`);let r=this.getHostUrl();return`${r}${t.app_path}`}throw Error("Must provide either runId or run")}async _loadChildRuns(e){let t=await $(this.listRuns({id:e.child_run_ids})),r={},a={};for(let e of(t.sort((e,t)=>(e?.dotted_order??"").localeCompare(t?.dotted_order??"")),t)){if(null===e.parent_run_id||void 0===e.parent_run_id)throw Error(`Child run ${e.id} has no parent`);e.parent_run_id in r||(r[e.parent_run_id]=[]),r[e.parent_run_id].push(e),a[e.id]=e}for(let t in e.child_runs=r[e.id]||[],r)t!==e.id&&(a[t].child_runs=r[t]);return e}async *listRuns(e){let{projectId:t,projectName:r,parentRunId:a,traceId:i,referenceExampleId:n,startTime:s,executionOrder:o,isRoot:l,runType:u,error:c,id:h,query:d,filter:p,traceFilter:f,treeFilter:m,limit:g,select:y}=e,b=[];if(t&&(b=Array.isArray(t)?t:[t]),r){let e=Array.isArray(r)?r:[r],t=await Promise.all(e.map(e=>this.readProject({projectName:e}).then(e=>e.id)));b.push(...t)}let _=["app_path","child_run_ids","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"],w={session:b.length?b:null,run_type:u,reference_example:n,query:d,filter:p,trace_filter:f,tree_filter:m,execution_order:o,parent_run:a,start_time:s?s.toISOString():null,error:c,id:h,limit:g,trace:i,select:y||_,is_root:l},v=0;for await(let e of this._getCursorPaginatedList("/runs/query",w))if(g){if(v>=g)break;if(e.length+v>g){let t=e.slice(0,g-v);yield*t;break}v+=e.length,yield*e}else yield*e}async getRunStats({id:e,trace:t,parentRun:r,runType:a,projectNames:i,projectIds:n,referenceExampleIds:o,startTime:l,endTime:u,error:c,query:h,filter:d,traceFilter:p,treeFilter:f,isRoot:m,dataSourceType:g}){let y=n||[];i&&(y=[...n||[],...await Promise.all(i.map(e=>this.readProject({projectName:e}).then(e=>e.id)))]);let b=Object.fromEntries(Object.entries({id:e,trace:t,parent_run:r,run_type:a,session:y,reference_example:o,start_time:l,end_time:u,error:c,query:h,filter:d,trace_filter:p,tree_filter:f,is_root:m,data_source_type:g}).filter(([e,t])=>void 0!==t)),_=await this.caller.call((0,s.Y)(),`${this.apiUrl}/runs/stats`,{method:"POST",headers:this.headers,body:JSON.stringify(b),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _.json()}async shareRun(e,{shareId:t}={}){let r={run_id:e,share_token:t||a.A()};m(e);let i=await this.caller.call((0,s.Y)(),`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),n=await i.json();if(null===n||!("share_token"in n))throw Error("Invalid response from server");return`${this.getHostUrl()}/public/${n.share_token}/r`}async unshareRun(e){m(e);let t=await this.caller.call((0,s.Y)(),`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(t,"unshare run",!0)}async readRunSharedLink(e){m(e);let t=await this.caller.call((0,s.Y)(),`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),r=await t.json();if(null!==r&&"share_token"in r)return`${this.getHostUrl()}/public/${r.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){let r=new URLSearchParams({share_token:e});if(void 0!==t)for(let e of t)r.append("id",e);m(e);let a=await this.caller.call((0,s.Y)(),`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await a.json()}async readDatasetSharedSchema(e,t){if(!e&&!t)throw Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id),m(e);let r=await this.caller.call((0,s.Y)(),`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),a=await r.json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async shareDataset(e,t){if(!e&&!t)throw Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id);let r={dataset_id:e};m(e);let a=await this.caller.call((0,s.Y)(),`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),i=await a.json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){m(e);let t=await this.caller.call((0,s.Y)(),`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(t,"unshare dataset",!0)}async readSharedDataset(e){m(e);let t=await this.caller.call((0,s.Y)(),`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await t.json()}async listSharedExamples(e,t){let r={};t?.exampleIds&&(r.id=t.exampleIds);let a=new URLSearchParams;Object.entries(r).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>a.append(e,t)):a.append(e,t)});let i=await this.caller.call((0,s.Y)(),`${this.apiUrl}/public/${e}/examples?${a.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),n=await i.json();if(!i.ok){if("detail"in n)throw Error(`Failed to list shared examples. Status: ${i.status} Message: ${n.detail.join("\n")}`);throw Error(`Failed to list shared examples: ${i.status} ${i.statusText}`)}return n.map(e=>({...e,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:t=null,metadata:r=null,upsert:a=!1,projectExtra:i=null,referenceDatasetId:n=null}){let o=a?"?upsert=true":"",l=`${this.apiUrl}/sessions${o}`,u=i||{};r&&(u.metadata=r);let c={name:e,extra:u,description:t};null!==n&&(c.reference_dataset_id=n);let h=await this.caller.call((0,s.Y)(),l,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(c),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(h,"create project"),await h.json()}async updateProject(e,{name:t=null,description:r=null,metadata:a=null,projectExtra:i=null,endTime:n=null}){let o=`${this.apiUrl}/sessions/${e}`,l=i;a&&(l={...l||{},metadata:a});let u={name:t,extra:l,description:r,end_time:n?new Date(n).toISOString():null},c=await this.caller.call((0,s.Y)(),o,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(c,"update project"),await c.json()}async hasProject({projectId:e,projectName:t}){let r="/sessions",a=new URLSearchParams;if(void 0!==e&&void 0!==t)throw Error("Must provide either projectName or projectId, not both");if(void 0!==e)m(e),r+=`/${e}`;else if(void 0!==t)a.append("name",t);else throw Error("Must provide projectName or projectId");let i=await this.caller.call((0,s.Y)(),`${this.apiUrl}${r}?${a}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});try{let e=await i.json();if(!i.ok)return!1;if(Array.isArray(e))return e.length>0;return!0}catch(e){return!1}}async readProject({projectId:e,projectName:t,includeStats:r}){let a,i="/sessions",n=new URLSearchParams;if(void 0!==e&&void 0!==t)throw Error("Must provide either projectName or projectId, not both");if(void 0!==e)m(e),i+=`/${e}`;else if(void 0!==t)n.append("name",t);else throw Error("Must provide projectName or projectId");void 0!==r&&n.append("include_stats",r.toString());let s=await this._get(i,n);if(Array.isArray(s)){if(0===s.length)throw Error(`Project[id=${e}, name=${t}] not found`);a=s[0]}else a=s;return a}async getProjectUrl({projectId:e,projectName:t}){if(void 0===e&&void 0===t)throw Error("Must provide either projectName or projectId");let r=await this.readProject({projectId:e,projectName:t}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(void 0===e&&void 0===t)throw Error("Must provide either datasetName or datasetId");let r=await this.readDataset({datasetId:e,datasetName:t}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/datasets/${r.id}`}async _getTenantId(){if(null!==this._tenantId)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let t of this._getPaginated("/sessions",e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw Error("No projects found to resolve tenant.")}async *listProjects({projectIds:e,name:t,nameContains:r,referenceDatasetId:a,referenceDatasetName:i,referenceFree:n,metadata:s}={}){let o=new URLSearchParams;if(void 0!==e)for(let t of e)o.append("id",t);if(void 0!==t&&o.append("name",t),void 0!==r&&o.append("name_contains",r),void 0!==a)o.append("reference_dataset",a);else if(void 0!==i){let e=await this.readDataset({datasetName:i});o.append("reference_dataset",e.id)}for await(let e of(void 0!==n&&o.append("reference_free",n.toString()),void 0!==s&&o.append("metadata",JSON.stringify(s)),this._getPaginated("/sessions",o)))yield*e}async deleteProject({projectId:e,projectName:t}){let r;if(void 0===e&&void 0===t)throw Error("Must provide projectName or projectId");if(void 0!==e&&void 0!==t)throw Error("Must provide either projectName or projectId, not both");m(r=void 0===e?(await this.readProject({projectName:t})).id:e);let a=await this.caller.call((0,s.Y)(),`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(a,`delete session ${r} (${t})`,!0)}async uploadCsv({csvFile:e,fileName:t,inputKeys:r,outputKeys:a,description:i,dataType:n,name:o}){let l=`${this.apiUrl}/datasets/upload`,u=new FormData;u.append("file",e,t),r.forEach(e=>{u.append("input_keys",e)}),a.forEach(e=>{u.append("output_keys",e)}),i&&u.append("description",i),n&&u.append("data_type",n),o&&u.append("name",o);let c=await this.caller.call((0,s.Y)(),l,{method:"POST",headers:this.headers,body:u,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(c,"upload CSV"),await c.json()}async createDataset(e,{description:t,dataType:r,inputsSchema:a,outputsSchema:i,metadata:n}={}){let o={name:e,description:t,extra:n?{metadata:n}:void 0};r&&(o.data_type=r),a&&(o.inputs_schema_definition=a),i&&(o.outputs_schema_definition=i);let l=await this.caller.call((0,s.Y)(),`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(l,"create dataset"),await l.json()}async readDataset({datasetId:e,datasetName:t}){let r,a="/datasets",i=new URLSearchParams({limit:"1"});if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==e)m(e),a+=`/${e}`;else if(void 0!==t)i.append("name",t);else throw Error("Must provide datasetName or datasetId");let n=await this._get(a,i);if(Array.isArray(n)){if(0===n.length)throw Error(`Dataset[id=${e}, name=${t}] not found`);r=n[0]}else r=n;return r}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(e){if(e instanceof Error&&e.message.toLocaleLowerCase().includes("not found"))return!1;throw e}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:r,toVersion:a}){let i=e;if(void 0===i&&void 0===t)throw Error("Must provide either datasetName or datasetId");if(void 0!==i&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");void 0===i&&(i=(await this.readDataset({datasetName:t})).id);let n=new URLSearchParams({from_version:"string"==typeof r?r:r.toISOString(),to_version:"string"==typeof a?a:a.toISOString()});return await this._get(`/datasets/${i}/versions/diff`,n)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){let r="/datasets";if(void 0!==e);else if(void 0!==t)e=(await this.readDataset({datasetName:t})).id;else throw Error("Must provide either datasetName or datasetId");let a=await this._getResponse(`${r}/${e}/openai_ft`);return(await a.text()).trim().split("\n").map(e=>JSON.parse(e))}async *listDatasets({limit:e=100,offset:t=0,datasetIds:r,datasetName:a,datasetNameContains:i,metadata:n}={}){let s="/datasets",o=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(void 0!==r)for(let e of r)o.append("id",e);for await(let e of(void 0!==a&&o.append("name",a),void 0!==i&&o.append("name_contains",i),void 0!==n&&o.append("metadata",JSON.stringify(n)),this._getPaginated(s,o)))yield*e}async updateDataset(e){let{datasetId:t,datasetName:r,...a}=e;if(!t&&!r)throw Error("Must provide either datasetName or datasetId");let i=t??(await this.readDataset({datasetName:r})).id;m(i);let n=await this.caller.call((0,s.Y)(),`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(n,"update dataset"),await n.json()}async updateDatasetTag(e){let{datasetId:t,datasetName:r,asOf:a,tag:i}=e;if(!t&&!r)throw Error("Must provide either datasetName or datasetId");let n=t??(await this.readDataset({datasetName:r})).id;m(n);let o=await this.caller.call((0,s.Y)(),`${this.apiUrl}/datasets/${n}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({as_of:"string"==typeof a?a:a.toISOString(),tag:i}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(o,"update dataset tags")}async deleteDataset({datasetId:e,datasetName:t}){let r="/datasets",a=e;if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==t&&(a=(await this.readDataset({datasetName:t})).id),void 0!==a)m(a),r+=`/${a}`;else throw Error("Must provide datasetName or datasetId");let i=await this.caller.call((0,s.Y)(),this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(i,`delete ${r}`),await i.json()}async indexDataset({datasetId:e,datasetName:t,tag:r}){let a=e;if(a||t){if(a&&t)throw Error("Must provide either datasetName or datasetId, not both");a||(a=(await this.readDataset({datasetName:t})).id)}else throw Error("Must provide either datasetName or datasetId");m(a);let i={tag:r},n=await this.caller.call((0,s.Y)(),`${this.apiUrl}/datasets/${a}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(n,"index dataset"),await n.json()}async similarExamples(e,t,r,{filter:a}={}){let i={limit:r,inputs:e};void 0!==a&&(i.filter=a),m(t);let n=await this.caller.call((0,s.Y)(),`${this.apiUrl}/datasets/${t}/search`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(n,"fetch similar examples"),(await n.json()).examples}async createExample(e,t,r){let i;if(H(e)&&(void 0!==t||void 0!==r))throw Error("Cannot provide outputs or options when using ExampleCreate object");let n=t?r?.datasetId:e.dataset_id,s=t?r?.datasetName:e.dataset_name;if(void 0===n&&void 0===s)throw Error("Must provide either datasetName or datasetId");if(void 0!==n&&void 0!==s)throw Error("Must provide either datasetName or datasetId, not both");void 0===n&&(n=(await this.readDataset({datasetName:s})).id);let o=(t?r?.createdAt:e.created_at)||new Date;i=H(e)?e:{inputs:e,outputs:t,created_at:o?.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};let l=await this._uploadExamplesMultipart(n,[i]);return await this.readExample(l.example_ids?.[0]??a.A())}async createExamples(e){if(Array.isArray(e)){if(0===e.length)return[];let t=e,r=t[0].dataset_id,a=t[0].dataset_name;if(void 0===r&&void 0===a)throw Error("Must provide either datasetName or datasetId");if(void 0!==r&&void 0!==a)throw Error("Must provide either datasetName or datasetId, not both");void 0===r&&(r=(await this.readDataset({datasetName:a})).id);let i=await this._uploadExamplesMultipart(r,t);return await Promise.all(i.example_ids.map(e=>this.readExample(e)))}let{inputs:t,outputs:r,metadata:a,splits:i,sourceRunIds:n,useSourceRunIOs:s,useSourceRunAttachments:o,attachments:l,exampleIds:u,datasetId:c,datasetName:h}=e;if(void 0===t)throw Error("Must provide inputs when using legacy parameters");let d=c,p=h;if(void 0===d&&void 0===p)throw Error("Must provide either datasetName or datasetId");if(void 0!==d&&void 0!==p)throw Error("Must provide either datasetName or datasetId, not both");void 0===d&&(d=(await this.readDataset({datasetName:p})).id);let f=t.map((e,t)=>({dataset_id:d,inputs:e,outputs:r?.[t],metadata:a?.[t],split:i?.[t],id:u?.[t],attachments:l?.[t],source_run_id:n?.[t],use_source_run_io:s?.[t],use_source_run_attachments:o?.[t]})),m=await this._uploadExamplesMultipart(d,f);return await Promise.all(m.example_ids.map(e=>this.readExample(e)))}async createLLMExample(e,t,r){return this.createExample({input:e},{output:t},r)}async createChatExample(e,t,r){let a=e.map(e=>c(e)?h(e):e),i=c(t)?h(t):t;return this.createExample({input:a},{output:i},r)}async readExample(e){m(e);let t=`/examples/${e}`,{attachment_urls:r,...a}=await this._get(t),i=a;return r&&(i.attachments=Object.entries(r).reduce((e,[t,r])=>(e[t.slice("attachment.".length)]={presigned_url:r.presigned_url,mime_type:r.mime_type},e),{})),i}async *listExamples({datasetId:e,datasetName:t,exampleIds:r,asOf:a,splits:i,inlineS3Urls:n,metadata:s,limit:o,offset:l,filter:u,includeAttachments:c}={}){let h;if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==e)h=e;else if(void 0!==t)h=(await this.readDataset({datasetName:t})).id;else throw Error("Must provide a datasetName or datasetId");let d=new URLSearchParams({dataset:h}),p=a?"string"==typeof a?a:a?.toISOString():void 0;p&&d.append("as_of",p);let f=n??!0;if(d.append("inline_s3_urls",f.toString()),void 0!==r)for(let e of r)d.append("id",e);if(void 0!==i)for(let e of i)d.append("splits",e);if(void 0!==s){let e=JSON.stringify(s);d.append("metadata",e)}void 0!==o&&d.append("limit",o.toString()),void 0!==l&&d.append("offset",l.toString()),void 0!==u&&d.append("filter",u),!0===c&&["attachment_urls","outputs","metadata"].forEach(e=>d.append("select",e));let m=0;for await(let e of this._getPaginated("/examples",d)){for(let t of e){let{attachment_urls:e,...r}=t,a=r;e&&(a.attachments=Object.entries(e).reduce((e,[t,r])=>(e[t.slice("attachment.".length)]={presigned_url:r.presigned_url,mime_type:r.mime_type||void 0},e),{})),yield a,m++}if(void 0!==o&&m>=o)break}}async deleteExample(e){m(e);let t=`/examples/${e}`,r=await this.caller.call((0,s.Y)(),this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(r,`delete ${t}`),await r.json()}async updateExample(e,t){let r,a,i;return m(r=t?e:e.id),i=void 0!==(a=t?{id:r,...t}:e).dataset_id?a.dataset_id:(await this.readExample(r)).dataset_id,this._updateExamplesMultipart(i,[a])}async updateExamples(e){let t;return t=void 0===e[0].dataset_id?(await this.readExample(e[0].id)).dataset_id:e[0].dataset_id,this._updateExamplesMultipart(t,e)}async readDatasetVersion({datasetId:e,datasetName:t,asOf:r,tag:a}){let i;if(m(i=e||(await this.readDataset({datasetName:t})).id),r&&a||!r&&!a)throw Error("Exactly one of asOf and tag must be specified.");let n=new URLSearchParams;void 0!==r&&n.append("as_of","string"==typeof r?r:r.toISOString()),void 0!==a&&n.append("tag",a);let o=await this.caller.call((0,s.Y)(),`${this.apiUrl}/datasets/${i}/version?${n.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(o,"read dataset version"),await o.json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:r}){let a;if(void 0===e&&void 0===t)throw Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");m(a=void 0===e?(await this.readDataset({datasetName:t})).id:e);let i=new URLSearchParams,n=r?"string"==typeof r?r:r?.toISOString():void 0;return n&&i.append("as_of",n),await this._get(`/datasets/${a}/splits`,i)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:r,exampleIds:a,remove:i=!1}){let n;if(void 0===e&&void 0===t)throw Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");m(n=void 0===e?(await this.readDataset({datasetName:t})).id:e);let o={split_name:r,examples:a.map(e=>(m(e),e)),remove:i},l=await this.caller.call((0,s.Y)(),`${this.apiUrl}/datasets/${n}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(l,"update dataset splits",!0)}async evaluateRun(e,t,{sourceInfo:r,loadChildRuns:a,referenceExample:i}={loadChildRuns:!1}){let n;if((0,g.m)("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."),"string"==typeof e)n=await this.readRun(e,{loadChildRuns:a});else if("object"==typeof e&&"id"in e)n=e;else throw Error(`Invalid run type: ${typeof e}`);null!==n.reference_example_id&&void 0!==n.reference_example_id&&(i=await this.readExample(n.reference_example_id));let s=await t.evaluateRun(n,i),[o,l]=await this._logEvaluationFeedback(s,n,r);return l[0]}async createFeedback(e,t,{score:r,value:i,correction:n,comment:o,sourceInfo:l,feedbackSourceType:u="api",sourceRunId:c,feedbackId:h,feedbackConfig:d,projectId:p,comparativeExperimentId:f}){if(!e&&!p)throw Error("One of runId or projectId must be provided");if(e&&p)throw Error("Only one of runId or projectId can be provided");let g={type:u??"api",metadata:l??{}};void 0===c||g?.metadata===void 0||g.metadata.__run||(g.metadata.__run={run_id:c}),g?.metadata!==void 0&&g.metadata.__run?.run_id!==void 0&&m(g.metadata.__run.run_id);let y={id:h??a.A(),run_id:e,key:t,score:U(r),value:i,correction:n,comment:o,feedback_source:g,comparative_experiment_id:f,feedbackConfig:d,session_id:p},b=`${this.apiUrl}/feedback`,w=await this.caller.call((0,s.Y)(),b,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(y),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(w,"create feedback",!0),y}async updateFeedback(e,{score:t,value:r,correction:a,comment:i}){let n={};null!=t&&(n.score=U(t)),null!=r&&(n.value=r),null!=a&&(n.correction=a),null!=i&&(n.comment=i),m(e);let o=await this.caller.call((0,s.Y)(),`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(o,"update feedback",!0)}async readFeedback(e){m(e);let t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){m(e);let t=`/feedback/${e}`,r=await this.caller.call((0,s.Y)(),this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(r,`delete ${t}`),await r.json()}async *listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:r}={}){let a=new URLSearchParams;if(e&&a.append("run",e.join(",")),t)for(let e of t)a.append("key",e);if(r)for(let e of r)a.append("source",e);for await(let e of this._getPaginated("/feedback",a))yield*e}async createPresignedFeedbackToken(e,t,{expiration:r,feedbackConfig:a}={}){let i={run_id:e,feedback_key:t,feedback_config:a};r?"string"==typeof r?i.expires_at=r:(r?.hours||r?.minutes||r?.days)&&(i.expires_in=r):i.expires_in={hours:3};let n=await this.caller.call((0,s.Y)(),`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await n.json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:r,createdAt:a,description:i,metadata:n,id:o}){if(0===t.length)throw Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:t[0]})).reference_dataset_id),null==!r)throw Error("A reference dataset is required");let l={id:o,name:e,experiment_ids:t,reference_dataset_id:r,description:i,created_at:(a??new Date)?.toISOString(),extra:{}};n&&(l.extra.metadata=n);let u=await this.caller.call((0,s.Y)(),`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u.json()}async *listPresignedFeedbackTokens(e){m(e);let t=new URLSearchParams({run_id:e});for await(let e of this._getPaginated("/feedback/tokens",t))yield*e}_selectEvalResults(e){let t;return"results"in e?e.results:Array.isArray(e)?e:[e]}async _logEvaluationFeedback(e,t,r){let a=this._selectEvalResults(e),i=[];for(let e of a){let a=r||{};e.evaluatorInfo&&(a={...e.evaluatorInfo,...a});let n=null;e.targetRunId?n=e.targetRunId:t&&(n=t.id),i.push(await this.createFeedback(n,e.key,{score:e.score,value:e.value,comment:e.comment,correction:e.correction,sourceInfo:a,sourceRunId:e.sourceRunId,feedbackConfig:e.feedbackConfig,feedbackSourceType:"model"}))}return[a,i]}async logEvaluationFeedback(e,t,r){let[a]=await this._logEvaluationFeedback(e,t,r);return a}async *listAnnotationQueues(e={}){let{queueIds:t,name:r,nameContains:a,limit:i}=e,n=new URLSearchParams;t&&t.forEach((e,t)=>{m(e,`queueIds[${t}]`),n.append("ids",e)}),r&&n.append("name",r),a&&n.append("name_contains",a),n.append("limit",(void 0!==i?Math.min(i,100):100).toString());let s=0;for await(let e of this._getPaginated("/annotation-queues",n))if(yield*e,s++,void 0!==i&&s>=i)break}async createAnnotationQueue(e){let{name:t,description:r,queueId:i}=e,n={name:t,description:r,id:i||a.A()},o=await this.caller.call((0,s.Y)(),`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(Object.fromEntries(Object.entries(n).filter(([e,t])=>void 0!==t))),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(o,"create annotation queue"),await o.json()}async readAnnotationQueue(e){let t=await this.listAnnotationQueues({queueIds:[e]}).next();if(t.done)throw Error(`Annotation queue with ID ${e} not found`);return t.value}async updateAnnotationQueue(e,t){let{name:r,description:a}=t,i=await this.caller.call((0,s.Y)(),`${this.apiUrl}/annotation-queues/${m(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({name:r,description:a}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(i,"update annotation queue")}async deleteAnnotationQueue(e){let t=await this.caller.call((0,s.Y)(),`${this.apiUrl}/annotation-queues/${m(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(t,"delete annotation queue")}async addRunsToAnnotationQueue(e,t){let r=await this.caller.call((0,s.Y)(),`${this.apiUrl}/annotation-queues/${m(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(t.map((e,t)=>m(e,`runIds[${t}]`).toString())),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(r,"add runs to annotation queue")}async getRunFromAnnotationQueue(e,t){let r=`/annotation-queues/${m(e,"queueId")}/run`,a=await this.caller.call((0,s.Y)(),`${this.apiUrl}${r}/${t}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(a,"get run from annotation queue"),await a.json()}async deleteRunFromAnnotationQueue(e,t){let r=await this.caller.call((0,s.Y)(),`${this.apiUrl}/annotation-queues/${m(e,"queueId")}/runs/${m(t,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(r,"delete run from annotation queue")}async getSizeFromAnnotationQueue(e){let t=await this.caller.call((0,s.Y)(),`${this.apiUrl}/annotation-queues/${m(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(t,"get size from annotation queue"),await t.json()}async _currentTenantIsOwner(e){let t=await this._getSettings();return"-"==e||t.tenant_handle===e}async _ownerConflictError(e,t){let r=await this._getSettings();return Error(`Cannot ${e} for another tenant. Current tenant: ${r.tenant_handle} Requested tenant: ${t}`)}async _getLatestCommitHash(e){let t=await this.caller.call((0,s.Y)(),`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),r=await t.json();if(!t.ok){let e="string"==typeof r.detail?r.detail:JSON.stringify(r.detail),a=Error(`Error ${t.status}: ${t.statusText} ${e}`);throw a.statusCode=t.status,a}if(0!==r.commits.length)return r.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){let[r,a,i]=y(e),n=await this.caller.call((0,s.Y)(),`${this.apiUrl}/likes/${r}/${a}`,{method:"POST",body:JSON.stringify({like:t}),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(n,`${t?"like":"unlike"} prompt`),await n.json()}async _getPromptUrl(e){let[t,r,a]=y(e);if(await this._currentTenantIsOwner(t)){let e=await this._getSettings();return"latest"!==a?`${this.getHostUrl()}/prompts/${r}/${a.substring(0,8)}?organizationId=${e.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${e.id}`}return"latest"!==a?`${this.getHostUrl()}/hub/${t}/${r}/${a.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(let t of this._getPaginated(`/commits/${e}/`,new URLSearchParams,e=>e.commits))yield*t}async *listPrompts(e){let t=new URLSearchParams;for await(let r of(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),this._getPaginated("/repos",t,e=>e.repos)))yield*r}async getPrompt(e){let[t,r,a]=y(e),i=await this.caller.call((0,s.Y)(),`${this.apiUrl}/repos/${t}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(404===i.status)return null;await _(i,"get prompt");let n=await i.json();return n.repo?n.repo:null}async createPrompt(e,t){let r=await this._getSettings();if(t?.isPublic&&!r.tenant_handle)throw Error(`Cannot create a public prompt without first creating a LangChain Hub handle. You can add a handle by creating a public prompt at: https://smith.langchain.com/prompts`);let[a,i,n]=y(e);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError("create a prompt",a);let o={repo_handle:i,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic},l=await this.caller.call((0,s.Y)(),`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(l,"create prompt");let{repo:u}=await l.json();return u}async createCommit(e,t,r){if(!await this.promptExists(e))throw Error("Prompt does not exist, you must create it first.");let[a,i,n]=y(e),o=r?.parentCommitHash!=="latest"&&r?.parentCommitHash?r?.parentCommitHash:await this._getLatestCommitHash(`${a}/${i}`),l={manifest:JSON.parse(JSON.stringify(t)),parent_commit:o},u=await this.caller.call((0,s.Y)(),`${this.apiUrl}/commits/${a}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(u,"create commit");let c=await u.json();return this._getPromptUrl(`${a}/${i}${c.commit_hash?`:${c.commit_hash}`:""}`)}async updateExamplesMultipart(e,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){if(!await this._getMultiPartSupport())throw Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version.");let r=new FormData;for(let e of t){let t=e.id,a=new Blob([A({...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split}})],{type:"application/json"});if(r.append(t,a),e.inputs){let a=new Blob([A(e.inputs)],{type:"application/json"});r.append(`${t}.inputs`,a)}if(e.outputs){let a=new Blob([A(e.outputs)],{type:"application/json"});r.append(`${t}.outputs`,a)}if(e.attachments)for(let[a,i]of Object.entries(e.attachments)){let e,n;Array.isArray(i)?[e,n]=i:(e=i.mimeType,n=i.data);let s=new Blob([n],{type:`${e}; length=${n.byteLength}`});r.append(`${t}.attachment.${a}`,s)}if(e.attachments_operations){let a=new Blob([A(e.attachments_operations)],{type:"application/json"});r.append(`${t}.attachments_operations`,a)}}let a=e??t[0]?.dataset_id,i=await this.caller.call((0,s.Y)(),`${this.apiUrl}/v1/platform/datasets/${a}/examples`,{method:"PATCH",headers:this.headers,body:r});return await i.json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){if(!await this._getMultiPartSupport())throw Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version.");let r=new FormData;for(let e of t){let t=(e.id??a.A()).toString(),i=new Blob([A({created_at:e.created_at,...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split},...e.source_run_id&&{source_run_id:e.source_run_id},...e.use_source_run_io&&{use_source_run_io:e.use_source_run_io},...e.use_source_run_attachments&&{use_source_run_attachments:e.use_source_run_attachments}})],{type:"application/json"});if(r.append(t,i),e.inputs){let a=new Blob([A(e.inputs)],{type:"application/json"});r.append(`${t}.inputs`,a)}if(e.outputs){let a=new Blob([A(e.outputs)],{type:"application/json"});r.append(`${t}.outputs`,a)}if(e.attachments)for(let[a,i]of Object.entries(e.attachments)){let e,n;Array.isArray(i)?[e,n]=i:(e=i.mimeType,n=i.data);let s=new Blob([n],{type:`${e}; length=${n.byteLength}`});r.append(`${t}.attachment.${a}`,s)}}let i=await this.caller.call((0,s.Y)(),`${this.apiUrl}/v1/platform/datasets/${e}/examples`,{method:"POST",headers:this.headers,body:r});return await i.json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw Error("Prompt does not exist, you must create it first.");let[r,a]=y(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);let i={};if(t?.description!==void 0&&(i.description=t.description),t?.readme!==void 0&&(i.readme=t.readme),t?.tags!==void 0&&(i.tags=t.tags),t?.isPublic!==void 0&&(i.is_public=t.isPublic),t?.isArchived!==void 0&&(i.is_archived=t.isArchived),0===Object.keys(i).length)throw Error("No valid update options provided");let n=await this.caller.call((0,s.Y)(),`${this.apiUrl}/repos/${r}/${a}`,{method:"PATCH",body:JSON.stringify(i),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(n,"update prompt"),n.json()}async deletePrompt(e){if(!await this.promptExists(e))throw Error("Prompt does not exist, you must create it first.");let[t,r,a]=y(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);let i=await this.caller.call((0,s.Y)(),`${this.apiUrl}/repos/${t}/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await i.json()}async pullPromptCommit(e,t){let[r,a,i]=y(e),n=await this.caller.call((0,s.Y)(),`${this.apiUrl}/commits/${r}/${a}/${i}${t?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await _(n,"pull prompt commit");let o=await n.json();return{owner:r,repo:a,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async _pullPrompt(e,t){return JSON.stringify((await this.pullPromptCommit(e,{includeModel:t?.includeModel})).manifest)}async pushPrompt(e,t){return(await this.promptExists(e)?t&&Object.keys(t).some(e=>"object"!==e)&&await this.updatePrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}):await this.createPrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}),t?.object)?await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,t={}){let{sourceApiUrl:r=this.apiUrl,datasetName:a}=t,[i,n]=this.parseTokenOrUrl(e,r),s=new z({apiUrl:i,apiKey:"placeholder"}),o=await s.readSharedDataset(n),l=a||o.name;try{if(await this.hasDataset({datasetId:l})){console.log(`Dataset ${l} already exists in your tenant. Skipping.`);return}}catch(e){}let u=await s.listSharedExamples(n),c=await this.createDataset(l,{description:o.description,dataType:o.data_type||"kv",inputsSchema:o.inputs_schema_definition??void 0,outputsSchema:o.outputs_schema_definition??void 0});try{await this.createExamples({inputs:u.map(e=>e.inputs),outputs:u.flatMap(e=>e.outputs?[e.outputs]:[]),datasetId:c.id})}catch(e){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),e}}parseTokenOrUrl(e,t,r=2,a="dataset"){try{return m(e),[t,e]}catch(e){}try{let i=new URL(e).pathname.split("/").filter(e=>""!==e);if(i.length>=r){let e=i[i.length-r];return[t,e]}throw Error(`Invalid public ${a} URL: ${e}`)}catch(t){throw Error(`Invalid public ${a} URL or token: ${e}`)}}awaitPendingTraceBatches(){return this.manualFlushMode?(console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve()):Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()])}}function H(e){return"dataset_id"in e||"dataset_name"in e}},13818:(e,t,r)=>{let a=r(34290);e.exports=(e,t,r)=>a(e,t,">",r)},14848:(e,t,r)=>{"use strict";e=r.nmd(e);let a=10,i=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,n=(e=0)=>(t,r,a)=>`\u001B[${38+e};2;${t};${r};${a}m`;Object.defineProperty(e,"exports",{enumerable:!0,get:function(){let e=new Map,t={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]}};for(let[r,a]of(t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright,Object.entries(t))){for(let[r,i]of Object.entries(a))t[r]={open:`\u001B[${i[0]}m`,close:`\u001B[${i[1]}m`},a[r]=t[r],e.set(i[0],i[1]);Object.defineProperty(t,r,{value:a,enumerable:!1})}return Object.defineProperty(t,"codes",{value:e,enumerable:!1}),t.color.close="\x1b[39m",t.bgColor.close="\x1b[49m",t.color.ansi256=i(),t.color.ansi16m=n(),t.bgColor.ansi256=i(a),t.bgColor.ansi16m=n(a),Object.defineProperties(t,{rgbToAnsi256:{value:(e,t,r)=>e===t&&t===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(r/255*5),enumerable:!1},hexToRgb:{value:e=>{let t=/(?[a-f\d]{6}|[a-f\d]{3})/i.exec(e.toString(16));if(!t)return[0,0,0];let{colorString:r}=t.groups;3===r.length&&(r=r.split("").map(e=>e+e).join(""));let a=Number.parseInt(r,16);return[a>>16&255,a>>8&255,255&a]},enumerable:!1},hexToAnsi256:{value:e=>t.rgbToAnsi256(...t.hexToRgb(e)),enumerable:!1}}),t}})},15366:(e,t,r)=>{"use strict";let a;r.d(t,{y:()=>tN,u:()=>tC}),function(e){e.STRING="string",e.NUMBER="number",e.INTEGER="integer",e.BOOLEAN="boolean",e.ARRAY="array",e.OBJECT="object"}(er||(er={})),function(e){e.LANGUAGE_UNSPECIFIED="language_unspecified",e.PYTHON="python"}(ea||(ea={})),function(e){e.OUTCOME_UNSPECIFIED="outcome_unspecified",e.OUTCOME_OK="outcome_ok",e.OUTCOME_FAILED="outcome_failed",e.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"}(ei||(ei={}));let i=["user","model","function","system"];!function(e){e.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",e.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",e.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",e.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",e.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"}(en||(en={})),function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE"}(es||(es={})),function(e){e.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"}(eo||(eo={})),function(e){e.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",e.SAFETY="SAFETY",e.OTHER="OTHER"}(el||(el={})),function(e){e.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.LANGUAGE="LANGUAGE",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.SPII="SPII",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.OTHER="OTHER"}(eu||(eu={})),function(e){e.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",e.RETRIEVAL_QUERY="RETRIEVAL_QUERY",e.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",e.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",e.CLASSIFICATION="CLASSIFICATION",e.CLUSTERING="CLUSTERING"}(ec||(ec={})),function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE"}(eh||(eh={})),function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.MODE_DYNAMIC="MODE_DYNAMIC"}(ed||(ed={}));class n extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}}class s extends n{constructor(e,t){super(e),this.response=t}}class o extends n{constructor(e,t,r,a){super(e),this.status=t,this.statusText=r,this.errorDetails=a}}class l extends n{}class u extends n{}let c="https://generativelanguage.googleapis.com",h="v1beta",d="0.24.0",p="genai-js";!function(e){e.GENERATE_CONTENT="generateContent",e.STREAM_GENERATE_CONTENT="streamGenerateContent",e.COUNT_TOKENS="countTokens",e.EMBED_CONTENT="embedContent",e.BATCH_EMBED_CONTENTS="batchEmbedContents"}(ep||(ep={}));class f{constructor(e,t,r,a,i){this.model=e,this.task=t,this.apiKey=r,this.stream=a,this.requestOptions=i}toString(){var e,t;let r=(null===(e=this.requestOptions)||void 0===e?void 0:e.apiVersion)||h,a=(null===(t=this.requestOptions)||void 0===t?void 0:t.baseUrl)||c,i=`${a}/${r}/${this.model}:${this.task}`;return this.stream&&(i+="?alt=sse"),i}}function m(e){let t=[];return(null==e?void 0:e.apiClient)&&t.push(e.apiClient),t.push(`${p}/${d}`),t.join(" ")}async function g(e){var t;let r=new Headers;r.append("Content-Type","application/json"),r.append("x-goog-api-client",m(e.requestOptions)),r.append("x-goog-api-key",e.apiKey);let a=null===(t=e.requestOptions)||void 0===t?void 0:t.customHeaders;if(a){if(!(a instanceof Headers))try{a=new Headers(a)}catch(e){throw new l(`unable to convert customHeaders value ${JSON.stringify(a)} to Headers: ${e.message}`)}for(let[e,t]of a.entries()){if("x-goog-api-key"===e)throw new l(`Cannot set reserved header name ${e}`);if("x-goog-api-client"===e)throw new l(`Header name ${e} can only be set using the apiClient field`);r.append(e,t)}}return r}async function y(e,t,r,a,i,n){let s=new f(e,t,r,a,n);return{url:s.toString(),fetchOptions:Object.assign(Object.assign({},O(n)),{method:"POST",headers:await g(s),body:i})}}async function b(e,t,r,a,i,n={},s=fetch){let{url:o,fetchOptions:l}=await y(e,t,r,a,i,n);return _(o,l,s)}async function _(e,t,r=fetch){let a;try{a=await r(e,t)}catch(t){w(t,e)}return a.ok||await v(a,e),a}function w(e,t){let r=e;throw"AbortError"===r.name?(r=new u(`Request aborted when fetching ${t.toString()}: ${e.message}`)).stack=e.stack:e instanceof o||e instanceof l||((r=new n(`Error fetching from ${t.toString()}: ${e.message}`)).stack=e.stack),r}async function v(e,t){let r,a="";try{let t=await e.json();a=t.error.message,t.error.details&&(a+=` ${JSON.stringify(t.error.details)}`,r=t.error.details)}catch(e){}throw new o(`Error fetching from ${t.toString()}: [${e.status} ${e.statusText}] ${a}`,e.status,e.statusText,r)}function O(e){let t={};if((null==e?void 0:e.signal)!==void 0||(null==e?void 0:e.timeout)>=0){let r=new AbortController;(null==e?void 0:e.timeout)>=0&&setTimeout(()=>r.abort(),e.timeout),(null==e?void 0:e.signal)&&e.signal.addEventListener("abort",()=>{r.abort()}),t.signal=r.signal}return t}function E(e){return e.text=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),A(e.candidates[0]))throw new s(`${P(e)}`,e);return k(e)}if(e.promptFeedback)throw new s(`Text not available. ${P(e)}`,e);return""},e.functionCall=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),A(e.candidates[0]))throw new s(`${P(e)}`,e);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),x(e)[0]}if(e.promptFeedback)throw new s(`Function call not available. ${P(e)}`,e)},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),A(e.candidates[0]))throw new s(`${P(e)}`,e);return x(e)}if(e.promptFeedback)throw new s(`Function call not available. ${P(e)}`,e)},e}function k(e){var t,r,a,i;let n=[];if(null===(r=null===(t=e.candidates)||void 0===t?void 0:t[0].content)||void 0===r?void 0:r.parts)for(let t of null===(i=null===(a=e.candidates)||void 0===a?void 0:a[0].content)||void 0===i?void 0:i.parts)t.text&&n.push(t.text),t.executableCode&&n.push("\n```"+t.executableCode.language+"\n"+t.executableCode.code+"\n```\n"),t.codeExecutionResult&&n.push("\n```\n"+t.codeExecutionResult.output+"\n```\n");return n.length>0?n.join(""):""}function x(e){var t,r,a,i;let n=[];if(null===(r=null===(t=e.candidates)||void 0===t?void 0:t[0].content)||void 0===r?void 0:r.parts)for(let t of null===(i=null===(a=e.candidates)||void 0===a?void 0:a[0].content)||void 0===i?void 0:i.parts)t.functionCall&&n.push(t.functionCall);return n.length>0?n:void 0}let S=[eu.RECITATION,eu.SAFETY,eu.LANGUAGE];function A(e){return!!e.finishReason&&S.includes(e.finishReason)}function P(e){var t,r,a;let i="";if((!e.candidates||0===e.candidates.length)&&e.promptFeedback)i+="Response was blocked",(null===(t=e.promptFeedback)||void 0===t?void 0:t.blockReason)&&(i+=` due to ${e.promptFeedback.blockReason}`),(null===(r=e.promptFeedback)||void 0===r?void 0:r.blockReasonMessage)&&(i+=`: ${e.promptFeedback.blockReasonMessage}`);else if(null===(a=e.candidates)||void 0===a?void 0:a[0]){let t=e.candidates[0];A(t)&&(i+=`Candidate was blocked due to ${t.finishReason}`,t.finishMessage&&(i+=`: ${t.finishMessage}`))}return i}function T(e){return this instanceof T?(this.v=e,this):new T(e)}function I(e,t,r){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var a,i=r.apply(e,t||[]),n=[];return a={},s("next"),s("throw"),s("return"),a[Symbol.asyncIterator]=function(){return this},a;function s(e){i[e]&&(a[e]=function(t){return new Promise(function(r,a){n.push([e,t,r,a])>1||o(e,t)})})}function o(e,t){try{l(i[e](t))}catch(e){h(n[0][3],e)}}function l(e){e.value instanceof T?Promise.resolve(e.value.v).then(u,c):h(n[0][2],e)}function u(e){o("next",e)}function c(e){o("throw",e)}function h(e,t){e(t),n.shift(),n.length&&o(n[0][0],n[0][1])}}"function"==typeof SuppressedError&&SuppressedError;let N=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function j(e){let[t,r]=$(e.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0}))).tee();return{stream:C(t),response:R(r)}}async function R(e){let t=[],r=e.getReader();for(;;){let{done:e,value:a}=await r.read();if(e)return E(M(t));t.push(a)}}function C(e){return I(this,arguments,function*(){let t=e.getReader();for(;;){let{value:e,done:r}=yield T(t.read());if(r)break;yield yield T(E(e))}})}function $(e){let t=e.getReader();return new ReadableStream({start(e){let r="";return a();function a(){return t.read().then(({value:t,done:i})=>{let s;if(i){if(r.trim()){e.error(new n("Failed to parse stream"));return}e.close();return}let o=(r+=t).match(N);for(;o;){try{s=JSON.parse(o[1])}catch(t){e.error(new n(`Error parsing JSON response: "${o[1]}"`));return}e.enqueue(s),o=(r=r.substring(o[0].length)).match(N)}return a()}).catch(e=>{let t=e;throw t.stack=e.stack,t="AbortError"===t.name?new u("Request aborted when reading from the stream"):new n("Error reading from the stream")})}}})}function M(e){let t=e[e.length-1],r={promptFeedback:null==t?void 0:t.promptFeedback};for(let t of e){if(t.candidates){let e=0;for(let a of t.candidates)if(r.candidates||(r.candidates=[]),r.candidates[e]||(r.candidates[e]={index:e}),r.candidates[e].citationMetadata=a.citationMetadata,r.candidates[e].groundingMetadata=a.groundingMetadata,r.candidates[e].finishReason=a.finishReason,r.candidates[e].finishMessage=a.finishMessage,r.candidates[e].safetyRatings=a.safetyRatings,a.content&&a.content.parts){r.candidates[e].content||(r.candidates[e].content={role:a.content.role||"user",parts:[]});let t={};for(let i of a.content.parts)i.text&&(t.text=i.text),i.functionCall&&(t.functionCall=i.functionCall),i.executableCode&&(t.executableCode=i.executableCode),i.codeExecutionResult&&(t.codeExecutionResult=i.codeExecutionResult),0===Object.keys(t).length&&(t.text=""),r.candidates[e].content.parts.push(t)}e++}t.usageMetadata&&(r.usageMetadata=t.usageMetadata)}return r}async function L(e,t,r,a){return j(await b(t,ep.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(r),a))}async function U(e,t,r,a){let i=await b(t,ep.GENERATE_CONTENT,e,!1,JSON.stringify(r),a);return{response:E(await i.json())}}function D(e){if(null!=e){if("string"==typeof e)return{role:"system",parts:[{text:e}]};if(e.text)return{role:"system",parts:[e]};if(e.parts)return e.role?e:{role:"system",parts:e.parts}}}function F(e){let t=[];if("string"==typeof e)t=[{text:e}];else for(let r of e)"string"==typeof r?t.push({text:r}):t.push(r);return B(t)}function B(e){let t={role:"user",parts:[]},r={role:"function",parts:[]},a=!1,i=!1;for(let n of e)"functionResponse"in n?(r.parts.push(n),i=!0):(t.parts.push(n),a=!0);if(a&&i)throw new n("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!a&&!i)throw new n("No content is provided for sending chat message.");return a?t:r}function z(e,t){var r;let a={model:null==t?void 0:t.model,generationConfig:null==t?void 0:t.generationConfig,safetySettings:null==t?void 0:t.safetySettings,tools:null==t?void 0:t.tools,toolConfig:null==t?void 0:t.toolConfig,systemInstruction:null==t?void 0:t.systemInstruction,cachedContent:null===(r=null==t?void 0:t.cachedContent)||void 0===r?void 0:r.name,contents:[]},i=null!=e.generateContentRequest;if(e.contents){if(i)throw new l("CountTokensRequest must have one of contents or generateContentRequest, not both.");a.contents=e.contents}else if(i)a=Object.assign(Object.assign({},a),e.generateContentRequest);else{let t=F(e);a.contents=[t]}return{generateContentRequest:a}}function H(e){let t;return t=e.contents?e:{contents:[F(e)]},e.systemInstruction&&(t.systemInstruction=D(e.systemInstruction)),t}function Z(e){return"string"==typeof e||Array.isArray(e)?{content:F(e)}:e}let q=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],G={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function W(e){let t=!1;for(let r of e){let{role:e,parts:a}=r;if(!t&&"user"!==e)throw new n(`First content should be with role 'user', got ${e}`);if(!i.includes(e))throw new n(`Each item should include role field. Got ${e} but valid roles are: ${JSON.stringify(i)}`);if(!Array.isArray(a))throw new n("Content should have 'parts' property with an array of Parts");if(0===a.length)throw new n("Each Content should have at least one part");let s={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(let e of a)for(let t of q)t in e&&(s[t]+=1);let o=G[e];for(let t of q)if(!o.includes(t)&&s[t]>0)throw new n(`Content with role '${e}' can't contain '${t}' part`);t=!0}}function K(e){var t;if(void 0===e.candidates||0===e.candidates.length)return!1;let r=null===(t=e.candidates[0])||void 0===t?void 0:t.content;if(void 0===r||void 0===r.parts||0===r.parts.length)return!1;for(let e of r.parts)if(void 0===e||0===Object.keys(e).length||void 0!==e.text&&""===e.text)return!1;return!0}let J="SILENT_ERROR";class Y{constructor(e,t,r,a={}){this.model=t,this.params=r,this._requestOptions=a,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,(null==r?void 0:r.history)&&(W(r.history),this._history=r.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,t={}){var r,a,i,n,s,o;let l;await this._sendPromise;let u=F(e),c={safetySettings:null===(r=this.params)||void 0===r?void 0:r.safetySettings,generationConfig:null===(a=this.params)||void 0===a?void 0:a.generationConfig,tools:null===(i=this.params)||void 0===i?void 0:i.tools,toolConfig:null===(n=this.params)||void 0===n?void 0:n.toolConfig,systemInstruction:null===(s=this.params)||void 0===s?void 0:s.systemInstruction,cachedContent:null===(o=this.params)||void 0===o?void 0:o.cachedContent,contents:[...this._history,u]},h=Object.assign(Object.assign({},this._requestOptions),t);return this._sendPromise=this._sendPromise.then(()=>U(this._apiKey,this.model,c,h)).then(e=>{var t;if(K(e.response)){this._history.push(u);let r=Object.assign({parts:[],role:"model"},null===(t=e.response.candidates)||void 0===t?void 0:t[0].content);this._history.push(r)}else{let t=P(e.response);t&&console.warn(`sendMessage() was unsuccessful. ${t}. Inspect response object for details.`)}l=e}),await this._sendPromise,l}async sendMessageStream(e,t={}){var r,a,i,n,s,o;await this._sendPromise;let l=F(e),u={safetySettings:null===(r=this.params)||void 0===r?void 0:r.safetySettings,generationConfig:null===(a=this.params)||void 0===a?void 0:a.generationConfig,tools:null===(i=this.params)||void 0===i?void 0:i.tools,toolConfig:null===(n=this.params)||void 0===n?void 0:n.toolConfig,systemInstruction:null===(s=this.params)||void 0===s?void 0:s.systemInstruction,cachedContent:null===(o=this.params)||void 0===o?void 0:o.cachedContent,contents:[...this._history,l]},c=Object.assign(Object.assign({},this._requestOptions),t),h=L(this._apiKey,this.model,u,c);return this._sendPromise=this._sendPromise.then(()=>h).catch(e=>{throw Error(J)}).then(e=>e.response).then(e=>{if(K(e)){this._history.push(l);let t=Object.assign({},e.candidates[0].content);t.role||(t.role="model"),this._history.push(t)}else{let t=P(e);t&&console.warn(`sendMessageStream() was unsuccessful. ${t}. Inspect response object for details.`)}}).catch(e=>{e.message!==J&&console.error(e)}),h}}async function V(e,t,r,a){return(await b(t,ep.COUNT_TOKENS,e,!1,JSON.stringify(r),a)).json()}async function X(e,t,r,a){return(await b(t,ep.EMBED_CONTENT,e,!1,JSON.stringify(r),a)).json()}async function Q(e,t,r,a){let i=r.requests.map(e=>Object.assign(Object.assign({},e),{model:t}));return(await b(t,ep.BATCH_EMBED_CONTENTS,e,!1,JSON.stringify({requests:i}),a)).json()}class ee{constructor(e,t,r={}){this.apiKey=e,this._requestOptions=r,t.model.includes("/")?this.model=t.model:this.model=`models/${t.model}`,this.generationConfig=t.generationConfig||{},this.safetySettings=t.safetySettings||[],this.tools=t.tools,this.toolConfig=t.toolConfig,this.systemInstruction=D(t.systemInstruction),this.cachedContent=t.cachedContent}async generateContent(e,t={}){var r;let a=H(e),i=Object.assign(Object.assign({},this._requestOptions),t);return U(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:null===(r=this.cachedContent)||void 0===r?void 0:r.name},a),i)}async generateContentStream(e,t={}){var r;let a=H(e),i=Object.assign(Object.assign({},this._requestOptions),t);return L(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:null===(r=this.cachedContent)||void 0===r?void 0:r.name},a),i)}startChat(e){var t;return new Y(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:null===(t=this.cachedContent)||void 0===t?void 0:t.name},e),this._requestOptions)}async countTokens(e,t={}){let r=z(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),a=Object.assign(Object.assign({},this._requestOptions),t);return V(this.apiKey,this.model,r,a)}async embedContent(e,t={}){let r=Z(e),a=Object.assign(Object.assign({},this._requestOptions),t);return X(this.apiKey,this.model,r,a)}async batchEmbedContents(e,t={}){let r=Object.assign(Object.assign({},this._requestOptions),t);return Q(this.apiKey,this.model,e,r)}}class et{constructor(e){this.apiKey=e}getGenerativeModel(e,t){if(!e.model)throw new n("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new ee(this.apiKey,e,t)}getGenerativeModelFromCachedContent(e,t,r){if(!e.name)throw new l("Cached content must contain a `name` field.");if(!e.model)throw new l("Cached content must contain a `model` field.");for(let r of["model","systemInstruction"])if((null==t?void 0:t[r])&&e[r]&&(null==t?void 0:t[r])!==e[r]){if("model"===r&&(t.model.startsWith("models/")?t.model.replace("models/",""):t.model)===(e.model.startsWith("models/")?e.model.replace("models/",""):e.model))continue;throw new l(`Different value for "${r}" specified in modelParams (${t[r]}) and cachedContent (${e[r]})`)}let a=Object.assign(Object.assign({},t),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new ee(this.apiKey,a,r)}}var er,ea,ei,en,es,eo,el,eu,ec,eh,ed,ep,ef=r(1776),em=r(46580),eg=r(58775),ey=r(70240);let eb=Symbol("Let zodToJsonSchema decide on which parser to use"),e_={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"},ew=e=>"string"==typeof e?{...e_,name:e}:{...e_,...e},ev=e=>{let t=ew(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};var eO=r(55594);function eE(){return{}}function ek(e,t,r,a){a?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function ex(e,t,r,a,i){e[t]=r,ek(e,t,a,i)}function eS(e,t){let r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==eO.kY.ZodAny&&(r.items=tn(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&ex(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&ex(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(ex(r,"minItems",e.exactLength.value,e.exactLength.message,t),ex(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function eA(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let a of e.checks)switch(a.kind){case"min":"jsonSchema7"===t.target?a.inclusive?ex(r,"minimum",a.value,a.message,t):ex(r,"exclusiveMinimum",a.value,a.message,t):(a.inclusive||(r.exclusiveMinimum=!0),ex(r,"minimum",a.value,a.message,t));break;case"max":"jsonSchema7"===t.target?a.inclusive?ex(r,"maximum",a.value,a.message,t):ex(r,"exclusiveMaximum",a.value,a.message,t):(a.inclusive||(r.exclusiveMaximum=!0),ex(r,"maximum",a.value,a.message,t));break;case"multipleOf":ex(r,"multipleOf",a.value,a.message,t)}return r}function eP(){return{type:"boolean"}}function eT(e,t){return tn(e.type._def,t)}let eI=(e,t)=>tn(e.innerType._def,t);function eN(e,t,r){let a=r??t.dateStrategy;if(Array.isArray(a))return{anyOf:a.map((r,a)=>eN(e,t,r))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return ej(e,t)}}let ej=(e,t)=>{let r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(let a of e.checks)switch(a.kind){case"min":ex(r,"minimum",a.value,a.message,t);break;case"max":ex(r,"maximum",a.value,a.message,t)}return r};function eR(e,t){return{...tn(e.innerType._def,t),default:e.defaultValue()}}function eC(e,t){return"input"===t.effectStrategy?tn(e.schema._def,t):{}}function e$(e){return{type:"string",enum:Array.from(e.values)}}let eM=e=>(!("type"in e)||"string"!==e.type)&&"allOf"in e;function eL(e,t){let r=[tn(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),tn(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(e=>!!e),a="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0,i=[];return r.forEach(e=>{if(eM(e))i.push(...e.allOf),void 0===e.unevaluatedProperties&&(a=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){let{additionalProperties:r,...a}=e;t=a}else a=void 0;i.push(t)}}),i.length?{allOf:i,...a}:void 0}function eU(e,t){let r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}let eD={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:()=>(void 0===a&&(a=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),a),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])$/,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 eF(e,t){let r={type:"string"};if(e.checks)for(let a of e.checks)switch(a.kind){case"min":ex(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,a.value):a.value,a.message,t);break;case"max":ex(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,a.value):a.value,a.message,t);break;case"email":switch(t.emailStrategy){case"format:email":eZ(r,"email",a.message,t);break;case"format:idn-email":eZ(r,"idn-email",a.message,t);break;case"pattern:zod":eq(r,eD.email,a.message,t)}break;case"url":eZ(r,"uri",a.message,t);break;case"uuid":eZ(r,"uuid",a.message,t);break;case"regex":eq(r,a.regex,a.message,t);break;case"cuid":eq(r,eD.cuid,a.message,t);break;case"cuid2":eq(r,eD.cuid2,a.message,t);break;case"startsWith":eq(r,RegExp(`^${eB(a.value,t)}`),a.message,t);break;case"endsWith":eq(r,RegExp(`${eB(a.value,t)}$`),a.message,t);break;case"datetime":eZ(r,"date-time",a.message,t);break;case"date":eZ(r,"date",a.message,t);break;case"time":eZ(r,"time",a.message,t);break;case"duration":eZ(r,"duration",a.message,t);break;case"length":ex(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,a.value):a.value,a.message,t),ex(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,a.value):a.value,a.message,t);break;case"includes":eq(r,RegExp(eB(a.value,t)),a.message,t);break;case"ip":"v6"!==a.version&&eZ(r,"ipv4",a.message,t),"v4"!==a.version&&eZ(r,"ipv6",a.message,t);break;case"base64url":eq(r,eD.base64url,a.message,t);break;case"jwt":eq(r,eD.jwt,a.message,t);break;case"cidr":"v6"!==a.version&&eq(r,eD.ipv4Cidr,a.message,t),"v4"!==a.version&&eq(r,eD.ipv6Cidr,a.message,t);break;case"emoji":eq(r,eD.emoji(),a.message,t);break;case"ulid":eq(r,eD.ulid,a.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":eZ(r,"binary",a.message,t);break;case"contentEncoding:base64":ex(r,"contentEncoding","base64",a.message,t);break;case"pattern:zod":eq(r,eD.base64,a.message,t)}break;case"nanoid":eq(r,eD.nanoid,a.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:(e=>{})(0)}return r}function eB(e,t){return"escape"===t.patternStrategy?eH(e):e}let ez=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function eH(e){let t="";for(let r=0;re.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&a.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&a.errorMessages&&{errorMessage:{format:r}}})):ex(e,"format",t,r,a)}function eq(e,t,r,a){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&a.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:eG(t,a),...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):ex(e,"pattern",eG(t,a),r,a)}function eG(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},a=r.i?e.source.toLowerCase():e.source,i="",n=!1,s=!1,o=!1;for(let e=0;e({...r,[a]:tn(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",a]})??{}}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:tn(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===eO.kY.ZodString&&e.keyType._def.checks?.length){let{type:a,...i}=eF(e.keyType._def,t);return{...r,propertyNames:i}}if(e.keyType?._def.typeName===eO.kY.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===eO.kY.ZodBranded&&e.keyType._def.type._def.typeName===eO.kY.ZodString&&e.keyType._def.type._def.checks?.length){let{type:a,...i}=eT(e.keyType._def,t);return{...r,propertyNames:i}}return r}function eK(e,t){return"record"===t.mapStrategy?eW(e,t):{type:"array",maxItems:125,items:{type:"array",items:[tn(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},tn(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}function eJ(e){let t=e.values,r=Object.keys(e.values).filter(e=>"number"!=typeof t[t[e]]).map(e=>t[e]),a=Array.from(new Set(r.map(e=>typeof e)));return{type:1===a.length?"string"===a[0]?"string":"number":["string","number"],enum:r}}function eY(){return{not:{}}}function eV(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}let eX={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function eQ(e,t){if("openApi3"===t.target)return e0(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(e=>e._def.typeName in eX&&(!e._def.checks||!e._def.checks.length))){let e=r.reduce((e,t)=>{let r=eX[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e},[]);return{type:e.length>1?e:e[0]}}if(r.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){let e=r.reduce((e,t)=>{let r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===r.length){let t=e.filter((e,t,r)=>r.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:r.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(r.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:r.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return e0(e,t)}let e0=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>tn(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0};function e1(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:eX[e.innerType._def.typeName],nullable:!0}:{type:[eX[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){let r=tn(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let r=tn(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function e2(e,t){let r={type:"number"};if(!e.checks)return r;for(let a of e.checks)switch(a.kind){case"int":r.type="integer",ek(r,"type",a.message,t);break;case"min":"jsonSchema7"===t.target?a.inclusive?ex(r,"minimum",a.value,a.message,t):ex(r,"exclusiveMinimum",a.value,a.message,t):(a.inclusive||(r.exclusiveMinimum=!0),ex(r,"minimum",a.value,a.message,t));break;case"max":"jsonSchema7"===t.target?a.inclusive?ex(r,"maximum",a.value,a.message,t):ex(r,"exclusiveMaximum",a.value,a.message,t):(a.inclusive||(r.exclusiveMaximum=!0),ex(r,"maximum",a.value,a.message,t));break;case"multipleOf":ex(r,"multipleOf",a.value,a.message,t)}return r}function e4(e,t){let r="openAi"===t.target,a={type:"object",properties:{}},i=[],n=e.shape();for(let e in n){let s=n[e];if(void 0===s||void 0===s._def)continue;let o=e9(s);o&&r&&(s instanceof eO.Ii&&(s=s._def.innerType),s.isNullable()||(s=s.nullable()),o=!1);let l=tn(s._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==l&&(a.properties[e]=l,o||i.push(e))}i.length&&(a.required=i);let s=e5(e,t);return void 0!==s&&(a.additionalProperties=s),a}function e5(e,t){if("ZodNever"!==e.catchall._def.typeName)return tn(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function e9(e){try{return e.isOptional()}catch{return!0}}let e3=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return tn(e.innerType._def,t);let r=tn(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}},e6=(e,t)=>{if("input"===t.pipeStrategy)return tn(e.in._def,t);if("output"===t.pipeStrategy)return tn(e.out._def,t);let r=tn(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),a=tn(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,a].filter(e=>void 0!==e)}};function e8(e,t){return tn(e.type._def,t)}function e7(e,t){let r={type:"array",uniqueItems:!0,items:tn(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ex(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ex(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function te(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,r)=>tn(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:tn(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,r)=>tn(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}function tt(){return{not:{}}}function tr(){return{}}let ta=(e,t)=>tn(e.innerType._def,t),ti=(e,t,r)=>{switch(t){case eO.kY.ZodString:return eF(e,r);case eO.kY.ZodNumber:return e2(e,r);case eO.kY.ZodObject:return e4(e,r);case eO.kY.ZodBigInt:return eA(e,r);case eO.kY.ZodBoolean:return eP();case eO.kY.ZodDate:return eN(e,r);case eO.kY.ZodUndefined:return tt();case eO.kY.ZodNull:return eV(r);case eO.kY.ZodArray:return eS(e,r);case eO.kY.ZodUnion:case eO.kY.ZodDiscriminatedUnion:return eQ(e,r);case eO.kY.ZodIntersection:return eL(e,r);case eO.kY.ZodTuple:return te(e,r);case eO.kY.ZodRecord:return eW(e,r);case eO.kY.ZodLiteral:return eU(e,r);case eO.kY.ZodEnum:return e$(e);case eO.kY.ZodNativeEnum:return eJ(e);case eO.kY.ZodNullable:return e1(e,r);case eO.kY.ZodOptional:return e3(e,r);case eO.kY.ZodMap:return eK(e,r);case eO.kY.ZodSet:return e7(e,r);case eO.kY.ZodLazy:return()=>e.getter()._def;case eO.kY.ZodPromise:return e8(e,r);case eO.kY.ZodNaN:case eO.kY.ZodNever:return eY();case eO.kY.ZodEffects:return eC(e,r);case eO.kY.ZodAny:return eE();case eO.kY.ZodUnknown:return tr();case eO.kY.ZodDefault:return eR(e,r);case eO.kY.ZodBranded:return eT(e,r);case eO.kY.ZodReadonly:return ta(e,r);case eO.kY.ZodCatch:return eI(e,r);case eO.kY.ZodPipeline:return e6(e,r);case eO.kY.ZodFunction:case eO.kY.ZodVoid:case eO.kY.ZodSymbol:return;default:let a;return void(a=0)}};function tn(e,t,r=!1){let a=t.seen.get(e);if(t.override){let i=t.override?.(e,t,a,r);if(i!==eb)return i}if(a&&!r){let e=ts(a,t);if(void 0!==e)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let n=ti(e,e.typeName,t),s="function"==typeof n?tn(n(),t):n;if(s&&tl(e,t,s),t.postProcess){let r=t.postProcess(s,e,t);return i.jsonSchema=s,r}return i.jsonSchema=s,s}let ts=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:to(t.currentPath,e.path)};case"none":case"seen":if(e.path.lengtht.currentPath[r]===e))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{};return"seen"===t.$refStrategy?{}:void 0}},to=(e,t)=>{let r=0;for(;r(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),tu=(e,t)=>{let r=ev(t),a="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,a])=>({...e,[t]:tn(a._def,{...r,currentPath:[...r.basePath,r.definitionPath,t]},!0)??{}}),{}):void 0,i="string"==typeof t?t:t?.nameStrategy==="title"?void 0:t?.name,n=tn(e._def,void 0===i?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??{},s="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==s&&(n.title=s);let o=void 0===i?a?{...n,[r.definitionPath]:a}:n:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...a,[i]:n}};return"jsonSchema7"===r.target?o.$schema="http://json-schema.org/draft-07/schema#":("jsonSchema2019-09"===r.target||"openAi"===r.target)&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===r.target&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o};function tc(e){if("object"==typeof e&&null!==e){let t={...e};for(let e in"additionalProperties"in t&&delete t.additionalProperties,"$schema"in t&&delete t.$schema,t)e in t&&(Array.isArray(t[e])?t[e]=t[e].map(tc):"object"==typeof t[e]&&null!==t[e]&&(t[e]=tc(t[e])));return t}return e}function th(e){let{$schema:t,...r}=tc(tu(e));return r}function td(e){let{$schema:t,...r}=tc(e);return r}var tp=r(5415),tf=r(43399),tm=r(46628),tg=r(97832);function ty(e){let t=e._getType();return tp.cM.isInstance(e)?e.role:"tool"===t?t:e.name??t}function tb(e){switch(e){case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw Error(`Unknown / unsupported author: ${e}`)}}function t_(e){if("mimeType"in e&&"data"in e)return{inlineData:{mimeType:e.mimeType,data:e.data}};if("mimeType"in e&&"fileUri"in e)return{fileData:{mimeType:e.mimeType,fileUri:e.fileUri}};throw Error("Invalid media content")}function tw(e,t){if("string"==typeof e.content&&""!==e.content)return[{text:e.content}];let r=[],a=[],i=[];return"tool_calls"in e&&Array.isArray(e.tool_calls)&&e.tool_calls.length>0?r=e.tool_calls.map(e=>({functionCall:{name:e.name,args:e.args}})):"tool"===e.getType()&&e.name&&e.content?a=[{functionResponse:{name:e.name,response:e.content}}]:Array.isArray(e.content)&&(i=e.content.map(e=>{if("text"===e.type)return{text:e.text};if("executableCode"===e.type)return{executableCode:e.executableCode};if("codeExecutionResult"===e.type)return{codeExecutionResult:e.codeExecutionResult};if("image_url"===e.type){let r;if(!t)throw Error("This model does not support images");if("string"==typeof e.image_url)r=e.image_url;else if("object"==typeof e.image_url&&"url"in e.image_url)r=e.image_url.url;else throw Error("Please provide image as base64 encoded data URL");let[a,i]=r.split(",");if(!a.startsWith("data:"))throw Error("Please provide image as base64 encoded data URL");let[n,s]=a.replace(/^data:/,"").split(";");if("base64"!==s)throw Error("Please provide image as base64 encoded data URL");return{inlineData:{data:i,mimeType:n}}}if("media"===e.type)return t_(e);if("tool_use"===e.type)return{functionCall:{name:e.name,args:e.input}};if(e.type?.includes("/")&&2===e.type.split("/").length&&"data"in e&&"string"==typeof e.data)return{inlineData:{mimeType:e.type,data:e.data}};throw Error(`Unknown content type ${e.type}`)})),[...i,...r,...a]}function tv(e,t,r=!1){return e.reduce((e,a,i)=>{if(!(0,tp.ny)(a))throw Error("Unsupported message input");let n=ty(a);if("system"===n&&0!==i)throw Error("System message should be the first one");let s=tb(n),o=e.content[e.content.length];if(!e.mergeWithPreviousContent&&o&&o.role===s)throw Error("Google Generative AI requires alternate messages between authors");let l=tw(a,t);if(e.mergeWithPreviousContent){let t=e.content[e.content.length-1];if(!t)throw Error("There was a problem parsing your system message. Please try a prompt without one.");return t.parts.push(...l),{mergeWithPreviousContent:!1,content:e.content}}let u=s;"function"!==u&&("system"!==u||r)||(u="user");let c={role:u,parts:l};return{mergeWithPreviousContent:"system"===n&&!r,content:[...e.content,c]}},{content:[],mergeWithPreviousContent:!1}).content}function tO(e,t){let r;if(!e.candidates||0===e.candidates.length||!e.candidates[0])return{generations:[],llmOutput:{filters:e.promptFeedback}};let a=e.functionCalls(),[i]=e.candidates,{content:n,...s}=i;r=n?.parts.length===1&&n.parts[0].text?n.parts[0].text:n.parts.map(e=>"text"in e?{type:"text",text:e.text}:"executableCode"in e?{type:"executableCode",executableCode:e.executableCode}:"codeExecutionResult"in e?{type:"codeExecutionResult",codeExecutionResult:e.codeExecutionResult}:e);let o="";return"string"==typeof r?o=r:"text"in r[0]&&(o=r[0].text),{generations:[{text:o,message:new tp.Od({content:r,tool_calls:a?.map(e=>({...e,type:"tool_call"})),additional_kwargs:{...s},usage_metadata:t?.usageMetadata}),generationInfo:s}],llmOutput:{tokenUsage:{promptTokens:t?.usageMetadata?.input_tokens,completionTokens:t?.usageMetadata?.output_tokens,totalTokens:t?.usageMetadata?.total_tokens}}}}function tE(e,t){let r;if(!e.candidates||0===e.candidates.length)return null;let a=e.functionCalls(),[i]=e.candidates,{content:n,...s}=i;n?.parts&&n.parts.every(e=>"text"in e)?r=n.parts.map(e=>e.text).join(""):n.parts&&(r=n.parts.map(e=>"text"in e?{type:"text",text:e.text}:"executableCode"in e?{type:"executableCode",executableCode:e.executableCode}:"codeExecutionResult"in e?{type:"codeExecutionResult",codeExecutionResult:e.codeExecutionResult}:e));let o="";r&&"string"==typeof r?o=r:r&&"object"==typeof r&&"text"in r[0]&&(o=r[0].text);let l=[];return a&&l.push(...a.map(e=>({...e,args:JSON.stringify(e.args),index:t.index,type:"tool_call_chunk"}))),new tf.Cf({text:o,message:new tp.H({content:r||"",name:n?n.role:void 0,tool_call_chunks:l,additional_kwargs:{},usage_metadata:t.usageMetadata}),generationInfo:s})}function tk(e){return e.every(e=>"functionDeclarations"in e&&Array.isArray(e.functionDeclarations))?e:[{functionDeclarations:e.map(e=>{if((0,tm.qG)(e)){let t=th(e.schema);return{name:e.name,description:e.description,parameters:t}}return(0,tg.VC)(e)?{name:e.function.name,description:e.function.description??"A function available to call.",parameters:td(e.function.parameters)}:e})}]}var tx=r(3909);class tS extends tx.vd{static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","google_genai","output_parsers"]}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(void 0===this.zodSchema)return e;let t=await this.zodSchema.safeParseAsync(e);if(t.success)return t.data;throw new tx.CC(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error.errors)}`,JSON.stringify(e,null,2))}async parseResult(e){let t=e.flatMap(e=>{let{message:t}=e;return"tool_calls"in t&&Array.isArray(t.tool_calls)?t.tool_calls:[]});if(void 0===t[0])throw Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");let[r]=t;return await this._validateResult(r.args)}}function tA(e,t){let r=tP(e),a=tI(r,t);return{tools:r,toolConfig:a}}function tP(e){let t=[],r=[];return(e.forEach(e=>{if((0,tm.qG)(e)){let[r]=tk([e]);r.functionDeclarations&&t.push(...r.functionDeclarations)}else if((0,tg.VC)(e)){let{functionDeclarations:r}=tT(e);if(r)t.push(...r);else throw Error("Failed to convert OpenAI structured tool to GenerativeAI tool")}else r.push(e)}),r.find(e=>"functionDeclarations"in e))?r.map(e=>{if(t?.length>0&&"functionDeclarations"in e){let r={functionDeclarations:[...e.functionDeclarations||[],...t]};return t=[],r}return e}):[...r,...t.length>0?[{functionDeclarations:t}]:[]]}function tT(e){return{functionDeclarations:[{name:e.function.name,description:e.function.description,parameters:tc(e.function.parameters)}]}}function tI(e,t){if(!e.length||!t)return;let{toolChoice:r,allowedFunctionNames:a}=t,i={any:eh.ANY,auto:eh.AUTO,none:eh.NONE};return r&&["any","auto","none"].includes(r)?{functionCallingConfig:{mode:i[r]??"MODE_UNSPECIFIED",allowedFunctionNames:a}}:"string"==typeof r||a?{functionCallingConfig:{mode:eh.ANY,allowedFunctionNames:[...a??[],...r&&"string"==typeof r?[r]:[]]}}:void 0}class tN extends em.xV{static lc_name(){return"ChatGoogleGenerativeAI"}get lc_secrets(){return{apiKey:"GOOGLE_API_KEY"}}get lc_aliases(){return{apiKey:"google_api_key"}}get _isMultimodalModel(){return this.model.includes("vision")||this.model.startsWith("gemini-1.5")||this.model.startsWith("gemini-2")}constructor(e){if(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","chat_models","google_genai"]}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:"gemini-pro"}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"gemini-pro"}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxOutputTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topK",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stopSequences",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"safetySettings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"convertSystemMessageToHumanContent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.modelName=e?.model?.replace(/^models\//,"")??e?.modelName?.replace(/^models\//,"")??this.model,this.model=this.modelName,this.maxOutputTokens=e?.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw Error("`maxOutputTokens` must be a positive integer");if(this.temperature=e?.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw Error("`temperature` must be in the range of [0.0,2.0]");if(this.topP=e?.topP??this.topP,this.topP&&this.topP<0)throw Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw Error("`topP` must be below 1.");if(this.topK=e?.topK??this.topK,this.topK&&this.topK<0)throw Error("`topK` must be a positive integer");if(this.stopSequences=e?.stopSequences??this.stopSequences,this.apiKey=e?.apiKey??(0,ef.Az)("GOOGLE_API_KEY"),!this.apiKey)throw Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");if(this.safetySettings=e?.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0&&new Set(this.safetySettings.map(e=>e.category)).size!==this.safetySettings.length)throw Error("The categories in `safetySettings` array must be unique");this.streaming=e?.streaming??this.streaming,this.client=new et(this.apiKey).getGenerativeModel({model:this.model,safetySettings:this.safetySettings,generationConfig:{candidateCount:1,stopSequences:this.stopSequences,maxOutputTokens:this.maxOutputTokens,temperature:this.temperature,topP:this.topP,topK:this.topK,...e?.json?{responseMimeType:"application/json"}:{}}},{apiVersion:e?.apiVersion,baseUrl:e?.baseUrl}),this.streamUsage=e?.streamUsage??this.streamUsage}useCachedContent(e,t,r){this.apiKey&&(this.client=new et(this.apiKey).getGenerativeModelFromCachedContent(e,t,r))}get useSystemInstruction(){return"boolean"==typeof this.convertSystemMessageToHumanContent?!this.convertSystemMessageToHumanContent:this.computeUseSystemInstruction}get computeUseSystemInstruction(){return!("gemini-1.0-pro-001"===this.modelName||this.modelName.startsWith("gemini-pro-vision"))&&!this.modelName.startsWith("gemini-1.0-pro-vision")&&"gemini-pro"!==this.modelName}getLsParams(e){return{ls_provider:"google_genai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:this.client.generationConfig.temperature,ls_max_tokens:this.client.generationConfig.maxOutputTokens,ls_stop:e.stop}}_combineLLMOutput(){return[]}_llmType(){return"googlegenerativeai"}bindTools(e,t){return this.bind({tools:tA(e)?.tools,...t})}invocationParams(e){let t=e?.tools?.length?tA(e.tools,{toolChoice:e.tool_choice,allowedFunctionNames:e.allowedFunctionNames}):void 0;return{...t?.tools?{tools:t.tools}:{},...t?.toolConfig?{toolConfig:t.toolConfig}:{}}}async _generate(e,t,r){let a;let i=tv(e,this._isMultimodalModel,this.useSystemInstruction),n=i;if("system"===i[0].role){let[e]=i;this.client.systemInstruction=e,n=i.slice(1)}let s=this.invocationParams(t);if(this.streaming){let a={},i=this._streamResponseChunks(e,t,r),n={};for await(let e of i){let t=e.generationInfo?.completion??0;void 0===n[t]?n[t]=e:n[t]=n[t].concat(e)}return{generations:Object.entries(n).sort(([e],[t])=>parseInt(e,10)-parseInt(t,10)).map(([e,t])=>t),llmOutput:{estimatedTokenUsage:a}}}let o=await this.completionWithRetry({...s,contents:n});if("usageMetadata"in o.response){let e=o.response.usageMetadata;a={input_tokens:e.promptTokenCount??0,output_tokens:e.candidatesTokenCount??0,total_tokens:e.totalTokenCount??0}}let l=tO(o.response,{usageMetadata:a});return await r?.handleLLMNewToken(l.generations[0].text??""),l}async *_streamResponseChunks(e,t,r){let a;let i=tv(e,this._isMultimodalModel,this.useSystemInstruction),n=i;if("system"===i[0].role){let[e]=i;this.client.systemInstruction=e,n=i.slice(1)}let s={...this.invocationParams(t),contents:n},o=await this.caller.callWithOptions({signal:t?.signal},async()=>{let{stream:e}=await this.client.generateContentStream(s);return e}),l=0;for await(let e of o){if("usageMetadata"in e&&!1!==this.streamUsage&&!1!==t.streamUsage){let t=e.usageMetadata;if(a){let e=(t.candidatesTokenCount??0)-a.output_tokens;a={input_tokens:0,output_tokens:e,total_tokens:e}}else a={input_tokens:t.promptTokenCount??0,output_tokens:t.candidatesTokenCount??0,total_tokens:t.totalTokenCount??0}}let i=tE(e,{usageMetadata:a,index:l});l+=1,i&&(yield i,await r?.handleLLMNewToken(i.text??""))}}async completionWithRetry(e,t){return this.caller.callWithOptions({signal:t?.signal},async()=>{try{return await this.client.generateContent(e)}catch(e){throw e.message?.includes("400 Bad Request")&&(e.status=400),e}})}withStructuredOutput(e,t){let r,a;let i=e,n=t?.name,s=t?.method,o=t?.includeRaw;if("jsonMode"===s)throw Error('ChatGoogleGenerativeAI only supports "functionCalling" as a method.');let l=n??"extract";if((0,ey.l)(i)){let e=th(i);a=[{functionDeclarations:[{name:l,description:e.description??"A function available to call.",parameters:e}]}],r=new tS({returnSingle:!0,keyName:l,zodSchema:i})}else{let e;"string"==typeof i.name&&"object"==typeof i.parameters&&null!=i.parameters?(e=i,l=i.name):e={name:l,description:i.description??"",parameters:i},a=[{functionDeclarations:[e]}],r=new tS({returnSingle:!0,keyName:l})}let u=this.bind({tools:a,tool_choice:l});if(!o)return u.pipe(r).withConfig({runName:"ChatGoogleGenerativeAIStructuredOutput"});let c=eg.kI.assign({parsed:(e,t)=>r.invoke(e.raw,t)}),h=eg.kI.assign({parsed:()=>null}),d=c.withFallbacks({fallbacks:[h]});return eg.zZ.from([{raw:u},d]).withConfig({runName:"StructuredOutputRunnable"})}}var tj=r(72257),tR=r(55853);class tC extends tj.J{constructor(e){if(super(e??{}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:"embedding-001"}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"embedding-001"}),Object.defineProperty(this,"taskType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"title",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stripNewLines",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"maxBatchSize",{enumerable:!0,configurable:!0,writable:!0,value:100}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.modelName=e?.model?.replace(/^models\//,"")??e?.modelName?.replace(/^models\//,"")??this.modelName,this.model=this.modelName,this.taskType=e?.taskType??this.taskType,this.title=e?.title??this.title,this.title&&"RETRIEVAL_DOCUMENT"!==this.taskType)throw Error("title can only be sepcified with TaskType.RETRIEVAL_DOCUMENT");if(this.apiKey=e?.apiKey??(0,ef.Az)("GOOGLE_API_KEY"),!this.apiKey)throw Error("Please set an API key for Google GenerativeAI in the environmentb variable GOOGLE_API_KEY or in the `apiKey` field of the GoogleGenerativeAIEmbeddings constructor");this.client=new et(this.apiKey).getGenerativeModel({model:this.model})}_convertToContent(e){return{content:{role:"user",parts:[{text:this.stripNewLines?e.replace(/\n/g," "):e}]},taskType:this.taskType,title:this.title}}async _embedQueryContent(e){let t=this._convertToContent(e);return(await this.client.embedContent(t)).embedding.values??[]}async _embedDocumentsContent(e){let t=(0,tR.l)(e,this.maxBatchSize),r=t.map(e=>({requests:e.map(e=>this._convertToContent(e))}));return(await Promise.allSettled(r.map(e=>this.client.batchEmbedContents(e)))).flatMap((e,r)=>"fulfilled"===e.status?e.value.embeddings.map(e=>e.values||[]):Array(t[r].length).fill([]))}embedQuery(e){return this.caller.call(this._embedQueryContent.bind(this),e)}embedDocuments(e){return this.caller.call(this._embedDocumentsContent.bind(this),e)}}},15395:e=>{class t{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(void 0!==t)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&void 0!==t){if(this.map.size>=this.max){let e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}e.exports=t},16587:(e,t,r)=>{let a=r(88193);e.exports=(e,t,r)=>a(t,e,r)},17877:(e,t,r)=>{let a=r(42870);e.exports=(e,t,r)=>(e=new a(e,r),t=new a(t,r),e.intersects(t,r))},18056:(e,t,r)=>{"use strict";r.d(t,{A:()=>i});let a=/^(?:[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,i=function(e){return"string"==typeof e&&a.test(e)}},18313:e=>{"use strict";function t(e){return Error("Can only stringify objects, not "+e)}function r(){return Error("Array values can't have mixed types")}function a(e){return Object.keys(e).filter(t=>o(e[t]))}function i(e){return Object.keys(e).filter(t=>!o(e[t]))}function n(e){let t=Array.isArray(e)?[]:Object.prototype.hasOwnProperty.call(e,"__proto__")?{["__proto__"]:void 0}:{};for(let r of Object.keys(e))!e[r]||"function"!=typeof e[r].toJSON||"toISOString"in e[r]?t[r]=e[r]:t[r]=e[r].toJSON();return t}function s(e,t,r){var s=a(r=n(r)),o=i(r),c=[],h=t||"";s.forEach(e=>{var t=l(r[e]);"undefined"!==t&&"null"!==t&&c.push(h+u(e)+" = "+m(r[e],!0))}),c.length>0&&c.push("");var d=e&&s.length>0?t+" ":"";return o.forEach(t=>{c.push(S(e,d,t,r[t]))}),c.join("\n")}function o(e){switch(l(e)){case"undefined":case"null":case"integer":case"nan":case"float":case"boolean":case"string":case"datetime":return!0;case"array":return 0===e.length||"table"!==l(e[0]);case"table":return 0===Object.keys(e).length;default:return!1}}function l(e){if(void 0===e)return"undefined";if(null===e)return"null";if("bigint"==typeof e||Number.isInteger(e)&&!Object.is(e,-0))return"integer";if("number"==typeof e)return"float";if("boolean"==typeof e)return"boolean";else if("string"==typeof e)return"string";else if("toISOString"in e)return isNaN(e)?"undefined":"datetime";else if(Array.isArray(e))return"array";else return"table"}function u(e){var t=String(e);return/^[-A-Za-z0-9_]+$/.test(t)?t:c(t)}function c(e){return'"'+p(e).replace(/"/g,'\\"')+'"'}function h(e){return"'"+e+"'"}function d(e,t){for(;t.length"\\u"+d(4,e.codePointAt(0).toString(16)))}function f(e){let t=e.split(/\n/).map(e=>p(e).replace(/"(?="")/g,'\\"')).join("\n");return'"'===t.slice(-1)&&(t+="\\\n"),'"""\n'+t+'"""'}function m(e,t){let r=l(e);return"string"===r&&(t&&/\n/.test(e)?r="string-multiline":!/[\b\t\n\f\r']/.test(e)&&/"/.test(e)&&(r="string-literal")),g(e,r)}function g(e,r){switch(r||(r=l(e)),r){case"string-multiline":return f(e);case"string":return c(e);case"string-literal":return h(e);case"integer":return y(e);case"float":return b(e);case"boolean":return _(e);case"datetime":return w(e);case"array":return k(e.filter(e=>"null"!==l(e)&&"undefined"!==l(e)&&"nan"!==l(e)));case"table":return x(e);default:throw t(r)}}function y(e){return String(e).replace(/\B(?=(\d{3})+(?!\d))/g,"_")}function b(e){if(e===1/0)return"inf";if(e===-1/0)return"-inf";if(Object.is(e,NaN))return"nan";if(Object.is(e,-0))return"-0.0";var t=String(e).split("."),r=t[0],a=t[1]||0;return y(r)+"."+a}function _(e){return String(e)}function w(e){return e.toISOString()}function v(e){return"float"===e||"integer"===e}function O(e){var t=l(e[0]);return e.every(e=>l(e)===t)?t:e.every(e=>v(l(e)))?"float":"mixed"}function E(e){let t=O(e);if("mixed"===t)throw r();return t}function k(e){let t=E(e=n(e));var r="[",a=e.map(e=>g(e,t));return a.join(", ").length>60||/\n/.test(a)?r+="\n "+a.join(",\n ")+"\n":r+=" "+a.join(", ")+(a.length>0?" ":""),r+"]"}function x(e){e=n(e);var t=[];return Object.keys(e).forEach(r=>{t.push(u(r)+" = "+m(e[r],!1))}),"{ "+t.join(", ")+(t.length>0?" ":"")+"}"}function S(e,r,a,i){var n=l(i);if("array"===n)return A(e,r,a,i);if("table"===n)return P(e,r,a,i);throw t(n)}function A(e,r,a,i){E(i=n(i));var o=l(i[0]);if("table"!==o)throw t(o);var c=e+u(a),h="";return i.forEach(e=>{h.length>0&&(h+="\n"),h+=r+"[["+c+"]]\n",h+=s(c+".",r,e)}),h}function P(e,t,r,i){var n=e+u(r),o="";return a(i).length>0&&(o+=t+"["+n+"]\n"),o+s(n+".",t,i)}e.exports=function e(e){if(null===e)throw t("null");if(void 0===e)throw t("undefined");if("object"!=typeof e)throw t(typeof e);if("function"==typeof e.toJSON&&(e=e.toJSON()),null==e)return null;let r=l(e);if("table"!==r)throw t(r);return s("","",e)},e.exports.value=g},19277:(e,t,r)=>{let a=r(36053),i=r(42870);e.exports=(e,t,r)=>{let n=null,s=null,o=null;try{o=new i(t,r)}catch(e){return null}return e.forEach(e=>{o.test(e)&&(!n||-1===s.compare(e))&&(s=new a(n=e,r))}),n}},19839:(e,t,r)=>{"use strict";r.d(t,{vR:()=>u,GZ:()=>c});var a=r(11259);class i{getStore(){}run(e,t){return t()}}let n=Symbol.for("ls:tracing_async_local_storage"),s=new i;class o{getInstance(){return globalThis[n]??s}initializeGlobalInstance(e){void 0===globalThis[n]&&(globalThis[n]=e)}}let l=new o,u=()=>{let e=l.getInstance().getStore();if(!(0,a.m5)(e))throw 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 c(e){return"function"==typeof e&&"langsmith:traceable"in e}Symbol.for("langsmith:traceable:root")},19902:(e,t,r)=>{let a=r(36053);e.exports=(e,t,r,i,n)=>{"string"==typeof r&&(n=i,i=r,r=void 0);try{return new a(e instanceof a?e.version:e,r).inc(t,i,n).version}catch(e){return null}}},19918:(e,t,r)=>{"use strict";e.exports=n;let a=r(62806),i=r(87096);function n(e){return e?s(e):o(e)}function s(e){let t=new i;return e.setEncoding("utf8"),new Promise((r,a)=>{let i;let n=!1,s=!1;function o(){if(n=!0,!i)try{r(t.finish())}catch(e){a(e)}}function l(e){s=!0,a(e)}function u(){let r;for(i=!0;null!==(r=e.read());)try{t.parse(r)}catch(e){return l(e)}if(i=!1,n)return o();s||e.once("readable",u)}e.once("end",o),e.once("error",l),u()})}function o(){let e=new i;return new a.Transform({objectMode:!0,transform(t,r,a){try{e.parse(t.toString(r))}catch(e){this.emit("error",e)}a()},flush(t){try{this.push(e.finish())}catch(e){this.emit("error",e)}t()}})}},21232:e=>{"use strict";e.exports=(e,t)=>(t=t||(()=>{}),e.then(e=>new Promise(e=>{e(t())}).then(()=>e),e=>new Promise(e=>{e(t())}).then(()=>{throw e})))},23255:(e,t,r)=>{let a=r(34290);e.exports=(e,t,r)=>a(e,t,"<",r)},23294:(e,t,r)=>{"use strict";r.d(t,{Cf:()=>n,SP:()=>a,mu:()=>i});let a="__run";class i{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 i({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}}class n extends i{constructor(e){super(e),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.message=e.message}concat(e){return new n({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo},message:this.message.concat(e.message)})}}},23464:(e,t,r)=>{"use strict";let a,i,n;r.d(t,{A:()=>tX});var s={};function o(e,t){return function(){return e.apply(t,arguments)}}r.r(s),r.d(s,{hasBrowserEnv:()=>e$,hasStandardBrowserEnv:()=>eL,hasStandardBrowserWebWorkerEnv:()=>eU,navigator:()=>eM,origin:()=>eD});var l=r(49509);let{toString:u}=Object.prototype,{getPrototypeOf:c}=Object,h=(e=>t=>{let r=u.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),d=e=>(e=e.toLowerCase(),t=>h(t)===e),p=e=>t=>typeof t===e,{isArray:f}=Array,m=p("undefined");function g(e){return null!==e&&!m(e)&&null!==e.constructor&&!m(e.constructor)&&w(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}let y=d("ArrayBuffer");function b(e){let t;return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&y(e.buffer)}let _=p("string"),w=p("function"),v=p("number"),O=e=>null!==e&&"object"==typeof e,E=e=>!0===e||!1===e,k=e=>{if("object"!==h(e))return!1;let t=c(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},x=d("Date"),S=d("File"),A=d("Blob"),P=d("FileList"),T=e=>O(e)&&w(e.pipe),I=e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||w(e.append)&&("formdata"===(t=h(e))||"object"===t&&w(e.toString)&&"[object FormData]"===e.toString()))},N=d("URLSearchParams"),[j,R,C,$]=["ReadableStream","Request","Response","Headers"].map(d),M=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function L(e,t,{allOwnKeys:r=!1}={}){let a,i;if(null!=e){if("object"!=typeof e&&(e=[e]),f(e))for(a=0,i=e.length;a0;)if(t===(r=a[i]).toLowerCase())return r;return null}let D="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,F=e=>!m(e)&&e!==D;function B(){let{caseless:e}=F(this)&&this||{},t={},r=(r,a)=>{let i=e&&U(t,a)||a;k(t[i])&&k(r)?t[i]=B(t[i],r):k(r)?t[i]=B({},r):f(r)?t[i]=r.slice():t[i]=r};for(let e=0,t=arguments.length;e(L(t,(t,a)=>{r&&w(t)?e[a]=o(t,r):e[a]=t},{allOwnKeys:a}),e),H=e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),Z=(e,t,r,a)=>{e.prototype=Object.create(t.prototype,a),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},q=(e,t,r,a)=>{let i,n,s;let o={};if(t=t||{},null==e)return t;do{for(n=(i=Object.getOwnPropertyNames(e)).length;n-- >0;)s=i[n],(!a||a(s,e,t))&&!o[s]&&(t[s]=e[s],o[s]=!0);e=!1!==r&&c(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},G=(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;let a=e.indexOf(t,r);return -1!==a&&a===r},W=e=>{if(!e)return null;if(f(e))return e;let t=e.length;if(!v(t))return null;let r=Array(t);for(;t-- >0;)r[t]=e[t];return r},K=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&c(Uint8Array)),J=(e,t)=>{let r;let a=(e&&e[Symbol.iterator]).call(e);for(;(r=a.next())&&!r.done;){let a=r.value;t.call(e,a[0],a[1])}},Y=(e,t)=>{let r;let a=[];for(;null!==(r=e.exec(t));)a.push(r);return a},V=d("HTMLFormElement"),X=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,r){return t.toUpperCase()+r}),Q=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),ee=d("RegExp"),et=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),a={};L(r,(r,i)=>{let n;!1!==(n=t(r,i,e))&&(a[i]=n||r)}),Object.defineProperties(e,a)},er=e=>{et(e,(t,r)=>{if(w(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;if(w(e[r])){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},ea=(e,t)=>{let r={};return(e=>{e.forEach(e=>{r[e]=!0})})(f(e)?e:String(e).split(t)),r},ei=()=>{},en=(e,t)=>null!=e&&Number.isFinite(e*=1)?e:t;function es(e){return!!(e&&w(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator])}let eo=e=>{let t=Array(10),r=(e,a)=>{if(O(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[a]=e;let i=f(e)?[]:{};return L(e,(e,t)=>{let n=r(e,a+1);m(n)||(i[t]=n)}),t[a]=void 0,i}}return e};return r(e,0)},el=d("AsyncFunction"),eu=e=>e&&(O(e)||w(e))&&w(e.then)&&w(e.catch),ec=(i="function"==typeof setImmediate,n=w(D.postMessage),i?setImmediate:n?((e,t)=>(D.addEventListener("message",({source:r,data:a})=>{r===D&&a===e&&t.length&&t.shift()()},!1),r=>{t.push(r),D.postMessage(e,"*")}))(`axios@${Math.random()}`,[]):e=>setTimeout(e)),eh="undefined"!=typeof queueMicrotask?queueMicrotask.bind(D):void 0!==l&&l.nextTick||ec,ed={isArray:f,isArrayBuffer:y,isBuffer:g,isFormData:I,isArrayBufferView:b,isString:_,isNumber:v,isBoolean:E,isObject:O,isPlainObject:k,isReadableStream:j,isRequest:R,isResponse:C,isHeaders:$,isUndefined:m,isDate:x,isFile:S,isBlob:A,isRegExp:ee,isFunction:w,isStream:T,isURLSearchParams:N,isTypedArray:K,isFileList:P,forEach:L,merge:B,extend:z,trim:M,stripBOM:H,inherits:Z,toFlatObject:q,kindOf:h,kindOfTest:d,endsWith:G,toArray:W,forEachEntry:J,matchAll:Y,isHTMLForm:V,hasOwnProperty:Q,hasOwnProp:Q,reduceDescriptors:et,freezeMethods:er,toObjectSet:ea,toCamelCase:X,noop:ei,toFiniteNumber:en,findKey:U,global:D,isContextDefined:F,isSpecCompliantForm:es,toJSONObject:eo,isAsyncFn:el,isThenable:eu,setImmediate:ec,asap:eh};function ep(e,t,r,a,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),a&&(this.request=a),i&&(this.response=i,this.status=i.status?i.status:null)}ed.inherits(ep,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ed.toJSONObject(this.config),code:this.code,status:this.status}}});let ef=ep.prototype,em={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{em[e]={value:e}}),Object.defineProperties(ep,em),Object.defineProperty(ef,"isAxiosError",{value:!0}),ep.from=(e,t,r,a,i,n)=>{let s=Object.create(ef);return ed.toFlatObject(e,s,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),ep.call(s,e.message,t,r,a,i),s.cause=e,s.name=e.name,n&&Object.assign(s,n),s};let eg=ep,ey=null;var eb=r(44134).Buffer;function e_(e){return ed.isPlainObject(e)||ed.isArray(e)}function ew(e){return ed.endsWith(e,"[]")?e.slice(0,-2):e}function ev(e,t,r){return e?e.concat(t).map(function(e,t){return e=ew(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}function eO(e){return ed.isArray(e)&&!e.some(e_)}let eE=ed.toFlatObject(ed,{},null,function(e){return/^is[A-Z]/.test(e)}),ek=function(e,t,r){if(!ed.isObject(e))throw TypeError("target must be an object");t=t||new(ey||FormData);let a=(r=ed.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!ed.isUndefined(t[e])})).metaTokens,i=r.visitor||u,n=r.dots,s=r.indexes,o=(r.Blob||"undefined"!=typeof Blob&&Blob)&&ed.isSpecCompliantForm(t);if(!ed.isFunction(i))throw TypeError("visitor must be a function");function l(e){if(null===e)return"";if(ed.isDate(e))return e.toISOString();if(!o&&ed.isBlob(e))throw new eg("Blob is not supported. Use a Buffer instead.");return ed.isArrayBuffer(e)||ed.isTypedArray(e)?o&&"function"==typeof Blob?new Blob([e]):eb.from(e):e}function u(e,r,i){let o=e;if(e&&!i&&"object"==typeof e){if(ed.endsWith(r,"{}"))r=a?r:r.slice(0,-2),e=JSON.stringify(e);else if(ed.isArray(e)&&eO(e)||(ed.isFileList(e)||ed.endsWith(r,"[]"))&&(o=ed.toArray(e)))return r=ew(r),o.forEach(function(e,a){ed.isUndefined(e)||null===e||t.append(!0===s?ev([r],a,n):null===s?r:r+"[]",l(e))}),!1}return!!e_(e)||(t.append(ev(i,r,n),l(e)),!1)}let c=[],h=Object.assign(eE,{defaultVisitor:u,convertValue:l,isVisitable:e_});function d(e,r){if(!ed.isUndefined(e)){if(-1!==c.indexOf(e))throw Error("Circular reference detected in "+r.join("."));c.push(e),ed.forEach(e,function(e,a){!0===(!(ed.isUndefined(e)||null===e)&&i.call(t,e,ed.isString(a)?a.trim():a,r,h))&&d(e,r?r.concat(a):[a])}),c.pop()}}if(!ed.isObject(e))throw TypeError("data must be an object");return d(e),t};function ex(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function eS(e,t){this._pairs=[],e&&ek(e,this,t)}let eA=eS.prototype;eA.append=function(e,t){this._pairs.push([e,t])},eA.toString=function(e){let t=e?function(t){return e.call(this,t,ex)}:ex;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};let eP=eS;function eT(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function eI(e,t,r){let a;if(!t)return e;let i=r&&r.encode||eT;ed.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize;if(a=n?n(t,r):ed.isURLSearchParams(t)?t.toString():new eP(t,r).toString(i)){let t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+a}return e}class eN{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){ed.forEach(this.handlers,function(t){null!==t&&e(t)})}}let ej=eN,eR={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},eC={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:eP,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},e$="undefined"!=typeof window&&"undefined"!=typeof document,eM="object"==typeof navigator&&navigator||void 0,eL=e$&&(!eM||0>["ReactNative","NativeScript","NS"].indexOf(eM.product)),eU="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,eD=e$&&window.location.href||"http://localhost",eF={...s,...eC};function eB(e,t){return ek(e,new eF.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,a){return eF.isNode&&ed.isBuffer(e)?(this.append(t,e.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function ez(e){return ed.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}function eH(e){let t,r;let a={},i=Object.keys(e),n=i.length;for(t=0;t=e.length;return(n=!n&&ed.isArray(a)?a.length:n,o)?ed.hasOwnProp(a,n)?a[n]=[a[n],r]:a[n]=r:(a[n]&&ed.isObject(a[n])||(a[n]=[]),t(e,r,a[n],i)&&ed.isArray(a[n])&&(a[n]=eH(a[n]))),!s}if(ed.isFormData(e)&&ed.isFunction(e.entries)){let r={};return ed.forEachEntry(e,(e,a)=>{t(ez(e),a,r,0)}),r}return null};function eq(e,t,r){if(ed.isString(e))try{return(t||JSON.parse)(e),ed.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}let eG={transitional:eR,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){let r;let a=t.getContentType()||"",i=a.indexOf("application/json")>-1,n=ed.isObject(e);if(n&&ed.isHTMLForm(e)&&(e=new FormData(e)),ed.isFormData(e))return i?JSON.stringify(eZ(e)):e;if(ed.isArrayBuffer(e)||ed.isBuffer(e)||ed.isStream(e)||ed.isFile(e)||ed.isBlob(e)||ed.isReadableStream(e))return e;if(ed.isArrayBufferView(e))return e.buffer;if(ed.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();if(n){if(a.indexOf("application/x-www-form-urlencoded")>-1)return eB(e,this.formSerializer).toString();if((r=ed.isFileList(e))||a.indexOf("multipart/form-data")>-1){let t=this.env&&this.env.FormData;return ek(r?{"files[]":e}:e,t&&new t,this.formSerializer)}}return n||i?(t.setContentType("application/json",!1),eq(e)):e}],transformResponse:[function(e){let t=this.transitional||eG.transitional,r=t&&t.forcedJSONParsing,a="json"===this.responseType;if(ed.isResponse(e)||ed.isReadableStream(e))return e;if(e&&ed.isString(e)&&(r&&!this.responseType||a)){let r=!(t&&t.silentJSONParsing)&&a;try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw eg.from(e,eg.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:eF.classes.FormData,Blob:eF.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ed.forEach(["delete","get","head","post","put","patch"],e=>{eG.headers[e]={}});let eW=eG,eK=ed.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),eJ=e=>{let t,r,a;let i={};return e&&e.split("\n").forEach(function(e){a=e.indexOf(":"),t=e.substring(0,a).trim().toLowerCase(),r=e.substring(a+1).trim(),t&&(!i[t]||!eK[t])&&("set-cookie"===t?i[t]?i[t].push(r):i[t]=[r]:i[t]=i[t]?i[t]+", "+r:r)}),i},eY=Symbol("internals");function eV(e){return e&&String(e).trim().toLowerCase()}function eX(e){return!1===e||null==e?e:ed.isArray(e)?e.map(eX):String(e)}function eQ(e){let t;let r=Object.create(null),a=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;for(;t=a.exec(e);)r[t[1]]=t[2];return r}let e0=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function e1(e,t,r,a,i){if(ed.isFunction(a))return a.call(this,t,r);if(i&&(t=r),ed.isString(t)){if(ed.isString(a))return -1!==t.indexOf(a);if(ed.isRegExp(a))return a.test(t)}}function e2(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,r)=>t.toUpperCase()+r)}function e4(e,t){let r=ed.toCamelCase(" "+t);["get","set","has"].forEach(a=>{Object.defineProperty(e,a+r,{value:function(e,r,i){return this[a].call(this,t,e,r,i)},configurable:!0})})}class e5{constructor(e){e&&this.set(e)}set(e,t,r){let a=this;function i(e,t,r){let i=eV(t);if(!i)throw Error("header name must be a non-empty string");let n=ed.findKey(a,i);n&&void 0!==a[n]&&!0!==r&&(void 0!==r||!1===a[n])||(a[n||t]=eX(e))}let n=(e,t)=>ed.forEach(e,(e,r)=>i(e,r,t));if(ed.isPlainObject(e)||e instanceof this.constructor)n(e,t);else if(ed.isString(e)&&(e=e.trim())&&!e0(e))n(eJ(e),t);else if(ed.isHeaders(e))for(let[t,a]of e.entries())i(a,t,r);else null!=e&&i(t,e,r);return this}get(e,t){if(e=eV(e)){let r=ed.findKey(this,e);if(r){let e=this[r];if(!t)return e;if(!0===t)return eQ(e);if(ed.isFunction(t))return t.call(this,e,r);if(ed.isRegExp(t))return t.exec(e);throw TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=eV(e)){let r=ed.findKey(this,e);return!!(r&&void 0!==this[r]&&(!t||e1(this,this[r],r,t)))}return!1}delete(e,t){let r=this,a=!1;function i(e){if(e=eV(e)){let i=ed.findKey(r,e);i&&(!t||e1(r,r[i],i,t))&&(delete r[i],a=!0)}}return ed.isArray(e)?e.forEach(i):i(e),a}clear(e){let t=Object.keys(this),r=t.length,a=!1;for(;r--;){let i=t[r];(!e||e1(this,this[i],i,e,!0))&&(delete this[i],a=!0)}return a}normalize(e){let t=this,r={};return ed.forEach(this,(a,i)=>{let n=ed.findKey(r,i);if(n){t[n]=eX(a),delete t[i];return}let s=e?e2(i):String(i).trim();s!==i&&delete t[i],t[s]=eX(a),r[s]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){let t=Object.create(null);return ed.forEach(this,(r,a)=>{null!=r&&!1!==r&&(t[a]=e&&ed.isArray(r)?r.join(", "):r)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){let r=new this(e);return t.forEach(e=>r.set(e)),r}static accessor(e){let t=(this[eY]=this[eY]={accessors:{}}).accessors,r=this.prototype;function a(e){let a=eV(e);t[a]||(e4(r,e),t[a]=!0)}return ed.isArray(e)?e.forEach(a):a(e),this}}e5.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),ed.reduceDescriptors(e5.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}}),ed.freezeMethods(e5);let e9=e5;function e3(e,t){let r=this||eW,a=t||r,i=e9.from(a.headers),n=a.data;return ed.forEach(e,function(e){n=e.call(r,n,i.normalize(),t?t.status:void 0)}),i.normalize(),n}function e6(e){return!!(e&&e.__CANCEL__)}function e8(e,t,r){eg.call(this,null==e?"canceled":e,eg.ERR_CANCELED,t,r),this.name="CanceledError"}ed.inherits(e8,eg,{__CANCEL__:!0});let e7=e8;function te(e,t,r){let a=r.config.validateStatus;!r.status||!a||a(r.status)?e(r):t(new eg("Request failed with status code "+r.status,[eg.ERR_BAD_REQUEST,eg.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function tt(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}let tr=function(e,t){let r;let a=Array(e=e||10),i=Array(e),n=0,s=0;return t=void 0!==t?t:1e3,function(o){let l=Date.now(),u=i[s];r||(r=l),a[n]=o,i[n]=l;let c=s,h=0;for(;c!==n;)h+=a[c++],c%=e;if((n=(n+1)%e)===s&&(s=(s+1)%e),l-r{i=n,r=null,a&&(clearTimeout(a),a=null),e.apply(null,t)};return[(...e)=>{let t=Date.now(),o=t-i;o>=n?s(e,t):(r=e,a||(a=setTimeout(()=>{a=null,s(r)},n-o)))},()=>r&&s(r)]},ti=(e,t,r=3)=>{let a=0,i=tr(50,250);return ta(r=>{let n=r.loaded,s=r.lengthComputable?r.total:void 0,o=n-a,l=i(o),u=n<=s;a=n,e({loaded:n,total:s,progress:s?n/s:void 0,bytes:o,rate:l||void 0,estimated:l&&s&&u?(s-n)/l:void 0,event:r,lengthComputable:null!=s,[t?"download":"upload"]:!0})},r)},tn=(e,t)=>{let r=null!=e;return[a=>t[0]({lengthComputable:r,total:e,loaded:a}),t[1]]},ts=e=>(...t)=>ed.asap(()=>e(...t)),to=eF.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,eF.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(eF.origin),eF.navigator&&/(msie|trident)/i.test(eF.navigator.userAgent)):()=>!0,tl=eF.hasStandardBrowserEnv?{write(e,t,r,a,i,n){let s=[e+"="+encodeURIComponent(t)];ed.isNumber(r)&&s.push("expires="+new Date(r).toGMTString()),ed.isString(a)&&s.push("path="+a),ed.isString(i)&&s.push("domain="+i),!0===n&&s.push("secure"),document.cookie=s.join("; ")},read(e){let t=document.cookie.match(RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function tu(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function tc(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function th(e,t,r){let a=!tu(t);return e&&a||!1==r?tc(e,t):t}let td=e=>e instanceof e9?{...e}:e;function tp(e,t){t=t||{};let r={};function a(e,t,r,a){return ed.isPlainObject(e)&&ed.isPlainObject(t)?ed.merge.call({caseless:a},e,t):ed.isPlainObject(t)?ed.merge({},t):ed.isArray(t)?t.slice():t}function i(e,t,r,i){return ed.isUndefined(t)?ed.isUndefined(e)?void 0:a(void 0,e,r,i):a(e,t,r,i)}function n(e,t){if(!ed.isUndefined(t))return a(void 0,t)}function s(e,t){return ed.isUndefined(t)?ed.isUndefined(e)?void 0:a(void 0,e):a(void 0,t)}function o(r,i,n){return n in t?a(r,i):n in e?a(void 0,r):void 0}let l={url:n,method:n,data:n,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:o,headers:(e,t,r)=>i(td(e),td(t),r,!0)};return ed.forEach(Object.keys(Object.assign({},e,t)),function(a){let n=l[a]||i,s=n(e[a],t[a],a);ed.isUndefined(s)&&n!==o||(r[a]=s)}),r}let tf=e=>{let t;let r=tp({},e),{data:a,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:s,headers:o,auth:l}=r;if(r.headers=o=e9.from(o),r.url=eI(th(r.baseURL,r.url,r.allowAbsoluteUrls),e.params,e.paramsSerializer),l&&o.set("Authorization","Basic "+btoa((l.username||"")+":"+(l.password?unescape(encodeURIComponent(l.password)):""))),ed.isFormData(a)){if(eF.hasStandardBrowserEnv||eF.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(!1!==(t=o.getContentType())){let[e,...r]=t?t.split(";").map(e=>e.trim()).filter(Boolean):[];o.setContentType([e||"multipart/form-data",...r].join("; "))}}if(eF.hasStandardBrowserEnv&&(i&&ed.isFunction(i)&&(i=i(r)),i||!1!==i&&to(r.url))){let e=n&&s&&tl.read(s);e&&o.set(n,e)}return r},tm="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,r){let a,i,n,s,o;let l=tf(e),u=l.data,c=e9.from(l.headers).normalize(),{responseType:h,onUploadProgress:d,onDownloadProgress:p}=l;function f(){s&&s(),o&&o(),l.cancelToken&&l.cancelToken.unsubscribe(a),l.signal&&l.signal.removeEventListener("abort",a)}let m=new XMLHttpRequest;function g(){if(!m)return;let a=e9.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());te(function(e){t(e),f()},function(e){r(e),f()},{data:h&&"text"!==h&&"json"!==h?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:a,config:e,request:m}),m=null}m.open(l.method.toUpperCase(),l.url,!0),m.timeout=l.timeout,"onloadend"in m?m.onloadend=g:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(g)},m.onabort=function(){m&&(r(new eg("Request aborted",eg.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new eg("Network Error",eg.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let t=l.timeout?"timeout of "+l.timeout+"ms exceeded":"timeout exceeded",a=l.transitional||eR;l.timeoutErrorMessage&&(t=l.timeoutErrorMessage),r(new eg(t,a.clarifyTimeoutError?eg.ETIMEDOUT:eg.ECONNABORTED,e,m)),m=null},void 0===u&&c.setContentType(null),"setRequestHeader"in m&&ed.forEach(c.toJSON(),function(e,t){m.setRequestHeader(t,e)}),ed.isUndefined(l.withCredentials)||(m.withCredentials=!!l.withCredentials),h&&"json"!==h&&(m.responseType=l.responseType),p&&([n,o]=ti(p,!0),m.addEventListener("progress",n)),d&&m.upload&&([i,s]=ti(d),m.upload.addEventListener("progress",i),m.upload.addEventListener("loadend",s)),(l.cancelToken||l.signal)&&(a=t=>{m&&(r(!t||t.type?new e7(null,e,m):t),m.abort(),m=null)},l.cancelToken&&l.cancelToken.subscribe(a),l.signal&&(l.signal.aborted?a():l.signal.addEventListener("abort",a)));let y=tt(l.url);if(y&&-1===eF.protocols.indexOf(y)){r(new eg("Unsupported protocol "+y+":",eg.ERR_BAD_REQUEST,e));return}m.send(u||null)})},tg=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,a=new AbortController,i=function(e){if(!r){r=!0,s();let t=e instanceof Error?e:this.reason;a.abort(t instanceof eg?t:new e7(t instanceof Error?t.message:t))}},n=t&&setTimeout(()=>{n=null,i(new eg(`timeout ${t} of ms exceeded`,eg.ETIMEDOUT))},t),s=()=>{e&&(n&&clearTimeout(n),n=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(i):e.removeEventListener("abort",i)}),e=null)};e.forEach(e=>e.addEventListener("abort",i));let{signal:o}=a;return o.unsubscribe=()=>ed.asap(s),o}},ty=function*(e,t){let r,a=e.byteLength;if(!t||a{let i;let n=tb(e,t),s=0,o=e=>{!i&&(i=!0,a&&a(e))};return new ReadableStream({async pull(e){try{let{done:t,value:a}=await n.next();if(t){o(),e.close();return}let i=a.byteLength;if(r){let e=s+=i;r(e)}e.enqueue(new Uint8Array(a))}catch(e){throw o(e),e}},cancel:e=>(o(e),n.return())},{highWaterMark:2})},tv="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,tO=tv&&"function"==typeof ReadableStream,tE=tv&&("function"==typeof TextEncoder?(a=new TextEncoder,e=>a.encode(e)):async e=>new Uint8Array(await new Response(e).arrayBuffer())),tk=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},tx=tO&&tk(()=>{let e=!1,t=new Request(eF.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),tS=65536,tA=tO&&tk(()=>ed.isReadableStream(new Response("").body)),tP={stream:tA&&(e=>e.body)};tv&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{tP[t]||(tP[t]=ed.isFunction(e[t])?e=>e[t]():(e,r)=>{throw new eg(`Response type '${t}' is not supported`,eg.ERR_NOT_SUPPORT,r)})})})(new Response);let tT=async e=>{if(null==e)return 0;if(ed.isBlob(e))return e.size;if(ed.isSpecCompliantForm(e)){let t=new Request(eF.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return ed.isArrayBufferView(e)||ed.isArrayBuffer(e)?e.byteLength:(ed.isURLSearchParams(e)&&(e+=""),ed.isString(e))?(await tE(e)).byteLength:void 0},tI=async(e,t)=>{let r=ed.toFiniteNumber(e.getContentLength());return null==r?tT(t):r},tN={http:ey,xhr:tm,fetch:tv&&(async e=>{let t,r,{url:a,method:i,data:n,signal:s,cancelToken:o,timeout:l,onDownloadProgress:u,onUploadProgress:c,responseType:h,headers:d,withCredentials:p="same-origin",fetchOptions:f}=tf(e);h=h?(h+"").toLowerCase():"text";let m=tg([s,o&&o.toAbortSignal()],l),g=m&&m.unsubscribe&&(()=>{m.unsubscribe()});try{if(c&&tx&&"get"!==i&&"head"!==i&&0!==(r=await tI(d,n))){let e,t=new Request(a,{method:"POST",body:n,duplex:"half"});if(ed.isFormData(n)&&(e=t.headers.get("content-type"))&&d.setContentType(e),t.body){let[e,a]=tn(r,ti(ts(c)));n=tw(t.body,tS,e,a)}}ed.isString(p)||(p=p?"include":"omit");let s="credentials"in Request.prototype;t=new Request(a,{...f,signal:m,method:i.toUpperCase(),headers:d.normalize().toJSON(),body:n,duplex:"half",credentials:s?p:void 0});let o=await fetch(t),l=tA&&("stream"===h||"response"===h);if(tA&&(u||l&&g)){let e={};["status","statusText","headers"].forEach(t=>{e[t]=o[t]});let t=ed.toFiniteNumber(o.headers.get("content-length")),[r,a]=u&&tn(t,ti(ts(u),!0))||[];o=new Response(tw(o.body,tS,r,()=>{a&&a(),g&&g()}),e)}h=h||"text";let y=await tP[ed.findKey(tP,h)||"text"](o,e);return!l&&g&&g(),await new Promise((r,a)=>{te(r,a,{data:y,headers:e9.from(o.headers),status:o.status,statusText:o.statusText,config:e,request:t})})}catch(r){if(g&&g(),r&&"TypeError"===r.name&&/fetch/i.test(r.message))throw Object.assign(new eg("Network Error",eg.ERR_NETWORK,e,t),{cause:r.cause||r});throw eg.from(r,r&&r.code,e,t)}})};ed.forEach(tN,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}});let tj=e=>`- ${e}`,tR=e=>ed.isFunction(e)||null===e||!1===e,tC={getAdapter:e=>{let t,r;let{length:a}=e=ed.isArray(e)?e:[e],i={};for(let n=0;n`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new eg("There is no suitable adapter to dispatch the request "+(a?e.length>1?"since :\n"+e.map(tj).join("\n"):" "+tj(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return r}};function t$(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new e7(null,e)}function tM(e){return t$(e),e.headers=e9.from(e.headers),e.data=e3.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1),tC.getAdapter(e.adapter||eW.adapter)(e).then(function(t){return t$(e),t.data=e3.call(e,e.transformResponse,t),t.headers=e9.from(t.headers),t},function(t){return!e6(t)&&(t$(e),t&&t.response&&(t.response.data=e3.call(e,e.transformResponse,t.response),t.response.headers=e9.from(t.response.headers))),Promise.reject(t)})}let tL="1.8.3",tU={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{tU[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});let tD={};tU.transitional=function(e,t,r){function a(e,t){return"[Axios v"+tL+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,i,n)=>{if(!1===e)throw new eg(a(i," has been removed"+(t?" in "+t:"")),eg.ERR_DEPRECATED);return t&&!tD[i]&&(tD[i]=!0,console.warn(a(i," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,i,n)}},tU.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};let tF={assertOptions:function(e,t,r){if("object"!=typeof e)throw new eg("options must be an object",eg.ERR_BAD_OPTION_VALUE);let a=Object.keys(e),i=a.length;for(;i-- >0;){let n=a[i],s=t[n];if(s){let t=e[n],r=void 0===t||s(t,n,e);if(!0!==r)throw new eg("option "+n+" must be "+r,eg.ERR_BAD_OPTION_VALUE);continue}if(!0!==r)throw new eg("Unknown option "+n,eg.ERR_BAD_OPTION)}},validators:tU},tB=tF.validators;class tz{constructor(e){this.defaults=e,this.interceptors={request:new ej,response:new ej}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=Error();let r=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?r&&!String(e.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+r):e.stack=r}catch(e){}}throw e}}_request(e,t){let r,a;"string"==typeof e?(t=t||{}).url=e:t=e||{};let{transitional:i,paramsSerializer:n,headers:s}=t=tp(this.defaults,t);void 0!==i&&tF.assertOptions(i,{silentJSONParsing:tB.transitional(tB.boolean),forcedJSONParsing:tB.transitional(tB.boolean),clarifyTimeoutError:tB.transitional(tB.boolean)},!1),null!=n&&(ed.isFunction(n)?t.paramsSerializer={serialize:n}:tF.assertOptions(n,{encode:tB.function,serialize:tB.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),tF.assertOptions(t,{baseUrl:tB.spelling("baseURL"),withXsrfToken:tB.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let o=s&&ed.merge(s.common,s[t.method]);s&&ed.forEach(["delete","get","head","post","put","patch","common"],e=>{delete s[e]}),t.headers=e9.concat(o,s);let l=[],u=!0;this.interceptors.request.forEach(function(e){("function"!=typeof e.runWhen||!1!==e.runWhen(t))&&(u=u&&e.synchronous,l.unshift(e.fulfilled,e.rejected))});let c=[];this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let h=0;if(!u){let e=[tM.bind(this),void 0];for(e.unshift.apply(e,l),e.push.apply(e,c),a=e.length,r=Promise.resolve(t);h{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null}),this.promise.then=e=>{let t;let a=new Promise(e=>{r.subscribe(e),t=e}).then(e);return a.cancel=function(){r.unsubscribe(t)},a},e(function(e,a,i){!r.reason&&(r.reason=new e7(e,a,i),t(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){let e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new tZ(function(t){e=t}),cancel:e}}}let tq=tZ;function tG(e){return function(t){return e.apply(null,t)}}function tW(e){return ed.isObject(e)&&!0===e.isAxiosError}let tK={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(tK).forEach(([e,t])=>{tK[t]=e});let tJ=tK;function tY(e){let t=new tH(e),r=o(tH.prototype.request,t);return ed.extend(r,tH.prototype,t,{allOwnKeys:!0}),ed.extend(r,t,null,{allOwnKeys:!0}),r.create=function(t){return tY(tp(e,t))},r}let tV=tY(eW);tV.Axios=tH,tV.CanceledError=e7,tV.CancelToken=tq,tV.isCancel=e6,tV.VERSION=tL,tV.toFormData=ek,tV.AxiosError=eg,tV.Cancel=tV.CanceledError,tV.all=function(e){return Promise.all(e)},tV.spread=tG,tV.isAxiosError=tW,tV.mergeConfig=tp,tV.AxiosHeaders=e9,tV.formToJSON=e=>eZ(ed.isHTMLForm(e)?new FormData(e):e),tV.getAdapter=tC.getAdapter,tV.HttpStatusCode=tJ,tV.default=tV;let tX=tV},23906:(e,t,r)=>{let a=r(88193);e.exports=(e,t,r)=>0>a(e,t,r)},23931:(e,t,r)=>{"use strict";r.d(t,{y:()=>u,Z:()=>l});var a=r(76591);function i(e,t){return t?.[e]||a(e)}function n(e,t,r){let a={};for(let i in e)Object.hasOwn(e,i)&&(a[t(i,r)]=e[i]);return a}function s(e){return Array.isArray(e)?[...e]:{...e}}function o(e,t){let r=s(e);for(let[e,a]of Object.entries(t)){let[t,...i]=e.split(".").reverse(),n=r;for(let e of i.reverse()){if(void 0===n[e])break;n[e]=s(n[e]),n=n[e]}void 0!==n[t]&&(n[t]={lc:1,type:"secret",id:[a]})}return r}function l(e){let t=Object.getPrototypeOf(e);return"function"==typeof e.lc_name&&("function"!=typeof t.lc_name||e.lc_name()!==t.lc_name())?e.lc_name():e.name}r(85560);class u{static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,l(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}),void 0!==this.lc_serializable_keys?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([e])=>this.lc_serializable_keys?.includes(e))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable||this.lc_kwargs instanceof u||"object"!=typeof this.lc_kwargs||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let e={},t={},r=Object.keys(this.lc_kwargs).reduce((e,t)=>(e[t]=t in this?this[t]:this.lc_kwargs[t],e),{});for(let a=Object.getPrototypeOf(this);a;a=Object.getPrototypeOf(a))Object.assign(e,Reflect.get(a,"lc_aliases",this)),Object.assign(t,Reflect.get(a,"lc_secrets",this)),Object.assign(r,Reflect.get(a,"lc_attributes",this));return Object.keys(t).forEach(e=>{let t=this,a=r,[i,...n]=e.split(".").reverse();for(let e of n.reverse()){if(!(e in t)||void 0===t[e])return;e in a&&void 0!==a[e]||("object"==typeof t[e]&&null!=t[e]?a[e]={}:Array.isArray(t[e])&&(a[e]=[])),t=t[e],a=a[e]}i in t&&void 0!==t[i]&&(a[i]=a[i]||t[i])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:n(Object.keys(t).length?o(r,t):r,i,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}},25050:(e,t,r)=>{"use strict";r.d(t,{J:()=>l,j:()=>o});var a=r(72716);function i(e,t){return e&&!Array.isArray(e)&&"object"==typeof e?e:{[t]:e}}function n(e){return e.replace(/[-:.]/g,"")}function s(e,t,r){let a=r.toFixed(0).slice(0,3).padStart(3,"0");return n(`${new Date(e).toISOString().slice(0,-1)}${a}Z`)+t}function o(e){return"function"==typeof e._addRunToRunMap}class l extends a.NK{constructor(e){super(...arguments),Object.defineProperty(this,"runMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}copy(){return this}stringifyError(e){return e instanceof Error?e.message+(e?.stack?` ${e.stack}`:""):"string"==typeof e?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){let t=s(e.start_time,e.id,e.execution_order),r={...e};if(void 0!==r.parent_run_id){let e=this.runMap.get(r.parent_run_id);e&&(this._addChildRun(e,r),e.child_execution_order=Math.max(e.child_execution_order,r.child_execution_order),r.trace_id=e.trace_id,void 0!==e.dotted_order&&(r.dotted_order=[e.dotted_order,t].join(".")))}else r.trace_id=r.id,r.dotted_order=t;return this.runMap.set(r.id,r),r}async _endTrace(e){let t=void 0!==e.parent_run_id&&this.runMap.get(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),this.runMap.delete(e.id),await this.onRunUpdate?.(e)}_getExecutionOrder(e){let t=void 0!==e&&this.runMap.get(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,r,a,i,n,s,o){let l=this._getExecutionOrder(a),u=Date.now(),c=s?{...i,metadata:s}:i,h={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:t},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:c??{},tags:n||[]};return this._addRunToRunMap(h)}async handleLLMStart(e,t,r,a,i,n,s,o){let l=this.runMap.get(r)??this._createRunForLLMStart(e,t,r,a,i,n,s,o);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}_createRunForChatModelStart(e,t,r,a,i,n,s,o){let l=this._getExecutionOrder(a),u=Date.now(),c=s?{...i,metadata:s}:i,h={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:t},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:c??{},tags:n||[]};return this._addRunToRunMap(h)}async handleChatModelStart(e,t,r,a,i,n,s,o){let l=this.runMap.get(r)??this._createRunForChatModelStart(e,t,r,a,i,n,s,o);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}async handleLLMEnd(e,t,r,a,i){let n=this.runMap.get(t);if(!n||n?.run_type!=="llm")throw Error("No LLM run to end.");return n.end_time=Date.now(),n.outputs=e,n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),n.extra={...n.extra,...i},await this.onLLMEnd?.(n),await this._endTrace(n),n}async handleLLMError(e,t,r,a,i){let n=this.runMap.get(t);if(!n||n?.run_type!=="llm")throw Error("No LLM run to end.");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),n.extra={...n.extra,...i},await this.onLLMError?.(n),await this._endTrace(n),n}_createRunForChainStart(e,t,r,a,i,n,s,o){let l=this._getExecutionOrder(a),u=Date.now(),c={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:t,execution_order:l,child_execution_order:l,run_type:s??"chain",child_runs:[],extra:n?{metadata:n}:{},tags:i||[]};return this._addRunToRunMap(c)}async handleChainStart(e,t,r,a,i,n,s,o){let l=this.runMap.get(r)??this._createRunForChainStart(e,t,r,a,i,n,s,o);return await this.onRunCreate?.(l),await this.onChainStart?.(l),l}async handleChainEnd(e,t,r,a,n){let s=this.runMap.get(t);if(!s)throw Error("No chain run to end.");return s.end_time=Date.now(),s.outputs=i(e,"output"),s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),n?.inputs!==void 0&&(s.inputs=i(n.inputs,"input")),await this.onChainEnd?.(s),await this._endTrace(s),s}async handleChainError(e,t,r,a,n){let s=this.runMap.get(t);if(!s)throw Error("No chain run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(e),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),n?.inputs!==void 0&&(s.inputs=i(n.inputs,"input")),await this.onChainError?.(s),await this._endTrace(s),s}_createRunForToolStart(e,t,r,a,i,n,s){let o=this._getExecutionOrder(a),l=Date.now(),u={id:r,name:s??e.id[e.id.length-1],parent_run_id:a,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:t},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:n?{metadata:n}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleToolStart(e,t,r,a,i,n,s){let o=this.runMap.get(r)??this._createRunForToolStart(e,t,r,a,i,n,s);return await this.onRunCreate?.(o),await this.onToolStart?.(o),o}async handleToolEnd(e,t){let r=this.runMap.get(t);if(!r||r?.run_type!=="tool")throw 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){let r=this.runMap.get(t);if(!r||r?.run_type!=="tool")throw 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){let r=this.runMap.get(t);if(!r||r?.run_type!=="chain")return;let a=r;a.actions=a.actions||[],a.actions.push(e),a.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(r)}async handleAgentEnd(e,t){let r=this.runMap.get(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,a,i,n,s){let o=this._getExecutionOrder(a),l=Date.now(),u={id:r,name:s??e.id[e.id.length-1],parent_run_id:a,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{query:t},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:n?{metadata:n}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(e,t,r,a,i,n,s){let o=this.runMap.get(r)??this._createRunForRetrieverStart(e,t,r,a,i,n,s);return await this.onRunCreate?.(o),await this.onRetrieverStart?.(o),o}async handleRetrieverEnd(e,t){let r=this.runMap.get(t);if(!r||r?.run_type!=="retriever")throw 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){let r=this.runMap.get(t);if(!r||r?.run_type!=="retriever")throw 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){let r=this.runMap.get(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,a,i,n){let s=this.runMap.get(r);if(!s||s?.run_type!=="llm")throw Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return s.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:n?.chunk}}),await this.onLLMNewToken?.(s,e,{chunk:n?.chunk}),s}}},25489:(e,t,r)=>{"use strict";let a,i,n,s,o,l,u,c;r.d(t,{Ny:()=>ad});let h="0.37.0",d=!1,p=null,f=null,m=null,g=null,y=null,b=null,_=null;function w(e,t={auto:!1}){if(d)throw Error(`you must \`import '@anthropic-ai/sdk/shims/${e.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(i)throw Error(`can't \`import '@anthropic-ai/sdk/shims/${e.kind}'\` after \`import '@anthropic-ai/sdk/shims/${i}'\``);d=t.auto,i=e.kind,n=e.fetch,p=e.Request,f=e.Response,m=e.Headers,g=e.FormData,y=e.Blob,s=e.File,o=e.ReadableStream,b=e.getMultipartRequestOptions,l=e.getDefaultAgent,u=e.fileFromPath,_=e.isFsReadStream}class v{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}function O({manuallyImported:e}={}){let t,r,a,i;let n=e?"You may need to use polyfills":`Add one of these imports before your first \`import … from '@anthropic-ai/sdk'\`: - \`import '@anthropic-ai/sdk/shims/node'\` (if you're running on Node) - \`import '@anthropic-ai/sdk/shims/web'\` (otherwise) `;try{t=fetch,r=Request,a=Response,i=Headers}catch(e){throw Error(`this environment is missing the following Web Fetch API type: ${e.message}. ${n}`)}return{kind:"web",fetch:t,Request:r,Response:a,Headers:i,FormData:"undefined"!=typeof FormData?FormData:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${n}`)}},Blob:"undefined"!=typeof Blob?Blob:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${n}`)}},File:"undefined"!=typeof File?File:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${n}`)}},ReadableStream:"undefined"!=typeof ReadableStream?ReadableStream:class{constructor(){throw Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${n}`)}},getMultipartRequestOptions:async(e,t)=>({...t,body:new v(e)}),getDefaultAgent:e=>void 0,fileFromPath:()=>{throw Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads")},isFsReadStream:e=>!1}}i||w(O(),{auto:!0});class E extends Error{}class k extends E{constructor(e,t,r,a){super(`${k.makeMessage(e,t,r)}`),this.status=e,this.headers=a,this.request_id=a?.["request-id"],this.error=t}static makeMessage(e,t,r){let a=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&a?`${e} ${a}`:e?`${e} status code (no body)`:a||"(no status code or body)"}static generate(e,t,r,a){if(!e||!a)return new S({message:r,cause:tp(t)});let i=t;return 400===e?new P(e,i,r,a):401===e?new T(e,i,r,a):403===e?new I(e,i,r,a):404===e?new N(e,i,r,a):409===e?new j(e,i,r,a):422===e?new R(e,i,r,a):429===e?new C(e,i,r,a):e>=500?new $(e,i,r,a):new k(e,i,r,a)}}class x extends k{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class S extends k{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class A extends S{constructor({message:e}={}){super({message:e??"Request timed out."})}}class P extends k{}class T extends k{}class I extends k{}class N extends k{}class j extends k{}class R extends k{}class C extends k{}class $ extends k{}var M,L,U,D,F,B,z,H,Z,q,G,W,K,J,Y,V,X,Q,ee,et,er,ea,ei,en,es,eo,el,eu,ec,eh,ed,ep,ef,em,eg,ey,eb,e_,ew,ev,eO,eE,ek,ex,eS,eA,eP,eT=r(44134).Buffer,eI=function(e,t,r,a,i){if("m"===a)throw TypeError("Private method is not writable");if("a"===a&&!i)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===a?i.call(e,r):i?i.value=r:t.set(e,r),r},eN=function(e,t,r,a){if("a"===r&&!a)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!a:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?a:"a"===r?a.call(e):a?a.value:t.get(e)};class ej{constructor(){M.set(this,void 0),this.buffer=new Uint8Array,eI(this,M,null,"f")}decode(e){let t;if(null==e)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?new TextEncoder().encode(e):e,a=new Uint8Array(this.buffer.length+r.length);a.set(this.buffer),a.set(r,this.buffer.length),this.buffer=a;let i=[];for(;null!=(t=eR(this.buffer,eN(this,M,"f")));){if(t.carriage&&null==eN(this,M,"f")){eI(this,M,t.index,"f");continue}if(null!=eN(this,M,"f")&&(t.index!==eN(this,M,"f")+1||t.carriage)){i.push(this.decodeText(this.buffer.slice(0,eN(this,M,"f")-1))),this.buffer=this.buffer.slice(eN(this,M,"f")),eI(this,M,null,"f");continue}let e=null!==eN(this,M,"f")?t.preceding-1:t.preceding,r=this.decodeText(this.buffer.slice(0,e));i.push(r),this.buffer=this.buffer.slice(t.index),eI(this,M,null,"f")}return i}decodeText(e){if(null==e)return"";if("string"==typeof e)return e;if(void 0!==eT){if(e instanceof eT)return e.toString();if(e instanceof Uint8Array)return eT.from(e).toString();throw new E(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new E(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new E("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode("\n"):[]}}function eR(e,t){let r=10,a=13;for(let i=t??0;i({next:()=>{if(0===a.length){let a=r.next();e.push(a),t.push(a)}return a.shift()}});return[new eM(()=>a(e),this.controller),new eM(()=>a(t),this.controller)]}toReadableStream(){let e;let t=this,r=new TextEncoder;return new o({async start(){e=t[Symbol.asyncIterator]()},async pull(t){try{let{value:a,done:i}=await e.next();if(i)return t.close();let n=r.encode(JSON.stringify(a)+"\n");t.enqueue(n)}catch(e){t.error(e)}},async cancel(){await e.return?.()}})}}async function*eL(e,t){if(!e.body)throw t.abort(),new E("Attempted to iterate over a response with no body");let r=new eD,a=new ej;for await(let t of eU(e$(e.body)))for(let e of a.decode(t)){let t=r.decode(e);t&&(yield t)}for(let e of a.flush()){let t=r.decode(e);t&&(yield t)}}async function*eU(e){let t=new Uint8Array;for await(let r of e){let e;if(null==r)continue;let a=r instanceof ArrayBuffer?new Uint8Array(r):"string"==typeof r?new TextEncoder().encode(r):r,i=new Uint8Array(t.length+a.length);for(i.set(t),i.set(a,t.length),t=i;-1!==(e=eC(t));)yield t.slice(0,e),t=t.slice(e)}t.length>0&&(yield t)}class eD{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,a]=eF(e,":");return a.startsWith(" ")&&(a=a.substring(1)),"event"===t?this.event=a:"data"===t&&this.data.push(a),null}}function eF(e,t){let r=e.indexOf(t);return -1!==r?[e.substring(0,r),t,e.substring(r+t.length)]:[e,"",""]}var eB=r(44134).Buffer;let ez=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,eH=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&eZ(e),eZ=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer,eq=e=>eH(e)||ez(e)||isFsReadStream(e);async function eG(e,t,r){if(eH(e=await e))return e;if(ez(e)){let a=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=eZ(a)?[await a.arrayBuffer()]:[a];return new s(i,t,r)}let a=await eW(e);if(t||(t=eJ(e)??"unknown_file"),!r?.type){let e=a[0]?.type;"string"==typeof e&&(r={...r,type:e})}return new s(a,t,r)}async function eW(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(eZ(e))t.push(await e.arrayBuffer());else if(eV(e))for await(let r of e)t.push(r);else throw Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${eK(e)}`);return t}function eK(e){let t=Object.getOwnPropertyNames(e);return`[${t.map(e=>`"${e}"`).join(", ")}]`}function eJ(e){return eY(e.name)||eY(e.filename)||eY(e.path)?.split(/[\\/]/).pop()}let eY=e=>"string"==typeof e?e:void 0!==eB&&e instanceof eB?String(e):void 0,eV=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],eX=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag],eQ=e=>{if(eq(e))return!0;if(Array.isArray(e))return e.some(eQ);if(e&&"object"==typeof e){for(let t in e)if(eQ(e[t]))return!0}return!1};var e0=r(44134).Buffer,e1=r(49509),e2=function(e,t,r,a,i){if("m"===a)throw TypeError("Private method is not writable");if("a"===a&&!i)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===a?i.call(e,r):i?i.value=r:t.set(e,r),r},e4=function(e,t,r,a){if("a"===r&&!a)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!a:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?a:"a"===r?a.call(e):a?a.value:t.get(e)};async function e5(e){let{response:t}=e;if(e.options.stream)return(tb("response",t.status,t.url,t.headers,t.body),e.options.__streamClass)?e.options.__streamClass.fromSSEResponse(t,e.controller):eM.fromSSEResponse(t,e.controller);if(204===t.status)return null;if(e.options.__binaryResponse)return t;let r=t.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){let e=await t.json();return tb("response",t.status,t.url,t.headers,e),e9(e,t)}let a=await t.text();return tb("response",t.status,t.url,t.headers,a),a}function e9(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("request-id"),enumerable:!1})}class e3 extends Promise{constructor(e,t=e5){super(e=>{e(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new e3(this.responsePromise,async t=>e9(e(await this.parseResponse(t),t),t.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),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)}}class e6{constructor({baseURL:e,maxRetries:t=2,timeout:r=6e5,httpAgent:a,fetch:i}){this.baseURL=e,this.maxRetries=td("maxRetries",t),this.timeout=td("timeout",r),this.httpAgent=a,this.fetch=i??n}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...to(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${t_()}`}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(async r=>{let a=r&&eZ(r?.body)?new DataView(await r.body.arrayBuffer()):r?.body instanceof DataView?r.body:r?.body instanceof ArrayBuffer?new DataView(r.body):r&&ArrayBuffer.isView(r?.body)?new DataView(r.body.buffer):r?.body;return{method:e,path:t,...r,body:a}}))}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}calculateContentLength(e){if("string"==typeof e){if(void 0!==e0)return e0.byteLength(e,"utf8").toString();if("undefined"!=typeof TextEncoder)return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){let{method:r,path:a,query:i,headers:n={}}=e={...e},s=ArrayBuffer.isView(e.body)||e.__binaryRequest&&"string"==typeof e.body?e.body:eX(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,o=this.calculateContentLength(s),u=this.buildURL(a,i);"timeout"in e&&td("timeout",e.timeout),e.timeout=e.timeout??this.timeout;let c=e.httpAgent??this.httpAgent??l(u),h=e.timeout+1e3;"number"==typeof c?.options?.timeout&&h>(c.options.timeout??0)&&(c.options.timeout=h),this.idempotencyHeader&&"get"!==r&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),n[this.idempotencyHeader]=e.idempotencyKey);let d=this.buildHeaders({options:e,headers:n,contentLength:o,retryCount:t});return{req:{method:r,...s&&{body:s},headers:d,...c&&{agent:c},signal:e.signal??null},url:u,timeout:e.timeout}}buildHeaders({options:e,headers:t,contentLength:r,retryCount:a}){let n={};r&&(n["content-length"]=r);let s=this.defaultHeaders(e);return ty(n,s),ty(n,t),eX(e.body)&&"node"!==i&&delete n["content-type"],void 0===tO(s,"x-stainless-retry-count")&&void 0===tO(t,"x-stainless-retry-count")&&(n["x-stainless-retry-count"]=String(a)),void 0===tO(s,"x-stainless-timeout")&&void 0===tO(t,"x-stainless-timeout")&&e.timeout&&(n["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(n,t),n}_calculateNonstreamingTimeout(e){let t=600;if(3600*e/128e3>600)throw new E("Streaming is strongly recommended for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details");return 1e3*t}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(e=>[...e])):{...e}:{}}makeStatusError(e,t,r,a){return k.generate(e,t,r,a)}request(e,t=null){return new e3(this.makeRequest(e,t))}async makeRequest(e,t){let r=await e,a=r.maxRetries??this.maxRetries;null==t&&(t=a),await this.prepareOptions(r);let{req:i,url:n,timeout:s}=this.buildRequest(r,{retryCount:a-t});if(await this.prepareRequest(i,{url:n,options:r}),tb("request",n,r,i.headers),r.signal?.aborted)throw new x;let o=new AbortController,l=await this.fetchWithTimeout(n,i,s,o).catch(tp);if(l instanceof Error){if(r.signal?.aborted)throw new x;if(t)return this.retryRequest(r,t);if("AbortError"===l.name)throw new A;throw new S({cause:l})}let u=te(l.headers);if(!l.ok){if(t&&this.shouldRetry(l)){let e=`retrying, ${t} attempts remaining`;return tb(`response (error; ${e})`,l.status,n,u),this.retryRequest(r,t,u)}let e=await l.text().catch(e=>tp(e).message),a=tl(e),i=a?void 0:e,s=t?"(error; no more retries left)":"(error; not retryable)";throw tb(`response (error; ${s})`,l.status,n,u,i),this.makeStatusError(l.status,a,i,u)}return{response:l,options:r,controller:o}}requestAPIList(e,t){return new e7(this,this.makeRequest(t,null),e)}buildURL(e,t){let r=new URL(tc(e)?e:this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return tm(a)||(t={...a,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}stringifyQuery(e){return Object.entries(e).filter(([e,t])=>void 0!==t).map(([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new E(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,r,a){let{signal:i,...n}=t||{};i&&i.addEventListener("abort",()=>a.abort());let s=setTimeout(()=>a.abort(),r),o={signal:a.signal,...n};o.method&&(o.method=o.method.toUpperCase());let l=6e4,u=setTimeout(()=>{if(o&&o?.agent?.sockets)for(let e of Object.values(o?.agent?.sockets).flat())e?.setKeepAlive&&e.setKeepAlive(!0,l)},6e4);return this.fetch.call(void 0,e,o).finally(()=>{clearTimeout(s),clearTimeout(u)})}shouldRetry(e){let t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||409===e.status||429===e.status||!!(e.status>=500))}async retryRequest(e,t,r){let a;let i=r?.["retry-after-ms"];if(i){let e=parseFloat(i);Number.isNaN(e)||(a=e)}let n=r?.["retry-after"];if(n&&!a){let e=parseFloat(n);a=Number.isNaN(e)?Date.parse(n)-Date.now():1e3*e}if(!(a&&0<=a&&a<6e4)){let r=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,r)}return await th(a),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){return Math.min(.5*Math.pow(2,t-e),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${h}`}}class e8{constructor(e,t,r,a){L.set(this,void 0),e2(this,L,e,"f"),this.options=a,this.response=t,this.body=r}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new E("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let t={...this.options};if("params"in e&&"object"==typeof t.query)t.query={...t.query,...e.params};else if("url"in e){for(let[r,a]of[...Object.entries(t.query||{}),...e.url.searchParams.entries()])e.url.searchParams.set(r,a);t.query=void 0,t.path=e.url.toString()}return await e4(this,L,"f").requestAPIList(this.constructor,t)}async *iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async *[(L=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}class e7 extends e3{constructor(e,t,r){super(t,async t=>new r(e,t.response,await e5(t),t.options))}async *[Symbol.asyncIterator](){for await(let e of(await this))yield e}}let te=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){let r=t.toString();return e[r.toLowerCase()]||e[r]}}),tt={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},tr=e=>"object"==typeof e&&null!==e&&!tm(e)&&Object.keys(e).every(e=>tg(tt,e)),ta=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":h,"X-Stainless-OS":ts(Deno.build.os),"X-Stainless-Arch":tn(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":h,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":e1.version};if("[object process]"===Object.prototype.toString.call(void 0!==e1?e1:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":h,"X-Stainless-OS":ts(e1.platform),"X-Stainless-Arch":tn(e1.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":e1.version};let e=ti();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":h,"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":h,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ti(){if("undefined"==typeof navigator||!navigator)return null;for(let{key:e,pattern:t}of[{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/}]){let r=t.exec(navigator.userAgent);if(r){let t=r[1]||0,a=r[2]||0,i=r[3]||0;return{browser:e,version:`${t}.${a}.${i}`}}}return null}let tn=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",ts=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown",to=()=>a??(a=ta()),tl=e=>{try{return JSON.parse(e)}catch(e){return}},tu=/^[a-z][a-z0-9+.-]*:/i,tc=e=>tu.test(e),th=e=>new Promise(t=>setTimeout(t,e)),td=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new E(`${e} must be an integer`);if(t<0)throw new E(`${e} must be a positive integer`);return t},tp=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e)try{return Error(JSON.stringify(e))}catch{}return Error(String(e))},tf=e=>void 0!==e1?e1.env?.[e]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e)?.trim():void 0;function tm(e){if(!e)return!0;for(let t in e)return!1;return!0}function tg(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ty(e,t){for(let r in t){if(!tg(t,r))continue;let a=r.toLowerCase();if(!a)continue;let i=t[r];null===i?delete e[a]:void 0!==i&&(e[a]=i)}}function tb(e,...t){void 0!==e1&&e1?.env?.DEBUG==="true"&&console.log(`Anthropic:DEBUG:${e}`,...t)}let t_=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),tw=()=>"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator,tv=e=>"function"==typeof e?.get,tO=(e,t)=>{let r=t.toLowerCase();if(tv(e)){let a=t[0]?.toUpperCase()+t.substring(1).replace(/([^\w])(\w)/g,(e,t,r)=>t+r.toUpperCase());for(let i of[t,r,t.toUpperCase(),a]){let t=e.get(i);if(t)return t}}for(let[a,i]of Object.entries(e))if(a.toLowerCase()===r){if(Array.isArray(i)){if(i.length<=1)return i[0];return console.warn(`Received ${i.length} entries for the ${t} header, using the first entry.`),i[0]}return i}};class tE{constructor(e){this._client=e}}class tk extends tE{create(e,t){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}}class tx extends e8{constructor(e,t,r,a){super(e,t,r,a),this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageParams(){let e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;let t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){if(this.options.query?.before_id){let e=this.first_id;return e?{params:{before_id:e}}:null}let e=this.last_id;return e?{params:{after_id:e}}:null}}class tS{constructor(e,t){this.iterator=e,this.controller=t}async *decoder(){let e=new ej;for await(let t of this.iterator)for(let r of e.decode(t))yield JSON.parse(r);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),new E("Attempted to iterate over a response with no body");return new tS(e$(e.body),t)}}class tA extends tE{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/v1/messages/batches/${e}`,t)}list(e={},t){return tr(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",tP,{query:e,...t})}delete(e,t){return this._client.delete(`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let r=await this.retrieve(e);if(!r.results_url)throw new E(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})._thenUnwrap((e,t)=>tS.fromResponse(t.response,t.controller))}}class tP extends tx{}tA.MessageBatchesPage=tP;let tT=e=>{let t=0,r=[];for(;t{if(0===e.length)return e;let t=e[e.length-1];switch(t.type){case"separator":return tI(e=e.slice(0,e.length-1));case"number":let r=t.value[t.value.length-1];if("."===r||"-"===r)return tI(e=e.slice(0,e.length-1));case"string":let a=e[e.length-2];if(a?.type==="delimiter"||a?.type==="brace"&&"{"===a.value)return tI(e=e.slice(0,e.length-1));break;case"delimiter":return tI(e=e.slice(0,e.length-1))}return e},tN=e=>{let t=[];return e.map(e=>{"brace"===e.type&&("{"===e.value?t.push("}"):t.splice(t.lastIndexOf("}"),1)),"paren"===e.type&&("["===e.value?t.push("]"):t.splice(t.lastIndexOf("]"),1))}),t.length>0&&t.reverse().map(t=>{"}"===t?e.push({type:"brace",value:"}"}):"]"===t&&e.push({type:"paren",value:"]"})}),e},tj=e=>{let t="";return e.map(e=>{"string"===e.type?t+='"'+e.value+'"':t+=e.value}),t},tR=e=>JSON.parse(tj(tN(tI(tT(e)))));var tC=function(e,t,r,a,i){if("m"===a)throw TypeError("Private method is not writable");if("a"===a&&!i)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===a?i.call(e,r):i?i.value=r:t.set(e,r),r},t$=function(e,t,r,a){if("a"===r&&!a)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!a:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?a:"a"===r?a.call(e):a?a.value:t.get(e)};let tM="__json_buf";class tL{constructor(){U.add(this),this.messages=[],this.receivedMessages=[],D.set(this,void 0),this.controller=new AbortController,F.set(this,void 0),B.set(this,()=>{}),z.set(this,()=>{}),H.set(this,void 0),Z.set(this,()=>{}),q.set(this,()=>{}),G.set(this,{}),W.set(this,!1),K.set(this,!1),J.set(this,!1),Y.set(this,!1),V.set(this,void 0),X.set(this,void 0),et.set(this,e=>{if(tC(this,K,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new x),e instanceof x)return tC(this,J,!0,"f"),this._emit("abort",e);if(e instanceof E)return this._emit("error",e);if(e instanceof Error){let t=new E(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new E(String(e)))}),tC(this,F,new Promise((e,t)=>{tC(this,B,e,"f"),tC(this,z,t,"f")}),"f"),tC(this,H,new Promise((e,t)=>{tC(this,Z,e,"f"),tC(this,q,t,"f")}),"f"),t$(this,F,"f").catch(()=>{}),t$(this,H,"f").catch(()=>{})}get response(){return t$(this,V,"f")}get request_id(){return t$(this,X,"f")}async withResponse(){let e=await t$(this,F,"f");if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new tL;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r){let a=new tL;for(let e of t.messages)a._addMessageParam(e);return a._run(()=>a._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},t$(this,et,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){let a=r?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort())),t$(this,U,"m",er).call(this);let{response:i,data:n}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();for await(let e of(this._connected(i),n))t$(this,U,"m",ea).call(this,e);if(n.controller.signal?.aborted)throw new x;t$(this,U,"m",ei).call(this)}_connected(e){this.ended||(tC(this,V,e,"f"),tC(this,X,e?.headers.get("request-id"),"f"),t$(this,B,"f").call(this,e),this._emit("connect"))}get ended(){return t$(this,W,"f")}get errored(){return t$(this,K,"f")}get aborted(){return t$(this,J,"f")}abort(){this.controller.abort()}on(e,t){return(t$(this,G,"f")[e]||(t$(this,G,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=t$(this,G,"f")[e];if(!r)return this;let a=r.findIndex(e=>e.listener===t);return a>=0&&r.splice(a,1),this}once(e,t){return(t$(this,G,"f")[e]||(t$(this,G,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{tC(this,Y,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)})}async done(){tC(this,Y,!0,"f"),await t$(this,H,"f")}get currentMessage(){return t$(this,D,"f")}async finalMessage(){return await this.done(),t$(this,U,"m",Q).call(this)}async finalText(){return await this.done(),t$(this,U,"m",ee).call(this)}_emit(e,...t){if(t$(this,W,"f"))return;"end"===e&&(tC(this,W,!0,"f"),t$(this,Z,"f").call(this));let r=t$(this,G,"f")[e];if(r&&(t$(this,G,"f")[e]=r.filter(e=>!e.once),r.forEach(({listener:e})=>e(...t))),"abort"===e){let e=t[0];t$(this,Y,"f")||r?.length||Promise.reject(e),t$(this,z,"f").call(this,e),t$(this,q,"f").call(this,e),this._emit("end");return}if("error"===e){let e=t[0];t$(this,Y,"f")||r?.length||Promise.reject(e),t$(this,z,"f").call(this,e),t$(this,q,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",t$(this,U,"m",Q).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),t$(this,U,"m",er).call(this),this._connected(null);let a=eM.fromReadableStream(e,this.controller);for await(let e of a)t$(this,U,"m",ea).call(this,e);if(a.controller.signal?.aborted)throw new x;t$(this,U,"m",ei).call(this)}[(D=new WeakMap,F=new WeakMap,B=new WeakMap,z=new WeakMap,H=new WeakMap,Z=new WeakMap,q=new WeakMap,G=new WeakMap,W=new WeakMap,K=new WeakMap,J=new WeakMap,Y=new WeakMap,V=new WeakMap,X=new WeakMap,et=new WeakMap,U=new WeakSet,Q=function(){if(0===this.receivedMessages.length)throw new E("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},ee=function(){if(0===this.receivedMessages.length)throw new E("stream ended without producing a Message with role=assistant");let e=this.receivedMessages.at(-1).content.filter(e=>"text"===e.type).map(e=>e.text);if(0===e.length)throw new E("stream ended without producing a content block with type=text");return e.join(" ")},er=function(){this.ended||tC(this,D,void 0,"f")},ea=function(e){if(this.ended)return;let t=t$(this,U,"m",en).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{let r=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===r.type&&this._emit("text",e.delta.text,r.text||"");break;case"citations_delta":"text"===r.type&&this._emit("citation",e.delta.citation,r.citations??[]);break;case"input_json_delta":"tool_use"===r.type&&r.input&&this._emit("inputJson",e.delta.partial_json,r.input);break;case"thinking_delta":"thinking"===r.type&&this._emit("thinking",e.delta.thinking,r.thinking);break;case"signature_delta":"thinking"===r.type&&this._emit("signature",r.signature);break;default:e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(t,!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":tC(this,D,t,"f")}},ei=function(){if(this.ended)throw new E("stream has ended, this shouldn't happen");let e=t$(this,D,"f");if(!e)throw new E("request ended without sending any chunks");return tC(this,D,void 0,"f"),e},en=function(e){let t=t$(this,D,"f");if("message_start"===e.type){if(t)throw new E(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new E(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":case"content_block_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,t;case"content_block_start":return t.content.push(e.content_block),t;case"content_block_delta":{let r=t.content.at(e.index);switch(e.delta.type){case"text_delta":r?.type==="text"&&(r.text+=e.delta.text);break;case"citations_delta":r?.type==="text"&&(r.citations??(r.citations=[]),r.citations.push(e.delta.citation));break;case"input_json_delta":if(r?.type==="tool_use"){let t=r[tM]||"";Object.defineProperty(r,tM,{value:t+=e.delta.partial_json,enumerable:!1,writable:!0}),t&&(r.input=tR(t))}break;case"thinking_delta":r?.type==="thinking"&&(r.thinking+=e.delta.thinking);break;case"signature_delta":r?.type==="thinking"&&(r.signature=e.delta.signature);break;default:e.delta}return t}}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",r=>{let a=t.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{for(let e of(r=!0,t))e.resolve(void 0);t.length=0}),this.on("abort",e=>{for(let a of(r=!0,t))a.reject(e);t.length=0}),this.on("error",e=>{for(let a of(r=!0,t))a.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((e,r)=>t.push({resolve:e,reject:r})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new eM(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class tU extends tE{constructor(){super(...arguments),this.batches=new tA(this._client)}create(e,t){return e.model in tD&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${tD[e.model]} Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:e,timeout:this._client._options.timeout??(e.stream?6e5:this._client._calculateNonstreamingTimeout(e.max_tokens)),...t,stream:e.stream??!1})}stream(e,t){return tL.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}let tD={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};tU.Batches=tA,tU.MessageBatchesPage=tP;class tF extends tE{retrieve(e,t){return this._client.get(`/v1/models/${e}`,t)}list(e={},t){return tr(e)?this.list({},e):this._client.getAPIList("/v1/models",tB,{query:e,...t})}}class tB extends tx{}tF.ModelInfosPage=tB;class tz extends tE{retrieve(e,t){return this._client.get(`/v1/models/${e}?beta=true`,t)}list(e={},t){return tr(e)?this.list({},e):this._client.getAPIList("/v1/models?beta=true",tH,{query:e,...t})}}class tH extends tx{}tz.BetaModelInfosPage=tH;class tZ extends tE{create(e,t){let{betas:r,...a}=e;return this._client.post("/v1/messages/batches?beta=true",{body:a,...t,headers:{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}retrieve(e,t={},r){if(tr(t))return this.retrieve(e,{},t);let{betas:a}=t;return this._client.get(`/v1/messages/batches/${e}?beta=true`,{...r,headers:{"anthropic-beta":[...a??[],"message-batches-2024-09-24"].toString(),...r?.headers}})}list(e={},t){if(tr(e))return this.list({},e);let{betas:r,...a}=e;return this._client.getAPIList("/v1/messages/batches?beta=true",tq,{query:a,...t,headers:{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}delete(e,t={},r){if(tr(t))return this.delete(e,{},t);let{betas:a}=t;return this._client.delete(`/v1/messages/batches/${e}?beta=true`,{...r,headers:{"anthropic-beta":[...a??[],"message-batches-2024-09-24"].toString(),...r?.headers}})}cancel(e,t={},r){if(tr(t))return this.cancel(e,{},t);let{betas:a}=t;return this._client.post(`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:{"anthropic-beta":[...a??[],"message-batches-2024-09-24"].toString(),...r?.headers}})}async results(e,t={},r){if(tr(t))return this.results(e,{},t);let a=await this.retrieve(e);if(!a.results_url)throw new E(`No batch \`results_url\`; Has it finished processing? ${a.processing_status} - ${a.id}`);let{betas:i}=t;return this._client.get(a.results_url,{...r,headers:{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...r?.headers},__binaryResponse:!0})._thenUnwrap((e,t)=>tS.fromResponse(t.response,t.controller))}}class tq extends tx{}tZ.BetaMessageBatchesPage=tq;var tG=function(e,t,r,a,i){if("m"===a)throw TypeError("Private method is not writable");if("a"===a&&!i)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===a?i.call(e,r):i?i.value=r:t.set(e,r),r},tW=function(e,t,r,a){if("a"===r&&!a)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!a:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?a:"a"===r?a.call(e):a?a.value:t.get(e)};let tK="__json_buf";class tJ{constructor(){es.add(this),this.messages=[],this.receivedMessages=[],eo.set(this,void 0),this.controller=new AbortController,el.set(this,void 0),eu.set(this,()=>{}),ec.set(this,()=>{}),eh.set(this,void 0),ed.set(this,()=>{}),ep.set(this,()=>{}),ef.set(this,{}),em.set(this,!1),eg.set(this,!1),ey.set(this,!1),eb.set(this,!1),e_.set(this,void 0),ew.set(this,void 0),eE.set(this,e=>{if(tG(this,eg,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new x),e instanceof x)return tG(this,ey,!0,"f"),this._emit("abort",e);if(e instanceof E)return this._emit("error",e);if(e instanceof Error){let t=new E(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new E(String(e)))}),tG(this,el,new Promise((e,t)=>{tG(this,eu,e,"f"),tG(this,ec,t,"f")}),"f"),tG(this,eh,new Promise((e,t)=>{tG(this,ed,e,"f"),tG(this,ep,t,"f")}),"f"),tW(this,el,"f").catch(()=>{}),tW(this,eh,"f").catch(()=>{})}get response(){return tW(this,e_,"f")}get request_id(){return tW(this,ew,"f")}async withResponse(){let e=await tW(this,el,"f");if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new tJ;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r){let a=new tJ;for(let e of t.messages)a._addMessageParam(e);return a._run(()=>a._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},tW(this,eE,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){let a=r?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort())),tW(this,es,"m",ek).call(this);let{response:i,data:n}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();for await(let e of(this._connected(i),n))tW(this,es,"m",ex).call(this,e);if(n.controller.signal?.aborted)throw new x;tW(this,es,"m",eS).call(this)}_connected(e){this.ended||(tG(this,e_,e,"f"),tG(this,ew,e?.headers.get("request-id"),"f"),tW(this,eu,"f").call(this,e),this._emit("connect"))}get ended(){return tW(this,em,"f")}get errored(){return tW(this,eg,"f")}get aborted(){return tW(this,ey,"f")}abort(){this.controller.abort()}on(e,t){return(tW(this,ef,"f")[e]||(tW(this,ef,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=tW(this,ef,"f")[e];if(!r)return this;let a=r.findIndex(e=>e.listener===t);return a>=0&&r.splice(a,1),this}once(e,t){return(tW(this,ef,"f")[e]||(tW(this,ef,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{tG(this,eb,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)})}async done(){tG(this,eb,!0,"f"),await tW(this,eh,"f")}get currentMessage(){return tW(this,eo,"f")}async finalMessage(){return await this.done(),tW(this,es,"m",ev).call(this)}async finalText(){return await this.done(),tW(this,es,"m",eO).call(this)}_emit(e,...t){if(tW(this,em,"f"))return;"end"===e&&(tG(this,em,!0,"f"),tW(this,ed,"f").call(this));let r=tW(this,ef,"f")[e];if(r&&(tW(this,ef,"f")[e]=r.filter(e=>!e.once),r.forEach(({listener:e})=>e(...t))),"abort"===e){let e=t[0];tW(this,eb,"f")||r?.length||Promise.reject(e),tW(this,ec,"f").call(this,e),tW(this,ep,"f").call(this,e),this._emit("end");return}if("error"===e){let e=t[0];tW(this,eb,"f")||r?.length||Promise.reject(e),tW(this,ec,"f").call(this,e),tW(this,ep,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",tW(this,es,"m",ev).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),tW(this,es,"m",ek).call(this),this._connected(null);let a=eM.fromReadableStream(e,this.controller);for await(let e of a)tW(this,es,"m",ex).call(this,e);if(a.controller.signal?.aborted)throw new x;tW(this,es,"m",eS).call(this)}[(eo=new WeakMap,el=new WeakMap,eu=new WeakMap,ec=new WeakMap,eh=new WeakMap,ed=new WeakMap,ep=new WeakMap,ef=new WeakMap,em=new WeakMap,eg=new WeakMap,ey=new WeakMap,eb=new WeakMap,e_=new WeakMap,ew=new WeakMap,eE=new WeakMap,es=new WeakSet,ev=function(){if(0===this.receivedMessages.length)throw new E("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},eO=function(){if(0===this.receivedMessages.length)throw new E("stream ended without producing a Message with role=assistant");let e=this.receivedMessages.at(-1).content.filter(e=>"text"===e.type).map(e=>e.text);if(0===e.length)throw new E("stream ended without producing a content block with type=text");return e.join(" ")},ek=function(){this.ended||tG(this,eo,void 0,"f")},ex=function(e){if(this.ended)return;let t=tW(this,es,"m",eA).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{let r=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===r.type&&this._emit("text",e.delta.text,r.text||"");break;case"citations_delta":"text"===r.type&&this._emit("citation",e.delta.citation,r.citations??[]);break;case"input_json_delta":"tool_use"===r.type&&r.input&&this._emit("inputJson",e.delta.partial_json,r.input);break;case"thinking_delta":"thinking"===r.type&&this._emit("thinking",e.delta.thinking,r.thinking);break;case"signature_delta":"thinking"===r.type&&this._emit("signature",r.signature);break;default:e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(t,!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":tG(this,eo,t,"f")}},eS=function(){if(this.ended)throw new E("stream has ended, this shouldn't happen");let e=tW(this,eo,"f");if(!e)throw new E("request ended without sending any chunks");return tG(this,eo,void 0,"f"),e},eA=function(e){let t=tW(this,eo,"f");if("message_start"===e.type){if(t)throw new E(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new E(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":case"content_block_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,t;case"content_block_start":return t.content.push(e.content_block),t;case"content_block_delta":{let r=t.content.at(e.index);switch(e.delta.type){case"text_delta":r?.type==="text"&&(r.text+=e.delta.text);break;case"citations_delta":r?.type==="text"&&(r.citations??(r.citations=[]),r.citations.push(e.delta.citation));break;case"input_json_delta":if(r?.type==="tool_use"){let t=r[tK]||"";Object.defineProperty(r,tK,{value:t+=e.delta.partial_json,enumerable:!1,writable:!0}),t&&(r.input=tR(t))}break;case"thinking_delta":r?.type==="thinking"&&(r.thinking+=e.delta.thinking);break;case"signature_delta":r?.type==="thinking"&&(r.signature=e.delta.signature);break;default:e.delta}return t}}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",r=>{let a=t.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{for(let e of(r=!0,t))e.resolve(void 0);t.length=0}),this.on("abort",e=>{for(let a of(r=!0,t))a.reject(e);t.length=0}),this.on("error",e=>{for(let a of(r=!0,t))a.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((e,r)=>t.push({resolve:e,reject:r})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new eM(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}let tY={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};class tV extends tE{constructor(){super(...arguments),this.batches=new tZ(this._client)}create(e,t){let{betas:r,...a}=e;return a.model in tY&&console.warn(`The model '${a.model}' is deprecated and will reach end-of-life on ${tY[a.model]} Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages?beta=true",{body:a,timeout:this._client._options.timeout??(a.stream?6e5:this._client._calculateNonstreamingTimeout(a.max_tokens)),...t,headers:{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0,...t?.headers},stream:e.stream??!1})}stream(e,t){return tJ.createMessage(this,e,t)}countTokens(e,t){let{betas:r,...a}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:a,...t,headers:{"anthropic-beta":[...r??[],"token-counting-2024-11-01"].toString(),...t?.headers}})}}tV.Batches=tZ,tV.BetaMessageBatchesPage=tq;class tX extends tE{constructor(){super(...arguments),this.models=new tz(this._client),this.messages=new tV(this._client)}}tX.Models=tz,tX.BetaModelInfosPage=tH,tX.Messages=tV;class tQ extends e6{constructor({baseURL:e=tf("ANTHROPIC_BASE_URL"),apiKey:t=tf("ANTHROPIC_API_KEY")??null,authToken:r=tf("ANTHROPIC_AUTH_TOKEN")??null,...a}={}){let i={apiKey:t,authToken:r,...a,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&tw())throw new E("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 Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new tk(this),this.messages=new tU(this),this.models=new tF(this),this.beta=new tX(this),this._options=i,this.apiKey=t,this.authToken=r}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders(e,t){if((!this.apiKey||!e["x-api-key"])&&null!==t["x-api-key"]&&(!this.authToken||!e.authorization)&&null!==t.authorization)throw Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}authHeaders(e){let t=this.apiKeyAuth(e),r=this.bearerAuth(e);return null==t||tm(t)?null==r||tm(r)?{}:r:t}apiKeyAuth(e){return null==this.apiKey?{}:{"X-Api-Key":this.apiKey}}bearerAuth(e){return null==this.authToken?{}:{Authorization:`Bearer ${this.authToken}`}}}eP=tQ,tQ.Anthropic=eP,tQ.HUMAN_PROMPT="\n\nHuman:",tQ.AI_PROMPT="\n\nAssistant:",tQ.DEFAULT_TIMEOUT=6e5,tQ.AnthropicError=E,tQ.APIError=k,tQ.APIConnectionError=S,tQ.APIConnectionTimeoutError=A,tQ.APIUserAbortError=x,tQ.NotFoundError=N,tQ.ConflictError=j,tQ.RateLimitError=C,tQ.BadRequestError=P,tQ.AuthenticationError=T,tQ.InternalServerError=$,tQ.PermissionDeniedError=I,tQ.UnprocessableEntityError=R,tQ.toFile=eG,tQ.fileFromPath=u,tQ.Completions=tk,tQ.Messages=tU,tQ.Models=tF,tQ.ModelInfosPage=tB,tQ.Beta=tX;let{HUMAN_PROMPT:t0,AI_PROMPT:t1}=tQ;var t2=r(5415),t4=r(43399),t5=r(1776),t9=r(46580),t3=r(97832);let t6=Symbol("Let zodToJsonSchema decide on which parser to use"),t8={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"},t7=e=>"string"==typeof e?{...t8,name:e}:{...t8,...e},re=e=>{let t=t7(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};var rt=r(55594);function rr(){return{}}function ra(e,t,r,a){a?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function ri(e,t,r,a,i){e[t]=r,ra(e,t,a,i)}function rn(e,t){let r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==rt.kY.ZodAny&&(r.items=rK(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&ri(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&ri(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(ri(r,"minItems",e.exactLength.value,e.exactLength.message,t),ri(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function rs(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let a of e.checks)switch(a.kind){case"min":"jsonSchema7"===t.target?a.inclusive?ri(r,"minimum",a.value,a.message,t):ri(r,"exclusiveMinimum",a.value,a.message,t):(a.inclusive||(r.exclusiveMinimum=!0),ri(r,"minimum",a.value,a.message,t));break;case"max":"jsonSchema7"===t.target?a.inclusive?ri(r,"maximum",a.value,a.message,t):ri(r,"exclusiveMaximum",a.value,a.message,t):(a.inclusive||(r.exclusiveMaximum=!0),ri(r,"maximum",a.value,a.message,t));break;case"multipleOf":ri(r,"multipleOf",a.value,a.message,t)}return r}function ro(){return{type:"boolean"}}function rl(e,t){return rK(e.type._def,t)}let ru=(e,t)=>rK(e.innerType._def,t);function rc(e,t,r){let a=r??t.dateStrategy;if(Array.isArray(a))return{anyOf:a.map((r,a)=>rc(e,t,r))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return rh(e,t)}}let rh=(e,t)=>{let r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(let a of e.checks)switch(a.kind){case"min":ri(r,"minimum",a.value,a.message,t);break;case"max":ri(r,"maximum",a.value,a.message,t)}return r};function rd(e,t){return{...rK(e.innerType._def,t),default:e.defaultValue()}}function rp(e,t){return"input"===t.effectStrategy?rK(e.schema._def,t):{}}function rf(e){return{type:"string",enum:Array.from(e.values)}}let rm=e=>(!("type"in e)||"string"!==e.type)&&"allOf"in e;function rg(e,t){let r=[rK(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),rK(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(e=>!!e),a="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0,i=[];return r.forEach(e=>{if(rm(e))i.push(...e.allOf),void 0===e.unevaluatedProperties&&(a=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){let{additionalProperties:r,...a}=e;t=a}else a=void 0;i.push(t)}}),i.length?{allOf:i,...a}:void 0}function ry(e,t){let r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}let rb={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:()=>(void 0===c&&(c=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),c),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])$/,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 r_(e,t){let r={type:"string"};if(e.checks)for(let a of e.checks)switch(a.kind){case"min":ri(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,a.value):a.value,a.message,t);break;case"max":ri(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,a.value):a.value,a.message,t);break;case"email":switch(t.emailStrategy){case"format:email":rE(r,"email",a.message,t);break;case"format:idn-email":rE(r,"idn-email",a.message,t);break;case"pattern:zod":rk(r,rb.email,a.message,t)}break;case"url":rE(r,"uri",a.message,t);break;case"uuid":rE(r,"uuid",a.message,t);break;case"regex":rk(r,a.regex,a.message,t);break;case"cuid":rk(r,rb.cuid,a.message,t);break;case"cuid2":rk(r,rb.cuid2,a.message,t);break;case"startsWith":rk(r,RegExp(`^${rw(a.value,t)}`),a.message,t);break;case"endsWith":rk(r,RegExp(`${rw(a.value,t)}$`),a.message,t);break;case"datetime":rE(r,"date-time",a.message,t);break;case"date":rE(r,"date",a.message,t);break;case"time":rE(r,"time",a.message,t);break;case"duration":rE(r,"duration",a.message,t);break;case"length":ri(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,a.value):a.value,a.message,t),ri(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,a.value):a.value,a.message,t);break;case"includes":rk(r,RegExp(rw(a.value,t)),a.message,t);break;case"ip":"v6"!==a.version&&rE(r,"ipv4",a.message,t),"v4"!==a.version&&rE(r,"ipv6",a.message,t);break;case"base64url":rk(r,rb.base64url,a.message,t);break;case"jwt":rk(r,rb.jwt,a.message,t);break;case"cidr":"v6"!==a.version&&rk(r,rb.ipv4Cidr,a.message,t),"v4"!==a.version&&rk(r,rb.ipv6Cidr,a.message,t);break;case"emoji":rk(r,rb.emoji(),a.message,t);break;case"ulid":rk(r,rb.ulid,a.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":rE(r,"binary",a.message,t);break;case"contentEncoding:base64":ri(r,"contentEncoding","base64",a.message,t);break;case"pattern:zod":rk(r,rb.base64,a.message,t)}break;case"nanoid":rk(r,rb.nanoid,a.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:(e=>{})(0)}return r}function rw(e,t){return"escape"===t.patternStrategy?rO(e):e}let rv=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function rO(e){let t="";for(let r=0;re.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&a.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&a.errorMessages&&{errorMessage:{format:r}}})):ri(e,"format",t,r,a)}function rk(e,t,r,a){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&a.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:rx(t,a),...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):ri(e,"pattern",rx(t,a),r,a)}function rx(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},a=r.i?e.source.toLowerCase():e.source,i="",n=!1,s=!1,o=!1;for(let e=0;e({...r,[a]:rK(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",a]})??{}}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:rK(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===rt.kY.ZodString&&e.keyType._def.checks?.length){let{type:a,...i}=r_(e.keyType._def,t);return{...r,propertyNames:i}}if(e.keyType?._def.typeName===rt.kY.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===rt.kY.ZodBranded&&e.keyType._def.type._def.typeName===rt.kY.ZodString&&e.keyType._def.type._def.checks?.length){let{type:a,...i}=rl(e.keyType._def,t);return{...r,propertyNames:i}}return r}function rA(e,t){return"record"===t.mapStrategy?rS(e,t):{type:"array",maxItems:125,items:{type:"array",items:[rK(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},rK(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}function rP(e){let t=e.values,r=Object.keys(e.values).filter(e=>"number"!=typeof t[t[e]]).map(e=>t[e]),a=Array.from(new Set(r.map(e=>typeof e)));return{type:1===a.length?"string"===a[0]?"string":"number":["string","number"],enum:r}}function rT(){return{not:{}}}function rI(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}let rN={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function rj(e,t){if("openApi3"===t.target)return rR(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(e=>e._def.typeName in rN&&(!e._def.checks||!e._def.checks.length))){let e=r.reduce((e,t)=>{let r=rN[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e},[]);return{type:e.length>1?e:e[0]}}if(r.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){let e=r.reduce((e,t)=>{let r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===r.length){let t=e.filter((e,t,r)=>r.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:r.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(r.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:r.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return rR(e,t)}let rR=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>rK(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0};function rC(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:rN[e.innerType._def.typeName],nullable:!0}:{type:[rN[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){let r=rK(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let r=rK(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function r$(e,t){let r={type:"number"};if(!e.checks)return r;for(let a of e.checks)switch(a.kind){case"int":r.type="integer",ra(r,"type",a.message,t);break;case"min":"jsonSchema7"===t.target?a.inclusive?ri(r,"minimum",a.value,a.message,t):ri(r,"exclusiveMinimum",a.value,a.message,t):(a.inclusive||(r.exclusiveMinimum=!0),ri(r,"minimum",a.value,a.message,t));break;case"max":"jsonSchema7"===t.target?a.inclusive?ri(r,"maximum",a.value,a.message,t):ri(r,"exclusiveMaximum",a.value,a.message,t):(a.inclusive||(r.exclusiveMaximum=!0),ri(r,"maximum",a.value,a.message,t));break;case"multipleOf":ri(r,"multipleOf",a.value,a.message,t)}return r}function rM(e,t){let r="openAi"===t.target,a={type:"object",properties:{}},i=[],n=e.shape();for(let e in n){let s=n[e];if(void 0===s||void 0===s._def)continue;let o=rU(s);o&&r&&(s instanceof rt.Ii&&(s=s._def.innerType),s.isNullable()||(s=s.nullable()),o=!1);let l=rK(s._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==l&&(a.properties[e]=l,o||i.push(e))}i.length&&(a.required=i);let s=rL(e,t);return void 0!==s&&(a.additionalProperties=s),a}function rL(e,t){if("ZodNever"!==e.catchall._def.typeName)return rK(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function rU(e){try{return e.isOptional()}catch{return!0}}let rD=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return rK(e.innerType._def,t);let r=rK(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}},rF=(e,t)=>{if("input"===t.pipeStrategy)return rK(e.in._def,t);if("output"===t.pipeStrategy)return rK(e.out._def,t);let r=rK(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),a=rK(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,a].filter(e=>void 0!==e)}};function rB(e,t){return rK(e.type._def,t)}function rz(e,t){let r={type:"array",uniqueItems:!0,items:rK(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ri(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ri(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function rH(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,r)=>rK(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:rK(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,r)=>rK(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}function rZ(){return{not:{}}}function rq(){return{}}let rG=(e,t)=>rK(e.innerType._def,t),rW=(e,t,r)=>{switch(t){case rt.kY.ZodString:return r_(e,r);case rt.kY.ZodNumber:return r$(e,r);case rt.kY.ZodObject:return rM(e,r);case rt.kY.ZodBigInt:return rs(e,r);case rt.kY.ZodBoolean:return ro();case rt.kY.ZodDate:return rc(e,r);case rt.kY.ZodUndefined:return rZ();case rt.kY.ZodNull:return rI(r);case rt.kY.ZodArray:return rn(e,r);case rt.kY.ZodUnion:case rt.kY.ZodDiscriminatedUnion:return rj(e,r);case rt.kY.ZodIntersection:return rg(e,r);case rt.kY.ZodTuple:return rH(e,r);case rt.kY.ZodRecord:return rS(e,r);case rt.kY.ZodLiteral:return ry(e,r);case rt.kY.ZodEnum:return rf(e);case rt.kY.ZodNativeEnum:return rP(e);case rt.kY.ZodNullable:return rC(e,r);case rt.kY.ZodOptional:return rD(e,r);case rt.kY.ZodMap:return rA(e,r);case rt.kY.ZodSet:return rz(e,r);case rt.kY.ZodLazy:return()=>e.getter()._def;case rt.kY.ZodPromise:return rB(e,r);case rt.kY.ZodNaN:case rt.kY.ZodNever:return rT();case rt.kY.ZodEffects:return rp(e,r);case rt.kY.ZodAny:return rr();case rt.kY.ZodUnknown:return rq();case rt.kY.ZodDefault:return rd(e,r);case rt.kY.ZodBranded:return rl(e,r);case rt.kY.ZodReadonly:return rG(e,r);case rt.kY.ZodCatch:return ru(e,r);case rt.kY.ZodPipeline:return rF(e,r);case rt.kY.ZodFunction:case rt.kY.ZodVoid:case rt.kY.ZodSymbol:return;default:let a;return void(a=0)}};function rK(e,t,r=!1){let a=t.seen.get(e);if(t.override){let i=t.override?.(e,t,a,r);if(i!==t6)return i}if(a&&!r){let e=rJ(a,t);if(void 0!==e)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let n=rW(e,e.typeName,t),s="function"==typeof n?rK(n(),t):n;if(s&&rV(e,t,s),t.postProcess){let r=t.postProcess(s,e,t);return i.jsonSchema=s,r}return i.jsonSchema=s,s}let rJ=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:rY(t.currentPath,e.path)};case"none":case"seen":if(e.path.lengtht.currentPath[r]===e))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{};return"seen"===t.$refStrategy?{}:void 0}},rY=(e,t)=>{let r=0;for(;r(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),rX=(e,t)=>{let r=re(t),a="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,a])=>({...e,[t]:rK(a._def,{...r,currentPath:[...r.basePath,r.definitionPath,t]},!0)??{}}),{}):void 0,i="string"==typeof t?t:t?.nameStrategy==="title"?void 0:t?.name,n=rK(e._def,void 0===i?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??{},s="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==s&&(n.title=s);let o=void 0===i?a?{...n,[r.definitionPath]:a}:n:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...a,[i]:n}};return"jsonSchema7"===r.target?o.$schema="http://json-schema.org/draft-07/schema#":("jsonSchema2019-09"===r.target||"openAi"===r.target)&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===r.target&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o};var rQ=r(58775),r0=r(70240),r1=r(46628),r2=r(3909);class r4 extends r2.vd{static lc_name(){return"AnthropicToolsOutputParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","anthropic","output_parsers"]}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){let t=e;if("string"==typeof e)try{t=JSON.parse(e)}catch(t){throw new r2.CC(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.message)}`,e)}else t=e;if(void 0===this.zodSchema)return t;let r=await this.zodSchema.safeParseAsync(t);if(r.success)return r.data;throw new r2.CC(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.error.errors)}`,JSON.stringify(t,null,2))}async parseResult(e){let t=e.flatMap(e=>{let{message:t}=e;return Array.isArray(t.content)?r5(t.content)[0]:[]});if(void 0===t[0])throw Error("No parseable tool calls provided to AnthropicToolsOutputParser.");let[r]=t;return await this._validateResult(r.args)}}function r5(e){let t=[];for(let r of e)"tool_use"===r.type&&t.push({name:r.name,args:r.input,id:r.id,type:"tool_call"});return t}function r9(e){if(e)return"any"===e?{type:"any"}:"auto"===e?{type:"auto"}:"string"==typeof e?{type:"tool",name:e}:e}function r3(e){let t=/^data:(image\/.+);base64,(.+)$/,r=e.match(t);if(null===r)throw Error("Anthropic only supports base64-encoded images currently.\n\nExample: data:image/png;base64,/9j/4AAQSk...");return{type:"base64",media_type:r[1]??"",data:r[2]??""}}function r6(e){let t=[];for(let r of e)if("tool"===r._getType()){if("string"==typeof r.content){let e=t[t.length-1];e?._getType()==="human"&&Array.isArray(e.content)&&"type"in e.content[0]&&"tool_result"===e.content[0].type?e.content.push({type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}):t.push(new t2.xc({content:[{type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}]}))}else t.push(new t2.xc({content:[{type:"tool_result",content:r7(r.content),tool_use_id:r.tool_call_id}]}))}else t.push(r);return t}function r8(e){if(void 0===e.id)throw Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:e.id,name:e.name,input:e.args}}function r7(e){let t=["tool_use","tool_result","input_json_delta"],r=["text","text_delta"];return"string"==typeof e?e:e.map(e=>{let a="cache_control"in e?e.cache_control:void 0;if("image_url"===e.type){let t;return{type:"image",source:t="string"==typeof e.image_url?r3(e.image_url):r3(e.image_url.url),...a?{cache_control:a}:{}}}if("document"===e.type)return{...e,...a?{cache_control:a}:{}};if("thinking"===e.type)return{type:"thinking",thinking:e.thinking,signature:e.signature,...a?{cache_control:a}:{}};if("redacted_thinking"===e.type)return{type:"redacted_thinking",data:e.data,...a?{cache_control:a}:{}};if(r.find(t=>t===e.type)&&"text"in e)return{type:"text",text:e.text,...a?{cache_control:a}:{}};else if(t.find(t=>t===e.type)){let t={...e};if("index"in t&&delete t.index,"input_json_delta"===t.type&&(t.type="tool_use"),"input"in t)try{t.input=JSON.parse(t.input)}catch{}return{...t,...a?{cache_control:a}:{}}}else throw Error("Unsupported message content format")})}function ae(e){let t;let r=r6(e);return r.length>0&&"system"===r[0]._getType()&&(t=e[0].content),{messages:at((void 0!==t?r.slice(1):r).map(e=>{let t;if("human"===e._getType())t="user";else if("ai"===e._getType())t="assistant";else if("tool"===e._getType())t="user";else if("system"===e._getType())throw Error("System messages are only permitted as the first passed message.");else throw Error(`Message type "${e._getType()}" is not supported.`);if(!((0,t2.KX)(e)&&e.tool_calls?.length))return{role:t,content:r7(e.content)};if("string"==typeof e.content)return""===e.content?{role:t,content:e.tool_calls.map(r8)}:{role:t,content:[{type:"text",text:e.content},...e.tool_calls.map(r8)]};{let{content:r}=e;return e.tool_calls.every(e=>r.find(t=>("tool_use"===t.type||"input_json_delta"===t.type)&&t.id===e.id))||console.warn('The "tool_calls" field on a message is only respected if content is a string.'),{role:t,content:r7(e.content)}}})),system:t}}function at(e){if(!e||e.length<=1)return e;let t=[],r=e[0],a=e=>"string"==typeof e?[{type:"text",text:e}]:e,i=e=>"user"===e.role&&"string"!=typeof e.content&&Array.isArray(e.content)&&e.content.every(e=>"tool_result"===e.type);for(let n=1;n0)}function ao(e){for(let t of e.messages??[])if("string"!=typeof t.content){for(let e of t.content??[])if("object"==typeof e&&null!=e&&"document"===e.type&&"object"==typeof e.citations&&e.citations.enabled)return!0}return!1}function al(e){return!!(e.thinking&&"enabled"===e.thinking.type)}function au(e){return"input_schema"in e}function ac(e){return"string"==typeof e.content?e.content:Array.isArray(e.content)&&e.content.length>=1&&"input"in e.content[0]?"string"==typeof e.content[0].input?e.content[0].input:JSON.stringify(e.content[0].input):Array.isArray(e.content)&&e.content.length>=1&&"text"in e.content[0]?e.content[0].text:void 0}class ah extends t9.xV{static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}constructor(e){if(super(e??{}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"anthropicApiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"topK",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:2048}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:"claude-2.1"}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"claude-2.1"}),Object.defineProperty(this,"invocationKwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stopSequences",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"clientOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"thinking",{enumerable:!0,configurable:!0,writable:!0,value:{type:"disabled"}}),Object.defineProperty(this,"batchClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamingClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"createClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.anthropicApiKey=e?.apiKey??e?.anthropicApiKey??(0,t5.Az)("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!e?.createClient)throw Error("Anthropic API key not found");this.clientOptions=e?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=e?.anthropicApiUrl,this.modelName=e?.model??e?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=e?.invocationKwargs??{},this.temperature=e?.temperature??this.temperature,this.topK=e?.topK??this.topK,this.topP=e?.topP??this.topP,this.maxTokens=e?.maxTokensToSample??e?.maxTokens??this.maxTokens,this.stopSequences=e?.stopSequences??this.stopSequences,this.streaming=e?.streaming??!1,this.streamUsage=e?.streamUsage??this.streamUsage,this.thinking=e?.thinking??this.thinking,this.createClient=e?.createClient??(e=>new tQ(e))}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e){if(e&&e.length)return e.map(e=>{if(au(e))return e;if((0,t3.VC)(e))return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};if((0,r1.qG)(e))return{name:e.name,description:e.description,input_schema:rX(e.schema)};throw Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(e,null,2)}`)})}bindTools(e,t){return this.bind({tools:this.formatStructuredToolToAnthropic(e),...t})}invocationParams(e){let t=r9(e?.tool_choice);if("enabled"===this.thinking.type){if(-1!==this.topK)throw Error("topK is not supported when thinking is enabled");if(-1!==this.topP)throw Error("topP is not supported when thinking is enabled");if(1!==this.temperature)throw Error("temperature is not supported when thinking is enabled");return{model:this.model,stop_sequences:e?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(e?.tools),tool_choice:t,thinking:this.thinking,...this.invocationKwargs}}return{model:this.model,temperature:this.temperature,top_k:this.topK,top_p:this.topP,stop_sequences:e?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(e?.tools),tool_choice:t,thinking:this.thinking,...this.invocationKwargs}}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async *_streamResponseChunks(e,t,r){let a=this.invocationParams(t),i=ae(e),n={...a,...i,stream:!0},s=!as(n)&&!ao(n)&&!al(n),o=await this.createStreamWithRetry(n,{headers:t.headers});for await(let e of o){if(t.signal?.aborted)throw o.controller.abort(),Error("AbortError: User aborted the request.");let a=this.streamUsage??t.streamUsage,i=ar(e,{streamUsage:a,coerceContentToString:s});if(!i)continue;let{chunk:n}=i,l=ac(n),u=new t4.Cf({message:new t2.H({content:n.content,additional_kwargs:n.additional_kwargs,tool_call_chunks:n.tool_call_chunks,usage_metadata:a?n.usage_metadata:void 0,response_metadata:n.response_metadata,id:n.id}),text:l??""});yield u,await r?.handleLLMNewToken(l??"",void 0,void 0,void 0,void 0,{chunk:u})}}async _generateNonStreaming(e,t,r){let{content:a,...i}=await this.completionWithRetry({...t,stream:!1,...ae(e)},r),n=aa(a,i),{role:s,type:o,...l}=i;return{generations:n,llmOutput:l}}async _generate(e,t,r){if(this.stopSequences&&t.stop)throw Error('"stopSequence" parameter found in input and default params');let a=this.invocationParams(t);if(!a.stream)return this._generateNonStreaming(e,a,{signal:t.signal,headers:t.headers});{let a;for await(let i of this._streamResponseChunks(e,t,r))a=void 0===a?i:a.concat(i);if(void 0===a)throw Error("No chunks returned from Anthropic API.");return{generations:[{text:a.text,message:a.message}]}}}async createStreamWithRetry(e,t){if(!this.streamingClient){let e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}let r=async()=>{try{return await this.streamingClient.messages.create({...e,...this.invocationKwargs,stream:!0},t)}catch(e){throw an(e)}};return this.caller.call(r)}async completionWithRetry(e,t){if(!this.batchClient){let e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}let r=async()=>{try{return await this.batchClient.messages.create({...e,...this.invocationKwargs},t)}catch(e){throw an(e)}};return this.caller.callWithOptions({signal:t.signal??void 0},r)}_llmType(){return"anthropic"}withStructuredOutput(e,t){let r,a,i;let n=e,s=t?.name,o=t?.method,l=t?.includeRaw;if("jsonMode"===o)throw Error('Anthropic only supports "functionCalling" as a method.');let u=s??"extract";if((0,r0.l)(n)){let e=rX(n);a=[{name:u,description:e.description??"A function available to call.",input_schema:e}],r=new r4({returnSingle:!0,keyName:u,zodSchema:n})}else{let e;"string"==typeof n.name&&"string"==typeof n.description&&"object"==typeof n.input_schema&&null!=n.input_schema?(e=n,u=n.name):e={name:u,description:n.description??"",input_schema:n},a=[e],r=new r4({returnSingle:!0,keyName:u})}if(this.thinking?.type==="enabled"){let e="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(e);let t=t=>{if(!t.tool_calls||0===t.tool_calls.length)throw Error(e);return t};i=(i=this.bind({tools:a})).pipe(t)}else i=this.bind({tools:a,tool_choice:{type:"tool",name:u}});if(!l)return i.pipe(r).withConfig({runName:"ChatAnthropicStructuredOutput"});let c=rQ.kI.assign({parsed:(e,t)=>r.invoke(e.raw,t)}),h=rQ.kI.assign({parsed:()=>null}),d=c.withFallbacks({fallbacks:[h]});return rQ.zZ.from([{raw:i},d]).withConfig({runName:"StructuredOutputRunnable"})}}class ad extends ah{}},25822:(e,t,r)=>{"use strict";r.d(t,{Y:()=>n});let a=(...e)=>fetch(...e),i=Symbol.for("ls:fetch_implementation"),n=()=>globalThis[i]??a},26076:(e,t,r)=>{let a=r(36053),i=r(42870),n=r(28973);e.exports=(e,t)=>{e=new i(e,t);let r=new a("0.0.0");if(e.test(r)||(r=new a("0.0.0-0"),e.test(r)))return r;r=null;for(let t=0;t{let t=new a(e.semver.version);switch(e.operator){case">":0===t.prerelease.length?t.patch++:t.prerelease.push(0),t.raw=t.format();case"":case">=":(!s||n(t,s))&&(s=t);break;case"<":case"<=":break;default:throw Error(`Unexpected operation: ${e.operator}`)}}),s&&(!r||n(r,s))&&(r=s)}return r&&e.test(r)?r:null}},26264:(e,t,r)=>{"use strict";r(81679),r(18313)},26682:e=>{"use strict";e.exports=(e,t)=>{for(t=String(t);t.length{"use strict";r.d(t,{k:()=>s});var a=r(87150),i=r(4693),n=r(92173);class s extends i.YN{static lc_name(){return"RunnablePassthrough"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e&&(this.func=e.func)}async invoke(e,t){let r=(0,n.ZI)(t);return this.func&&await this.func(e,r),this._callWithConfig(e=>Promise.resolve(e),e,r)}async *transform(e,t){let r;let i=(0,n.ZI)(t),s=!0;for await(let t of this._transformStreamWithConfig(e,e=>e,i))if(yield t,s){if(void 0===r)r=t;else try{r=(0,a.xW)(r,t)}catch{r=void 0,s=!1}}this.func&&void 0!==r&&await this.func(r,i)}static assign(e){return new i.B2(new i.ck({steps:e}))}}},27231:(e,t,r)=>{"use strict";r.d(t,{dr:()=>n,p1:()=>s,uf:()=>i});var a=r(64520);class i extends a.XQ{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}constructor(e,t,r){"string"==typeof e&&(e={content:e,name:r,tool_call_id:t}),super(e),Object.defineProperty(this,"lc_direct_tool_output",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}_getType(){return"tool"}static isInstance(e){return"tool"===e._getType()}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}class n extends a.gj{constructor(e){super(e),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}_getType(){return"tool"}concat(e){return new n({content:(0,a._I)(this.content,e.content),additional_kwargs:(0,a.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,a.ns)(this.response_metadata,e.response_metadata),artifact:(0,a.F7)(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:(0,a.Iv)(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}function s(e){let t=[],r=[];for(let a of e)if(a.function){let e=a.function.name;try{let r=JSON.parse(a.function.arguments),i={name:e||"",args:r||{},id:a.id};t.push(i)}catch(t){r.push({name:e,args:a.function.arguments,id:a.id,error:"Malformed args."})}}return[t,r]}},28809:(e,t,r)=>{"use strict";function a(e){return!!(e&&"object"==typeof e&&"type"in e&&"tool_call"===e.type)}r.d(t,{K:()=>a,q:()=>i});class i extends Error{constructor(e,t){super(e),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=t}}},28973:(e,t,r)=>{let a=r(88193);e.exports=(e,t,r)=>a(e,t,r)>0},29200:e=>{function t(e,t){"boolean"==typeof t&&(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))}e.exports=t,t.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},t.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},t.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var a=this;return this._timer=setTimeout(function(){a._attempts++,a._operationTimeoutCb&&(a._timeout=setTimeout(function(){a._operationTimeoutCb(a._attempts)},a._operationTimeout),a._options.unref&&a._timeout.unref()),a._fn(a._attempts)},r),this._options.unref&&this._timer.unref(),!0},t.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)},t.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},t.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},t.prototype.start=t.prototype.try,t.prototype.errors=function(){return this._errors},t.prototype.attempts=function(){return this._attempts},t.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,a=0;a=r&&(t=i,r=s)}return t}},29555:(e,t,r)=>{let a=r(36053);e.exports=(e,t)=>new a(e,t).major},31107:(e,t,r)=>{let a=r(42870);e.exports=(e,t)=>{try{return new a(e,t).range||"*"}catch(e){return null}}},31432:(e,t,r)=>{let a=r(89377);e.exports=(e,t)=>{let r=a(e,t);return r?r.version:null}},32002:e=>{let t=Object.freeze({loose:!0}),r=Object.freeze({});e.exports=e=>e?"object"!=typeof e?t:e:r},32227:(e,t,r)=>{let a=r(36053),i=r(89377),{safeRe:n,t:s}=r(56655);e.exports=(e,t)=>{if(e instanceof a)return e;if("number"==typeof e&&(e=String(e)),"string"!=typeof e)return null;let r=null;if((t=t||{}).rtl){let a;let i=t.includePrerelease?n[s.COERCERTLFULL]:n[s.COERCERTL];for(;(a=i.exec(e))&&(!r||r.index+r[0].length!==e.length);)r&&a.index+a[0].length===r.index+r[0].length||(r=a),i.lastIndex=a.index+a[1].length+a[2].length;i.lastIndex=-1}else r=e.match(t.includePrerelease?n[s.COERCEFULL]:n[s.COERCE]);if(null===r)return null;let o=r[2],l=r[3]||"0",u=r[4]||"0",c=t.includePrerelease&&r[5]?`-${r[5]}`:"",h=t.includePrerelease&&r[6]?`+${r[6]}`:"";return i(`${o}.${l}.${u}${c}${h}`,t)}},32463:(e,t,r)=>{let a=r(36053);e.exports=(e,t)=>new a(e,t).minor},34290:(e,t,r)=>{let a=r(36053),i=r(50113),{ANY:n}=i,s=r(42870),o=r(43879),l=r(28973),u=r(23906),c=r(34817),h=r(98344);e.exports=(e,t,r,d)=>{let p,f,m,g,y;switch(e=new a(e,d),t=new s(t,d),r){case">":p=l,f=c,m=u,g=">",y=">=";break;case"<":p=u,f=h,m=l,g="<",y="<=";break;default:throw TypeError('Must provide a hilo val of "<" or ">"')}if(o(e,t,d))return!1;for(let r=0;r{e.semver===n&&(e=new i(">=0.0.0")),s=s||e,o=o||e,p(e.semver,s.semver,d)?s=e:m(e.semver,o.semver,d)&&(o=e)}),s.operator===g||s.operator===y||(!o.operator||o.operator===g)&&f(e,o.semver)||o.operator===y&&m(e,o.semver))return!1}return!0}},34817:(e,t,r)=>{let a=r(88193);e.exports=(e,t,r)=>0>=a(e,t,r)},34984:(e,t,r)=>{let a=r(88193);e.exports=(e,t,r)=>0===a(e,t,r)},35169:(e,t,r)=>{"use strict";r.d(t,{A:()=>a});let a=(0,r(90163).A)("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]])},36053:(e,t,r)=>{let a=r(57265),{MAX_LENGTH:i,MAX_SAFE_INTEGER:n}=r(81979),{safeRe:s,safeSrc:o,t:l}=r(56655),u=r(32002),{compareIdentifiers:c}=r(83930);class h{constructor(e,t){if(t=u(t),e instanceof h){if(!!t.loose===e.loose&&!!t.includePrerelease===e.includePrerelease)return e;e=e.version}else if("string"!=typeof e)throw TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>i)throw TypeError(`version is longer than ${i} characters`);a("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let r=e.trim().match(t.loose?s[l.LOOSE]:s[l.FULL]);if(!r)throw TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>n||this.major<0)throw TypeError("Invalid major version");if(this.minor>n||this.minor<0)throw TypeError("Invalid minor version");if(this.patch>n||this.patch<0)throw TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(e=>{if(/^[0-9]+$/.test(e)){let t=+e;if(t>=0&&t=0;)"number"==typeof this.prerelease[a]&&(this.prerelease[a]++,a=-2);if(-1===a){if(t===this.prerelease.join(".")&&!1===r)throw Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(t){let a=[t,e];!1===r&&(a=[t]),0===c(this.prerelease[0],t)?isNaN(this.prerelease[1])&&(this.prerelease=a):this.prerelease=a}break}default:throw Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}e.exports=h},37323:(e,t,r)=>{"use strict";r.d(t,{P:()=>c});var a=r(46580),i=r(5415),n=r(43399),s=r(87150);async function*o(e,t,r){let a=e;a.startsWith("http://localhost:")&&(a=a.replace("http://localhost:","http://127.0.0.1:"));let i=await fetch(a,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",...r.headers},signal:r.signal});if(!i.ok){let e;let t=await i.text();try{let r=JSON.parse(t);e=Error(`Ollama call failed with status code ${i.status}: ${r.error}`)}catch(r){e=Error(`Ollama call failed with status code ${i.status}: ${t}`)}throw e.response=i,e}if(!i.body)throw Error("Could not begin Ollama stream. Please check the given URL and try again.");let n=s.bO.fromReadableStream(i.body),o=new TextDecoder,l="";for await(let e of n){let t=(l+o.decode(e)).split("\n");for(let e of(l=t.pop()||"",t))try{yield JSON.parse(e)}catch(t){console.warn(`Received a non-JSON parseable chunk: ${e}`)}}}async function*l(e,t,r){yield*o(`${e}/api/generate`,t,r)}async function*u(e,t,r){yield*o(`${e}/api/chat`,t,r)}class c extends a.a7{static lc_name(){return"ChatOllama"}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"llama2"}),Object.defineProperty(this,"baseUrl",{enumerable:!0,configurable:!0,writable:!0,value:"http://localhost:11434"}),Object.defineProperty(this,"keepAlive",{enumerable:!0,configurable:!0,writable:!0,value:"5m"}),Object.defineProperty(this,"embeddingOnly",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"f16KV",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"frequencyPenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logitsAll",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lowVram",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mainGpu",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mirostat",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mirostatEta",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mirostatTau",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numBatch",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numCtx",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numGpu",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numGqa",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numKeep",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numPredict",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numThread",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"penalizeNewline",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"presencePenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"repeatLastN",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"repeatPenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ropeFrequencyBase",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ropeFrequencyScale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tfsZ",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topK",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"typicalP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"useMLock",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"useMMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"vocabOnly",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"format",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.model=e.model??this.model,this.baseUrl=e.baseUrl?.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl??this.baseUrl,this.keepAlive=e.keepAlive??this.keepAlive,this.embeddingOnly=e.embeddingOnly,this.f16KV=e.f16KV,this.frequencyPenalty=e.frequencyPenalty,this.headers=e.headers,this.logitsAll=e.logitsAll,this.lowVram=e.lowVram,this.mainGpu=e.mainGpu,this.mirostat=e.mirostat,this.mirostatEta=e.mirostatEta,this.mirostatTau=e.mirostatTau,this.numBatch=e.numBatch,this.numCtx=e.numCtx,this.numGpu=e.numGpu,this.numGqa=e.numGqa,this.numKeep=e.numKeep,this.numPredict=e.numPredict,this.numThread=e.numThread,this.penalizeNewline=e.penalizeNewline,this.presencePenalty=e.presencePenalty,this.repeatLastN=e.repeatLastN,this.repeatPenalty=e.repeatPenalty,this.ropeFrequencyBase=e.ropeFrequencyBase,this.ropeFrequencyScale=e.ropeFrequencyScale,this.temperature=e.temperature,this.stop=e.stop,this.tfsZ=e.tfsZ,this.topK=e.topK,this.topP=e.topP,this.typicalP=e.typicalP,this.useMLock=e.useMLock,this.useMMap=e.useMMap,this.vocabOnly=e.vocabOnly,this.format=e.format}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:"ollama",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:this.temperature??void 0,ls_stop:this.stop,ls_max_tokens:t.options.num_predict}}_llmType(){return"ollama"}invocationParams(e){return{model:this.model,format:this.format,keep_alive:this.keepAlive,options:{embedding_only:this.embeddingOnly,f16_kv:this.f16KV,frequency_penalty:this.frequencyPenalty,logits_all:this.logitsAll,low_vram:this.lowVram,main_gpu:this.mainGpu,mirostat:this.mirostat,mirostat_eta:this.mirostatEta,mirostat_tau:this.mirostatTau,num_batch:this.numBatch,num_ctx:this.numCtx,num_gpu:this.numGpu,num_gqa:this.numGqa,num_keep:this.numKeep,num_predict:this.numPredict,num_thread:this.numThread,penalize_newline:this.penalizeNewline,presence_penalty:this.presencePenalty,repeat_last_n:this.repeatLastN,repeat_penalty:this.repeatPenalty,rope_frequency_base:this.ropeFrequencyBase,rope_frequency_scale:this.ropeFrequencyScale,temperature:this.temperature,stop:e?.stop??this.stop,tfs_z:this.tfsZ,top_k:this.topK,top_p:this.topP,typical_p:this.typicalP,use_mlock:this.useMLock,use_mmap:this.useMMap,vocab_only:this.vocabOnly}}}_combineLLMOutput(){return{}}async *_streamResponseChunksLegacy(e,t,r){for await(let a of l(this.baseUrl,{...this.invocationParams(t),prompt:this._formatMessagesAsPrompt(e)},{...t,headers:this.headers}))a.done?yield new n.Cf({text:"",message:new i.H({content:""}),generationInfo:{model:a.model,total_duration:a.total_duration,load_duration:a.load_duration,prompt_eval_count:a.prompt_eval_count,prompt_eval_duration:a.prompt_eval_duration,eval_count:a.eval_count,eval_duration:a.eval_duration}}):(yield new n.Cf({text:a.response,message:new i.H({content:a.response})}),await r?.handleLLMNewToken(a.response??""))}async *_streamResponseChunks(e,t,r){try{for await(let a of(await this.caller.call(async()=>u(this.baseUrl,{...this.invocationParams(t),messages:this._convertMessagesToOllamaMessages(e)},{...t,headers:this.headers}))))a.done?yield new n.Cf({text:"",message:new i.H({content:""}),generationInfo:{model:a.model,total_duration:a.total_duration,load_duration:a.load_duration,prompt_eval_count:a.prompt_eval_count,prompt_eval_duration:a.prompt_eval_duration,eval_count:a.eval_count,eval_duration:a.eval_duration}}):(yield new n.Cf({text:a.message.content,message:new i.H({content:a.message.content})}),await r?.handleLLMNewToken(a.message.content??""))}catch(a){if(a.response?.status===404)console.warn("[WARNING]: It seems you are using a legacy version of Ollama. Please upgrade to a newer version for better chat support."),yield*this._streamResponseChunksLegacy(e,t,r);else throw a}}_convertMessagesToOllamaMessages(e){return e.map(e=>{let t;if("human"===e._getType())t="user";else if("ai"===e._getType())t="assistant";else if("system"===e._getType())t="system";else throw Error(`Unsupported message type for Ollama: ${e._getType()}`);let r="",a=[];if("string"==typeof e.content)r=e.content;else for(let t of e.content)if("text"===t.type)r=`${r} ${t.text}`;else if("image_url"===t.type&&"string"==typeof t.image_url){let e=t.image_url.split(",");a.push(e[1]??e[0])}else throw Error('Unsupported message content type. Must either have type "text" or type "image_url" with a string "image_url" field.');return{role:t,content:r,images:a}})}_formatMessagesAsPrompt(e){return e.map(e=>{let t;return"human"===e._getType()?t=`[INST] ${e.content} [/INST]`:"ai"===e._getType()?t=e.content:"system"===e._getType()?t=`<> ${e.content} <>`:i.cM.isInstance(e)?t=` ${e.role[0].toUpperCase()}${e.role.slice(1)}: ${e.content}`:(console.warn(`Unsupported message type passed to Ollama: "${e._getType()}"`),t=""),t}).join("\n")}async _call(e,t,r){let a=[];for await(let i of this._streamResponseChunks(e,t,r))a.push(i.message.content);return a.join("")}}},41039:(e,t,r)=>{"use strict";r.d(t,{H:()=>u,KX:()=>o,Od:()=>s,jm:()=>l});var a=r(58036),i=r(64520),n=r(27231);class s extends i.XQ{get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(e,t){let r;if("string"==typeof e)r={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:t??{}};else{r=e;let t=r.additional_kwargs?.tool_calls,a=r.tool_calls;null!=t&&t.length>0&&(void 0===a||0===a.length)&&console.warn("New LangChain packages are available that more efficiently handle tool calling.\n\nPlease upgrade your packages to versions that set message tool calls. e.g., `yarn add @langchain/anthropic`, yarn add @langchain/openai`, etc.");try{if(null!=t&&void 0===a){let[e,a]=(0,n.p1)(t);r.tool_calls=e??[],r.invalid_tool_calls=a??[]}else r.tool_calls=r.tool_calls??[],r.invalid_tool_calls=r.invalid_tool_calls??[]}catch(e){r.tool_calls=[],r.invalid_tool_calls=[]}}super(r),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),"string"!=typeof r&&(this.tool_calls=r.tool_calls??this.tool_calls,this.invalid_tool_calls=r.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=r.usage_metadata}static lc_name(){return"AIMessage"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}}function o(e){return"ai"===e._getType()}function l(e){return"ai"===e._getType()}class u extends i.gj{constructor(e){let t;if("string"==typeof e)t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(void 0===e.tool_call_chunks)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:void 0!==e.usage_metadata?e.usage_metadata:void 0};else{let r=[],i=[];for(let t of e.tool_call_chunks){let e={};try{if(e=(0,a.d)(t.args||"{}"),null===e||"object"!=typeof e||Array.isArray(e))throw Error("Malformed tool call chunk args.");r.push({name:t.name??"",args:e,id:t.id,type:"tool_call"})}catch(e){i.push({name:t.name,args:t.args,id:t.id,error:"Malformed args.",type:"invalid_tool_call"})}}t={...e,tool_calls:r,invalid_tool_calls:i,usage_metadata:void 0!==e.usage_metadata?e.usage_metadata:void 0}}super(t),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tool_call_chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){let t={content:(0,i._I)(this.content,e.content),additional_kwargs:(0,i.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,i.ns)(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(void 0!==this.tool_call_chunks||void 0!==e.tool_call_chunks){let r=(0,i.Vt)(this.tool_call_chunks,e.tool_call_chunks);void 0!==r&&r.length>0&&(t.tool_call_chunks=r)}if(void 0!==this.usage_metadata||void 0!==e.usage_metadata){let 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)}},a={...(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)}},i=this.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},n=e.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0};t.usage_metadata={input_tokens:i.input_tokens+n.input_tokens,output_tokens:i.output_tokens+n.output_tokens,total_tokens:i.total_tokens+n.total_tokens,...Object.keys(r).length>0&&{input_token_details:r},...Object.keys(a).length>0&&{output_token_details:a}}}return new u(t)}}},41412:(e,t,r)=>{let a=r(43879),i=r(88193);e.exports=(e,t,r)=>{let n=[],s=null,o=null,l=e.sort((e,t)=>i(e,t,r));for(let e of l)a(e,t,r)?(o=e,s||(s=e)):(o&&n.push([s,o]),o=null,s=null);s&&n.push([s,null]);let u=[];for(let[e,t]of n)e===t?u.push(e):t||e!==l[0]?t?e===l[0]?u.push(`<=${t}`):u.push(`${e} - ${t}`):u.push(`>=${e}`):u.push("*");let c=u.join(" || "),h="string"==typeof t.raw?t.raw:String(t);return c.length{"use strict";function a(e,t){return e.lc_error_code=t,e.message=`${e.message} Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${t}/ `,e}r.d(t,{Y:()=>a})},42870:(e,t,r)=>{let a=/\s+/g;class i{constructor(e,t){if(t=s(t),e instanceof i){if(!!t.loose===e.loose&&!!t.includePrerelease===e.includePrerelease)return e;return new i(e.raw,t)}if(e instanceof o)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(a," "),this.set=this.raw.split("||").map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let e=this.set[0];if(this.set=this.set.filter(e=>!y(e[0])),0===this.set.length)this.set=[e];else if(this.set.length>1){for(let e of this.set)if(1===e.length&&b(e[0])){this.set=[e];break}}}this.formatted=void 0}get range(){if(void 0===this.formatted){this.formatted="";for(let e=0;e0&&(this.formatted+="||");let t=this.set[e];for(let e=0;e0&&(this.formatted+=" "),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let t=((this.options.includePrerelease&&m)|(this.options.loose&&g))+":"+e,r=n.get(t);if(r)return r;let a=this.options.loose,i=a?c[h.HYPHENRANGELOOSE]:c[h.HYPHENRANGE];l("hyphen replace",e=e.replace(i,I(this.options.includePrerelease))),l("comparator trim",e=e.replace(c[h.COMPARATORTRIM],d)),l("tilde trim",e=e.replace(c[h.TILDETRIM],p)),l("caret trim",e=e.replace(c[h.CARETTRIM],f));let s=e.split(" ").map(e=>w(e,this.options)).join(" ").split(/\s+/).map(e=>T(e,this.options));a&&(s=s.filter(e=>(l("loose invalid filter",e,this.options),!!e.match(c[h.COMPARATORLOOSE])))),l("range list",s);let u=new Map;for(let e of s.map(e=>new o(e,this.options))){if(y(e))return[e];u.set(e.value,e)}u.size>1&&u.has("")&&u.delete("");let b=[...u.values()];return n.set(t,b),b}intersects(e,t){if(!(e instanceof i))throw TypeError("a Range is required");return this.set.some(r=>_(r,t)&&e.set.some(e=>_(e,t)&&r.every(r=>e.every(e=>r.intersects(e,t)))))}test(e){if(!e)return!1;if("string"==typeof e)try{e=new u(e,this.options)}catch(e){return!1}for(let t=0;t"<0.0.0-0"===e.value,b=e=>""===e.value,_=(e,t)=>{let r=!0,a=e.slice(),i=a.pop();for(;r&&a.length;)r=a.every(e=>i.intersects(e,t)),i=a.pop();return r},w=(e,t)=>(l("comp",e,t),l("caret",e=k(e,t)),l("tildes",e=O(e,t)),l("xrange",e=S(e,t)),l("stars",e=P(e,t)),e),v=e=>!e||"x"===e.toLowerCase()||"*"===e,O=(e,t)=>e.trim().split(/\s+/).map(e=>E(e,t)).join(" "),E=(e,t)=>{let r=t.loose?c[h.TILDELOOSE]:c[h.TILDE];return e.replace(r,(t,r,a,i,n)=>{let s;return l("tilde",e,t,r,a,i,n),v(r)?s="":v(a)?s=`>=${r}.0.0 <${+r+1}.0.0-0`:v(i)?s=`>=${r}.${a}.0 <${r}.${+a+1}.0-0`:n?(l("replaceTilde pr",n),s=`>=${r}.${a}.${i}-${n} <${r}.${+a+1}.0-0`):s=`>=${r}.${a}.${i} <${r}.${+a+1}.0-0`,l("tilde return",s),s})},k=(e,t)=>e.trim().split(/\s+/).map(e=>x(e,t)).join(" "),x=(e,t)=>{l("caret",e,t);let r=t.loose?c[h.CARETLOOSE]:c[h.CARET],a=t.includePrerelease?"-0":"";return e.replace(r,(t,r,i,n,s)=>{let o;return l("caret",e,t,r,i,n,s),v(r)?o="":v(i)?o=`>=${r}.0.0${a} <${+r+1}.0.0-0`:v(n)?o="0"===r?`>=${r}.${i}.0${a} <${r}.${+i+1}.0-0`:`>=${r}.${i}.0${a} <${+r+1}.0.0-0`:s?(l("replaceCaret pr",s),o="0"===r?"0"===i?`>=${r}.${i}.${n}-${s} <${r}.${i}.${+n+1}-0`:`>=${r}.${i}.${n}-${s} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${n}-${s} <${+r+1}.0.0-0`):(l("no pr"),o="0"===r?"0"===i?`>=${r}.${i}.${n}${a} <${r}.${i}.${+n+1}-0`:`>=${r}.${i}.${n}${a} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${n} <${+r+1}.0.0-0`),l("caret return",o),o})},S=(e,t)=>(l("replaceXRanges",e,t),e.split(/\s+/).map(e=>A(e,t)).join(" ")),A=(e,t)=>{e=e.trim();let r=t.loose?c[h.XRANGELOOSE]:c[h.XRANGE];return e.replace(r,(r,a,i,n,s,o)=>{l("xRange",e,r,a,i,n,s,o);let u=v(i),c=u||v(n),h=c||v(s),d=h;return"="===a&&d&&(a=""),o=t.includePrerelease?"-0":"",u?r=">"===a||"<"===a?"<0.0.0-0":"*":a&&d?(c&&(n=0),s=0,">"===a?(a=">=",c?(i=+i+1,n=0):n=+n+1,s=0):"<="===a&&(a="<",c?i=+i+1:n=+n+1),"<"===a&&(o="-0"),r=`${a+i}.${n}.${s}${o}`):c?r=`>=${i}.0.0${o} <${+i+1}.0.0-0`:h&&(r=`>=${i}.${n}.0${o} <${i}.${+n+1}.0-0`),l("xRange return",r),r})},P=(e,t)=>(l("replaceStars",e,t),e.trim().replace(c[h.STAR],"")),T=(e,t)=>(l("replaceGTE0",e,t),e.trim().replace(c[t.includePrerelease?h.GTE0PRE:h.GTE0],"")),I=e=>(t,r,a,i,n,s,o,l,u,c,h,d)=>(r=v(a)?"":v(i)?`>=${a}.0.0${e?"-0":""}`:v(n)?`>=${a}.${i}.0${e?"-0":""}`:s?`>=${r}`:`>=${r}${e?"-0":""}`,l=v(u)?"":v(c)?`<${+u+1}.0.0-0`:v(h)?`<${u}.${+c+1}.0-0`:d?`<=${u}.${c}.${h}-${d}`:e?`<${u}.${c}.${+h+1}-0`:`<=${l}`,`${r} ${l}`.trim()),N=(e,t,r)=>{for(let r=0;r0){let a=e[r].semver;if(a.major===t.major&&a.minor===t.minor&&a.patch===t.patch)return!0}return!1}return!0}},43377:(e,t,r)=>{let a=r(42870),i=r(50113),{ANY:n}=i,s=r(43879),o=r(88193),l=(e,t,r={})=>{if(e===t)return!0;e=new a(e,r),t=new a(t,r);let i=!1;e:for(let a of e.set){for(let e of t.set){let t=h(a,e,r);if(i=i||null!==t,t)continue e}if(i)return!1}return!0},u=[new i(">=0.0.0-0")],c=[new i(">=0.0.0")],h=(e,t,r)=>{let a,i,l,h,f,m,g;if(e===t)return!0;if(1===e.length&&e[0].semver===n){if(1===t.length&&t[0].semver===n)return!0;e=r.includePrerelease?u:c}if(1===t.length&&t[0].semver===n){if(r.includePrerelease)return!0;t=c}let y=new Set;for(let t of e)">"===t.operator||">="===t.operator?a=d(a,t,r):"<"===t.operator||"<="===t.operator?i=p(i,t,r):y.add(t.semver);if(y.size>1||a&&i&&((l=o(a.semver,i.semver,r))>0||0===l&&(">="!==a.operator||"<="!==i.operator)))return null;for(let e of y){if(a&&!s(e,String(a),r)||i&&!s(e,String(i),r))return null;for(let a of t)if(!s(e,String(a),r))return!1;return!0}let b=!!i&&!r.includePrerelease&&!!i.semver.prerelease.length&&i.semver,_=!!a&&!r.includePrerelease&&!!a.semver.prerelease.length&&a.semver;for(let e of(b&&1===b.prerelease.length&&"<"===i.operator&&0===b.prerelease[0]&&(b=!1),t)){if(g=g||">"===e.operator||">="===e.operator,m=m||"<"===e.operator||"<="===e.operator,a){if(_&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===_.major&&e.semver.minor===_.minor&&e.semver.patch===_.patch&&(_=!1),">"===e.operator||">="===e.operator){if((h=d(a,e,r))===e&&h!==a)return!1}else if(">="===a.operator&&!s(a.semver,String(e),r))return!1}if(i){if(b&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===b.major&&e.semver.minor===b.minor&&e.semver.patch===b.patch&&(b=!1),"<"===e.operator||"<="===e.operator){if((f=p(i,e,r))===e&&f!==i)return!1}else if("<="===i.operator&&!s(i.semver,String(e),r))return!1}if(!e.operator&&(i||a)&&0!==l)return!1}return(!a||!m||!!i||0===l)&&(!i||!g||!!a||0===l)&&!_&&!b&&!0},d=(e,t,r)=>{if(!e)return t;let a=o(e.semver,t.semver,r);return a>0?e:a<0?t:">"===t.operator&&">="===e.operator?t:e},p=(e,t,r)=>{if(!e)return t;let a=o(e.semver,t.semver,r);return a<0?e:a>0?t:"<"===t.operator&&"<="===e.operator?t:e};e.exports=l},43399:(e,t,r)=>{"use strict";r.d(t,{Cf:()=>a.Cf});var a=r(23294)},43879:(e,t,r)=>{let a=r(42870);e.exports=(e,t,r)=>{try{t=new a(t,r)}catch(e){return!1}return t.test(e)}},44726:(e,t,r)=>{let a=r(88193);e.exports=(e,t,r)=>0!==a(e,t,r)},44768:(e,t,r)=>{"use strict";r.d(t,{X0:()=>s,hr:()=>i,pH:()=>n});let a=Symbol.for("ls:tracing_async_local_storage"),i=Symbol.for("lc:context_variables"),n=e=>{globalThis[a]=e},s=()=>globalThis[a]},46520:(e,t,r)=>{"use strict";let a=r(21232);class i extends Error{constructor(e){super(e),this.name="TimeoutError"}}let n=(e,t,r)=>new Promise((n,s)=>{if("number"!=typeof t||t<0)throw TypeError("Expected `milliseconds` to be a positive number");if(t===1/0){n(e);return}let o=setTimeout(()=>{if("function"==typeof r){try{n(r())}catch(e){s(e)}return}let a="string"==typeof r?r:`Promise timed out after ${t} milliseconds`,o=r instanceof Error?r:new i(a);"function"==typeof e.cancel&&e.cancel(),s(o)},t);a(e.then(n,s),()=>{clearTimeout(o)})});e.exports=n,e.exports.default=n,e.exports.TimeoutError=i},46580:(e,t,r)=>{"use strict";r.d(t,{xV:()=>p,a7:()=>f});var a=r(50084),i=r(71150),n=r(23294),s=r(72400),o=r(77466),l=r(4693),u=r(87150),c=r(27123),h=r(70240),d=r(72716);class p extends s.j_{constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","chat_models",this._llmType()]}),Object.defineProperty(this,"disableStreaming",{enumerable:!0,configurable:!0,writable:!0,value:!1})}_separateRunnableConfigFromCallOptionsCompat(e){let[t,r]=super._separateRunnableConfigFromCallOptions(e);return r.signal=t.signal,[t,r]}async invoke(e,t){let r=p._convertInputToPromptValue(e);return(await this.generatePrompt([r],t,t?.callbacks)).generations[0][0].message}async *_streamResponseChunks(e,t,r){throw Error("Not implemented.")}async *_streamIterator(e,t){if(this._streamResponseChunks===p.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(e,t);else{let r,a;let n=p._convertInputToPromptValue(e).toChatMessages(),[s,l]=this._separateRunnableConfigFromCallOptionsCompat(t),u={...s.metadata,...this.getLsParams(l)},c=await o.Td.configure(s.callbacks,this.callbacks,s.tags,this.tags,u,this.metadata,{verbose:this.verbose}),h={options:l,invocation_params:this?.invocationParams(l),batch_size:1},d=await c?.handleChatModelStart(this.toJSON(),[n],s.runId,void 0,h,void 0,void 0,s.runName);try{for await(let e of this._streamResponseChunks(n,l,d?.[0])){if(null==e.message.id){let t=d?.at(0)?.runId;null!=t&&e.message._updateId(`run-${t}`)}e.message.response_metadata={...e.generationInfo,...e.message.response_metadata},yield e.message,r=r?r.concat(e):e,(0,i.jm)(e.message)&&void 0!==e.message.usage_metadata&&(a={tokenUsage:{promptTokens:e.message.usage_metadata.input_tokens,completionTokens:e.message.usage_metadata.output_tokens,totalTokens:e.message.usage_metadata.total_tokens}})}}catch(e){throw await Promise.all((d??[]).map(t=>t?.handleLLMError(e))),e}await Promise.all((d??[]).map(e=>e?.handleLLMEnd({generations:[[r]],llmOutput:a})))}}getLsParams(e){let t=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:e.stop,ls_provider:t}}async _generateUncached(e,t,r,a){let s;let l=e.map(e=>e.map(i.K0));if(void 0!==a&&a.length===l.length)s=a;else{let e={...r.metadata,...this.getLsParams(t)},a=await o.Td.configure(r.callbacks,this.callbacks,r.tags,this.tags,e,this.metadata,{verbose:this.verbose}),i={options:t,invocation_params:this?.invocationParams(t),batch_size:1};s=await a?.handleChatModelStart(this.toJSON(),l,r.runId,void 0,i,void 0,void 0,r.runName)}let c=[],h=[];if(s?.[0].handlers.find(d.xL)&&!this.disableStreaming&&1===l.length&&this._streamResponseChunks!==p.prototype._streamResponseChunks)try{let e,r;for await(let a of(await this._streamResponseChunks(l[0],t,s?.[0]))){if(null==a.message.id){let e=s?.at(0)?.runId;null!=e&&a.message._updateId(`run-${e}`)}e=void 0===e?a:(0,u.xW)(e,a),(0,i.jm)(a.message)&&void 0!==a.message.usage_metadata&&(r={tokenUsage:{promptTokens:a.message.usage_metadata.input_tokens,completionTokens:a.message.usage_metadata.output_tokens,totalTokens:a.message.usage_metadata.total_tokens}})}if(void 0===e)throw Error("Received empty response from chat model call.");c.push([e]),await s?.[0].handleLLMEnd({generations:c,llmOutput:r})}catch(e){throw await s?.[0].handleLLMError(e),e}else{let e=await Promise.allSettled(l.map((e,r)=>this._generate(e,{...t,promptIndex:r},s?.[r])));await Promise.all(e.map(async(e,t)=>{if("fulfilled"!==e.status)return await s?.[t]?.handleLLMError(e.reason),Promise.reject(e.reason);{let r=e.value;for(let e of r.generations){if(null==e.message.id){let t=s?.at(0)?.runId;null!=t&&e.message._updateId(`run-${t}`)}e.message.response_metadata={...e.generationInfo,...e.message.response_metadata}}return 1===r.generations.length&&(r.generations[0].message.response_metadata={...r.llmOutput,...r.generations[0].message.response_metadata}),c[t]=r.generations,h[t]=r.llmOutput,s?.[t]?.handleLLMEnd({generations:[r.generations],llmOutput:r.llmOutput})}}))}let f={generations:c,llmOutput:h.length?this._combineLLMOutput?.(...h):void 0};return Object.defineProperty(f,n.SP,{value:s?{runIds:s?.map(e=>e.runId)}:void 0,configurable:!0}),f}async _generateCached({messages:e,cache:t,llmStringKey:r,parsedOptions:a,handledOptions:s}){let l=e.map(e=>e.map(i.K0)),u={...s.metadata,...this.getLsParams(a)},c=await o.Td.configure(s.callbacks,this.callbacks,s.tags,this.tags,u,this.metadata,{verbose:this.verbose}),h={options:a,invocation_params:this?.invocationParams(a),batch_size:1},d=await c?.handleChatModelStart(this.toJSON(),l,s.runId,void 0,h,void 0,void 0,s.runName),f=[],m=(await Promise.allSettled(l.map(async(e,a)=>{let i=p._convertInputToPromptValue(e).toString(),n=await t.lookup(i,r);return null==n&&f.push(a),n}))).map((e,t)=>({result:e,runManager:d?.[t]})).filter(({result:e})=>"fulfilled"===e.status&&null!=e.value||"rejected"===e.status),g=[];await Promise.all(m.map(async({result:e,runManager:t},r)=>{if("fulfilled"!==e.status)return await t?.handleLLMError(e.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(e.reason);{let a=e.value;return g[r]=a.map(e=>("message"in e&&(0,i.ny)(e.message)&&(0,i.KX)(e.message)&&(e.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0}),e.generationInfo={...e.generationInfo,tokenUsage:{}},e)),a.length&&await t?.handleLLMNewToken(a[0].text),t?.handleLLMEnd({generations:[a]},void 0,void 0,void 0,{cached:!0})}}));let y={generations:g,missingPromptIndices:f,startedRunManagers:d};return Object.defineProperty(y,n.SP,{value:d?{runIds:d?.map(e=>e.runId)}:void 0,configurable:!0}),y}async generate(e,t,r){let a;a=Array.isArray(t)?{stop:t}:t;let n=e.map(e=>e.map(i.K0)),[s,o]=this._separateRunnableConfigFromCallOptionsCompat(a);if(s.callbacks=s.callbacks??r,!this.cache)return this._generateUncached(n,o,s);let{cache:l}=this,u=this._getSerializedCacheKeyParametersForCall(o),{generations:c,missingPromptIndices:h,startedRunManagers:d}=await this._generateCached({messages:n,cache:l,llmStringKey:u,parsedOptions:o,handledOptions:s}),f={};if(h.length>0){let e=await this._generateUncached(h.map(e=>n[e]),o,s,void 0!==d?h.map(e=>d?.[e]):void 0);await Promise.all(e.generations.map(async(e,t)=>{let r=h[t];c[r]=e;let a=p._convertInputToPromptValue(n[r]).toString();return l.update(a,u,e)})),f=e.llmOutput??{}}return{generations:c,llmOutput:f}}invocationParams(e){return{}}_modelType(){return"base_chat_model"}serialize(){return{...this.invocationParams(),_type:this._llmType(),_model:this._modelType()}}async generatePrompt(e,t,r){let a=e.map(e=>e.toChatMessages());return this.generate(a,t,r)}async call(e,t,r){return(await this.generate([e.map(i.K0)],t,r)).generations[0][0].message}async callPrompt(e,t,r){let a=e.toChatMessages();return this.call(a,t,r)}async predictMessages(e,t,r){return this.call(e,t,r)}async predict(e,t,r){let a=new i.xc(e),n=await this.call([a],t,r);if("string"!=typeof n.content)throw Error("Cannot use predict when output is not a string.");return n.content}withStructuredOutput(e,t){let r;if("function"!=typeof this.bindTools)throw Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(t?.strict)throw Error('"strict" mode is not supported for this model by default.');let i=e,n=t?.name,s=i.description??"A function available to call.",o=t?.method,u=t?.includeRaw;if("jsonMode"===o)throw Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let d=n??"extract";(0,h.l)(i)?r=[{type:"function",function:{name:d,description:s,parameters:(0,a.Ik)(i)}}]:("name"in i&&(d=i.name),r=[{type:"function",function:{name:d,description:s,parameters:i}}]);let p=this.bindTools(r),f=l.jY.from(e=>{if(!e.tool_calls||0===e.tool_calls.length)throw Error("No tool calls found in the response.");let t=e.tool_calls.find(e=>e.name===d);if(!t)throw Error(`No tool call found with name ${d}.`);return t.args});if(!u)return p.pipe(f).withConfig({runName:"StructuredOutput"});let m=c.k.assign({parsed:(e,t)=>f.invoke(e.raw,t)}),g=c.k.assign({parsed:()=>null}),y=m.withFallbacks({fallbacks:[g]});return l.zZ.from([{raw:p},y]).withConfig({runName:"StructuredOutputRunnable"})}}class f extends p{async _generate(e,t,r){let a=await this._call(e,t,r),n=new i.Od(a);if("string"!=typeof n.content)throw Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:n.content,message:n}]}}}},46628:(e,t,r)=>{"use strict";r.d(t,{qG:()=>l}),r(50084);var a=r(4693),i=r(70240);function n(e){return void 0!==e&&Array.isArray(e.lc_namespace)}function s(e){return void 0!==e&&a.YN.isRunnable(e)&&"lc_name"in e.constructor&&"function"==typeof e.constructor.lc_name&&"RunnableToolLike"===e.constructor.lc_name()}function o(e){return!!e&&"object"==typeof e&&"name"in e&&"schema"in e&&(0,i.l)(e.schema)}function l(e){return o(e)||s(e)||n(e)}},48350:(e,t,r)=>{let a=r(34984),i=r(44726),n=r(28973),s=r(98344),o=r(23906),l=r(34817);e.exports=(e,t,r,u)=>{switch(t){case"===":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e===r;case"!==":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e!==r;case"":case"=":case"==":return a(e,r,u);case"!=":return i(e,r,u);case">":return n(e,r,u);case">=":return s(e,r,u);case"<":return o(e,r,u);case"<=":return l(e,r,u);default:throw TypeError(`Invalid operator: ${t}`)}}},50084:(e,t,r)=>{"use strict";r.d(t,{Ik:()=>ee});let a=Symbol("Let zodToJsonSchema decide on which parser to use"),i={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",emailStrategy:"format:email"},n=e=>"string"==typeof e?{...i,name:e}:{...i,...e};var s=r(55594);function o(){return{}}function l(e,t,r,a){a?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function u(e,t,r,a,i){e[t]=r,l(e,t,a,i)}function c(e,t){let r={type:"array"};return e.type?._def?.typeName!==s.kY.ZodAny&&(r.items=K(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&u(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&u(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(u(r,"minItems",e.exactLength.value,e.exactLength.message,t),u(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function h(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let a of e.checks)switch(a.kind){case"min":"jsonSchema7"===t.target?a.inclusive?u(r,"minimum",a.value,a.message,t):u(r,"exclusiveMinimum",a.value,a.message,t):(a.inclusive||(r.exclusiveMinimum=!0),u(r,"minimum",a.value,a.message,t));break;case"max":"jsonSchema7"===t.target?a.inclusive?u(r,"maximum",a.value,a.message,t):u(r,"exclusiveMaximum",a.value,a.message,t):(a.inclusive||(r.exclusiveMaximum=!0),u(r,"maximum",a.value,a.message,t));break;case"multipleOf":u(r,"multipleOf",a.value,a.message,t)}return r}function d(){return{type:"boolean"}}function p(e,t){return K(e.type._def,t)}let f=(e,t)=>K(e.innerType._def,t);function m(e,t,r){let a=r??t.dateStrategy;if(Array.isArray(a))return{anyOf:a.map((r,a)=>m(e,t,r))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return g(e,t)}}let g=(e,t)=>{let r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(let a of e.checks)switch(a.kind){case"min":u(r,"minimum",a.value,a.message,t);break;case"max":u(r,"maximum",a.value,a.message,t)}return r};function y(e,t){return{...K(e.innerType._def,t),default:e.defaultValue()}}function b(e,t){return"input"===t.effectStrategy?K(e.schema._def,t):{}}function _(e){return{type:"string",enum:e.values}}let w=e=>(!("type"in e)||"string"!==e.type)&&"allOf"in e;function v(e,t){let r=[K(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),K(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(e=>!!e),a="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0,i=[];return r.forEach(e=>{if(w(e))i.push(...e.allOf),void 0===e.unevaluatedProperties&&(a=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){let{additionalProperties:r,...a}=e;t=a}else a=void 0;i.push(t)}}),i.length?{allOf:i,...a}:void 0}function O(e,t){let r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}let E={cuid:"^[cC][^\\s-]{8,}$",cuid2:"^[a-z][a-z0-9]*$",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:"^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$"};function k(e,t){let r={type:"string"};function a(e){return"escape"===t.patternStrategy?x(e):e}if(e.checks)for(let i of e.checks)switch(i.kind){case"min":u(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,i.value):i.value,i.message,t);break;case"max":u(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,i.value):i.value,i.message,t);break;case"email":switch(t.emailStrategy){case"format:email":S(r,"email",i.message,t);break;case"format:idn-email":S(r,"idn-email",i.message,t);break;case"pattern:zod":A(r,E.email,i.message,t)}break;case"url":S(r,"uri",i.message,t);break;case"uuid":S(r,"uuid",i.message,t);break;case"regex":A(r,i.regex.source,i.message,t);break;case"cuid":A(r,E.cuid,i.message,t);break;case"cuid2":A(r,E.cuid2,i.message,t);break;case"startsWith":A(r,"^"+a(i.value),i.message,t);break;case"endsWith":A(r,a(i.value)+"$",i.message,t);break;case"datetime":S(r,"date-time",i.message,t);break;case"length":u(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,i.value):i.value,i.message,t),u(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,i.value):i.value,i.message,t);break;case"includes":A(r,a(i.value),i.message,t);break;case"ip":"v6"!==i.version&&S(r,"ipv4",i.message,t),"v4"!==i.version&&S(r,"ipv6",i.message,t);break;case"emoji":A(r,E.emoji,i.message,t);break;case"ulid":A(r,E.ulid,i.message,t);break;case"toLowerCase":case"toUpperCase":case"trim":break;default:(e=>{})(0)}return r}let x=e=>Array.from(e).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),S=(e,t,r,a)=>{e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&a.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&a.errorMessages&&{errorMessage:{format:r}}})):u(e,"format",t,r,a)},A=(e,t,r,a)=>{e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&a.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:t,...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):u(e,"pattern",t,r,a)};function P(e,t){if("openApi3"===t.target&&e.keyType?._def.typeName===s.kY.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,a)=>({...r,[a]:K(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",a]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:K(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===s.kY.ZodString&&e.keyType._def.checks?.length){let a=Object.entries(k(e.keyType._def,t)).reduce((e,[t,r])=>"type"===t?e:{...e,[t]:r},{});return{...r,propertyNames:a}}return e.keyType?._def.typeName===s.kY.ZodEnum?{...r,propertyNames:{enum:e.keyType._def.values}}:r}function T(e,t){return"record"===t.mapStrategy?P(e,t):{type:"array",maxItems:125,items:{type:"array",items:[K(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},K(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}function I(e){let t=e.values,r=Object.keys(e.values).filter(e=>"number"!=typeof t[t[e]]).map(e=>t[e]),a=Array.from(new Set(r.map(e=>typeof e)));return{type:1===a.length?"string"===a[0]?"string":"number":["string","number"],enum:r}}function N(){return{not:{}}}function j(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}let R={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function C(e,t){if("openApi3"===t.target)return $(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(e=>e._def.typeName in R&&(!e._def.checks||!e._def.checks.length))){let e=r.reduce((e,t)=>{let r=R[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e},[]);return{type:e.length>1?e:e[0]}}if(r.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){let e=r.reduce((e,t)=>{let r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===r.length){let t=e.filter((e,t,r)=>r.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:r.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(r.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:r.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return $(e,t)}let $=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>K(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0};function M(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:R[e.innerType._def.typeName],nullable:!0}:{type:[R[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){let r=K(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let r=K(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function L(e,t){let r={type:"number"};if(!e.checks)return r;for(let a of e.checks)switch(a.kind){case"int":r.type="integer",l(r,"type",a.message,t);break;case"min":"jsonSchema7"===t.target?a.inclusive?u(r,"minimum",a.value,a.message,t):u(r,"exclusiveMinimum",a.value,a.message,t):(a.inclusive||(r.exclusiveMinimum=!0),u(r,"minimum",a.value,a.message,t));break;case"max":"jsonSchema7"===t.target?a.inclusive?u(r,"maximum",a.value,a.message,t):u(r,"exclusiveMaximum",a.value,a.message,t):(a.inclusive||(r.exclusiveMaximum=!0),u(r,"maximum",a.value,a.message,t));break;case"multipleOf":u(r,"multipleOf",a.value,a.message,t)}return r}function U(e,t){return"strict"===t.removeAdditionalStrategy?"ZodNever"===e.catchall._def.typeName?"strict"!==e.unknownKeys:K(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0:"ZodNever"===e.catchall._def.typeName?"passthrough"===e.unknownKeys:K(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0}function D(e,t){let r={type:"object",...Object.entries(e.shape()).reduce((e,[r,a])=>{if(void 0===a||void 0===a._def)return e;let i=K(a._def,{...t,currentPath:[...t.currentPath,"properties",r],propertyPath:[...t.currentPath,"properties",r]});return void 0===i?e:{properties:{...e.properties,[r]:i},required:a.isOptional()?e.required:[...e.required,r]}},{properties:{},required:[]}),additionalProperties:U(e,t)};return r.required.length||delete r.required,r}let F=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return K(e.innerType._def,t);let r=K(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}},B=(e,t)=>{if("input"===t.pipeStrategy)return K(e.in._def,t);if("output"===t.pipeStrategy)return K(e.out._def,t);let r=K(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),a=K(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,a].filter(e=>void 0!==e)}};function z(e,t){return K(e.type._def,t)}function H(e,t){let r={type:"array",uniqueItems:!0,items:K(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&u(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&u(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function Z(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,r)=>K(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:K(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,r)=>K(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}function q(){return{not:{}}}function G(){return{}}let W=(e,t)=>K(e.innerType._def,t);function K(e,t,r=!1){let i=t.seen.get(e);if(t.override){let n=t.override?.(e,t,i,r);if(n!==a)return n}if(i&&!r){let e=J(i,t);if(void 0!==e)return e}let n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);let s=V(e,e.typeName,t);return s&&X(e,t,s),n.jsonSchema=s,s}let J=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Y(t.currentPath,e.path)};case"none":case"seen":if(e.path.lengtht.currentPath[r]===e))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{};return"seen"===t.$refStrategy?{}:void 0}},Y=(e,t)=>{let r=0;for(;r{switch(t){case s.kY.ZodString:return k(e,r);case s.kY.ZodNumber:return L(e,r);case s.kY.ZodObject:return D(e,r);case s.kY.ZodBigInt:return h(e,r);case s.kY.ZodBoolean:return d();case s.kY.ZodDate:return m(e,r);case s.kY.ZodUndefined:return q();case s.kY.ZodNull:return j(r);case s.kY.ZodArray:return c(e,r);case s.kY.ZodUnion:case s.kY.ZodDiscriminatedUnion:return C(e,r);case s.kY.ZodIntersection:return v(e,r);case s.kY.ZodTuple:return Z(e,r);case s.kY.ZodRecord:return P(e,r);case s.kY.ZodLiteral:return O(e,r);case s.kY.ZodEnum:return _(e);case s.kY.ZodNativeEnum:return I(e);case s.kY.ZodNullable:return M(e,r);case s.kY.ZodOptional:return F(e,r);case s.kY.ZodMap:return T(e,r);case s.kY.ZodSet:return H(e,r);case s.kY.ZodLazy:return K(e.getter()._def,r);case s.kY.ZodPromise:return z(e,r);case s.kY.ZodNaN:case s.kY.ZodNever:return N();case s.kY.ZodEffects:return b(e,r);case s.kY.ZodAny:return o();case s.kY.ZodUnknown:return G();case s.kY.ZodDefault:return y(e,r);case s.kY.ZodBranded:return p(e,r);case s.kY.ZodReadonly:return W(e,r);case s.kY.ZodCatch:return f(e,r);case s.kY.ZodPipeline:return B(e,r);case s.kY.ZodFunction:case s.kY.ZodVoid:case s.kY.ZodSymbol:return;default:let a;return void(a=0)}},X=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),Q=e=>{let t=n(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}},ee=(e,t)=>{let r=Q(t),a="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,a])=>({...e,[t]:K(a._def,{...r,currentPath:[...r.basePath,r.definitionPath,t]},!0)??{}}),{}):void 0,i="string"==typeof t?t:t?.name,n=K(e._def,void 0===i?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??{},s=void 0===i?a?{...n,[r.definitionPath]:a}:n:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...a,[i]:n}};return"jsonSchema7"===r.target?s.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"===r.target&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),s}},50113:(e,t,r)=>{let a=Symbol("SemVer ANY");class i{static get ANY(){return a}constructor(e,t){if(t=n(t),e instanceof i){if(!!t.loose===e.loose)return e;e=e.value}u("comparator",e=e.trim().split(/\s+/).join(" "),t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===a?this.value="":this.value=this.operator+this.semver.version,u("comp",this)}parse(e){let t=this.options.loose?s[o.COMPARATORLOOSE]:s[o.COMPARATOR],r=e.match(t);if(!r)throw TypeError(`Invalid comparator: ${e}`);this.operator=void 0!==r[1]?r[1]:"","="===this.operator&&(this.operator=""),r[2]?this.semver=new c(r[2],this.options.loose):this.semver=a}toString(){return this.value}test(e){if(u("Comparator.test",e,this.options.loose),this.semver===a||e===a)return!0;if("string"==typeof e)try{e=new c(e,this.options)}catch(e){return!1}return l(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof i))throw TypeError("a Comparator is required");return""===this.operator?""===this.value||new h(e.value,t).test(this.value):""===e.operator?""===e.value||new h(this.value,t).test(e.semver):!((t=n(t)).includePrerelease&&("<0.0.0-0"===this.value||"<0.0.0-0"===e.value)||!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0")))&&!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||l(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||l(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">"))}}e.exports=i;let n=r(32002),{safeRe:s,t:o}=r(56655),l=r(48350),u=r(57265),c=r(36053),h=r(42870)},51362:(e,t,r)=>{"use strict";r.d(t,{D:()=>u,N:()=>c});var a=r(12115),i=["light","dark"],n="(prefers-color-scheme: dark)",s=!1,o=a.createContext(void 0),l={setTheme:e=>{},themes:[]},u=()=>{var e;return null!=(e=a.useContext(o))?e:l},c=e=>a.useContext(o)?e.children:a.createElement(d,{...e}),h=["light","dark"],d=e=>{let{forcedTheme:t,disableTransitionOnChange:r=!1,enableSystem:s=!0,enableColorScheme:l=!0,storageKey:u="theme",themes:c=h,defaultTheme:d=s?"system":"light",attribute:y="data-theme",value:b,children:_,nonce:w}=e,[v,O]=a.useState(()=>f(u,d)),[E,k]=a.useState(()=>f(u)),x=b?Object.values(b):c,S=a.useCallback(e=>{let t=e;if(!t)return;"system"===e&&s&&(t=g());let a=b?b[t]:t,n=r?m():null,o=document.documentElement;if("class"===y?(o.classList.remove(...x),a&&o.classList.add(a)):a?o.setAttribute(y,a):o.removeAttribute(y),l){let e=i.includes(d)?d:null,r=i.includes(t)?t:e;o.style.colorScheme=r}null==n||n()},[]),A=a.useCallback(e=>{let t="function"==typeof e?e(e):e;O(t);try{localStorage.setItem(u,t)}catch(e){}},[t]),P=a.useCallback(e=>{k(g(e)),"system"===v&&s&&!t&&S("system")},[v,t]);a.useEffect(()=>{let e=window.matchMedia(n);return e.addListener(P),P(e),()=>e.removeListener(P)},[P]),a.useEffect(()=>{let e=e=>{e.key===u&&A(e.newValue||d)};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[A]),a.useEffect(()=>{S(null!=t?t:v)},[t,v]);let T=a.useMemo(()=>({theme:v,setTheme:A,forcedTheme:t,resolvedTheme:"system"===v?E:v,themes:s?[...c,"system"]:c,systemTheme:s?E:void 0}),[v,A,t,E,s,c]);return a.createElement(o.Provider,{value:T},a.createElement(p,{forcedTheme:t,disableTransitionOnChange:r,enableSystem:s,enableColorScheme:l,storageKey:u,themes:c,defaultTheme:d,attribute:y,value:b,children:_,attrs:x,nonce:w}),_)},p=a.memo(e=>{let{forcedTheme:t,storageKey:r,attribute:s,enableSystem:o,enableColorScheme:l,defaultTheme:u,value:c,attrs:h,nonce:d}=e,p="system"===u,f="class"===s?"var d=document.documentElement,c=d.classList;".concat("c.remove(".concat(h.map(e=>"'".concat(e,"'")).join(","),")"),";"):"var d=document.documentElement,n='".concat(s,"',s='setAttribute';"),m=l?(i.includes(u)?u:null)?"if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'".concat(u,"'"):"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=!(arguments.length>2)||void 0===arguments[2]||arguments[2],a=c?c[e]:e,n=t?e+"|| ''":"'".concat(a,"'"),o="";return l&&r&&!t&&i.includes(e)&&(o+="d.style.colorScheme = '".concat(e,"';")),"class"===s?t||a?o+="c.add(".concat(n,")"):o+="null":a&&(o+="d[s](n,".concat(n,")")),o},y=t?"!function(){".concat(f).concat(g(t),"}()"):o?"!function(){try{".concat(f,"var e=localStorage.getItem('").concat(r,"');if('system'===e||(!e&&").concat(p,")){var t='").concat(n,"',m=window.matchMedia(t);if(m.media!==t||m.matches){").concat(g("dark"),"}else{").concat(g("light"),"}}else if(e){").concat(c?"var x=".concat(JSON.stringify(c),";"):"").concat(g(c?"x[e]":"e",!0),"}").concat(p?"":"else{"+g(u,!1,!1)+"}").concat(m,"}catch(e){}}()"):"!function(){try{".concat(f,"var e=localStorage.getItem('").concat(r,"');if(e){").concat(c?"var x=".concat(JSON.stringify(c),";"):"").concat(g(c?"x[e]":"e",!0),"}else{").concat(g(u,!1,!1),";}").concat(m,"}catch(t){}}();");return a.createElement("script",{nonce:d,dangerouslySetInnerHTML:{__html:y}})}),f=(e,t)=>{let r;if(!s){try{r=localStorage.getItem(e)||void 0}catch(e){}return r||t}},m=()=>{let e=document.createElement("style");return e.appendChild(document.createTextNode("*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}")),document.head.appendChild(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},g=e=>(e||(e=window.matchMedia(n)),e.matches?"dark":"light")},52435:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});let a=r(82661),i=r(46520),n=r(64951),s=()=>{},o=new i.TimeoutError;class l extends a{constructor(e){var t,r,a,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=s,this._resolveIdle=s,!("number"==typeof(e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:n.default},e)).intervalCap&&e.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!==(r=null===(t=e.intervalCap)||void 0===t?void 0:t.toString())&&void 0!==r?r:""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!==(i=null===(a=e.interval)||void 0===a?void 0:a.toString())&&void 0!==i?i:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||0===e.interval,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=!0===e.throwOnTimeout,this._isPaused=!1===e.autoStart}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount{this._onResumeInterval()},t)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}_tryToStartAnother(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let t=this._queue.dequeue();return!!t&&(this.emit("active"),t(),e&&this._initializeIntervalIfNeeded(),!0)}}return!1}_initializeIntervalIfNeeded(){!this._isIntervalIgnored&&void 0===this._intervalId&&(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){0===this._intervalCount&&0===this._pendingCount&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!("number"==typeof e&&e>=1))throw TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={}){return new Promise((r,a)=>{let n=async()=>{this._pendingCount++,this._intervalCount++;try{let n=void 0===this._timeout&&void 0===t.timeout?e():i.default(Promise.resolve(e()),void 0===t.timeout?this._timeout:t.timeout,()=>{(void 0===t.throwOnTimeout?this._throwOnTimeout:t.throwOnTimeout)&&a(o)});r(await n)}catch(e){a(e)}this._next()};this._queue.enqueue(n,t),this._tryToStartAnother(),this.emit("add")})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return this._isPaused&&(this._isPaused=!1,this._processQueue()),this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(0!==this._queue.size)return new Promise(e=>{let t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}})}async onIdle(){if(0!==this._pendingCount||0!==this._queue.size)return new Promise(e=>{let t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}}t.default=l},52813:(e,t,r)=>{"use strict";let a=r(84896),i=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class n extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}let s=(e,t,r)=>{let a=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=a,e},o=e=>i.includes(e),l=(e,t)=>new Promise((r,i)=>{t={onFailedAttempt:()=>{},retries:10,...t};let l=a.operation(t);l.attempt(async a=>{try{r(await e(a))}catch(e){if(!(e instanceof Error)){i(TypeError(`Non-error was thrown: "${e}". You should only throw errors.`));return}if(e instanceof n)l.stop(),i(e.originalError);else if(e instanceof TypeError&&!o(e.message))l.stop(),i(e);else{s(e,a,t);try{await t.onFailedAttempt(e)}catch(e){i(e);return}l.retry(e)||i(l.mainError())}}})});e.exports=l,e.exports.default=l,e.exports.AbortError=n},53210:(e,t,r)=>{"use strict";e.exports=n;let a=r(87096),i=r(11813);function n(e,t){t||(t={});let r=0,n=t.blocksize||40960,s=new a;return new Promise((e,t)=>{setImmediate(o,r,n,e,t)});function o(t,r,a,n){if(t>=e.length)try{return a(s.finish())}catch(t){return n(i(t,e))}try{s.parse(e.slice(t,t+r)),setImmediate(o,t+r,r,a,n)}catch(t){n(i(t,e))}}}},53909:(e,t,r)=>{"use strict";r.d(t,{Kj:()=>a.Kj,Ls:()=>n,gk:()=>i.gk});var a=r(13196),i=r(11259);r(25822);let n="0.3.14"},55165:(e,t,r)=>{"use strict";r.d(t,{m:()=>i});let a={};function i(e){a[e]||(console.warn(e),a[e]=!0)}},55594:(e,t,r)=>{"use strict";let a;r.d(t,{Ii:()=>ey,kY:()=>ts,z:()=>to}),function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw Error()},e.arrayToEnum=e=>{let t={};for(let r of e)t[r]=r;return t},e.getValidEnumValues=t=>{let r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),a={};for(let e of r)a[e]=t[e];return e.objectValues(a)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{let t=[];for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(let r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(ta||(ta={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(ti||(ti={}));let i=ta.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),n=e=>{switch(typeof e){case"undefined":return i.undefined;case"string":return i.string;case"number":return isNaN(e)?i.nan:i.number;case"boolean":return i.boolean;case"function":return i.function;case"bigint":return i.bigint;case"symbol":return i.symbol;case"object":if(Array.isArray(e))return i.array;if(null===e)return i.null;if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return i.promise;if("undefined"!=typeof Map&&e instanceof Map)return i.map;if("undefined"!=typeof Set&&e instanceof Set)return i.set;if("undefined"!=typeof Date&&e instanceof Date)return i.date;return i.object;default:return i.unknown}},s=ta.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"]),o=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class l extends Error{constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){let t=e||function(e){return e.message},r={_errors:[]},a=e=>{for(let i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(a);else if("invalid_return_type"===i.code)a(i.returnTypeError);else if("invalid_arguments"===i.code)a(i.argumentsError);else if(0===i.path.length)r._errors.push(t(i));else{let e=r,a=0;for(;ae.message){let t={},r=[];for(let a of this.issues)a.path.length>0?(t[a.path[0]]=t[a.path[0]]||[],t[a.path[0]].push(e(a))):r.push(e(a));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}l.create=e=>new l(e);let u=(e,t)=>{let r;switch(e.code){case s.invalid_type:r=e.received===i.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case s.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,ta.jsonStringifyReplacer)}`;break;case s.unrecognized_keys:r=`Unrecognized key(s) in object: ${ta.joinValues(e.keys,", ")}`;break;case s.invalid_union:r="Invalid input";break;case s.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ta.joinValues(e.options)}`;break;case s.invalid_enum_value:r=`Invalid enum value. Expected ${ta.joinValues(e.options)}, received '${e.received}'`;break;case s.invalid_arguments:r="Invalid function arguments";break;case s.invalid_return_type:r="Invalid function return type";break;case s.invalid_date:r="Invalid date";break;case s.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:ta.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case s.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case s.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case s.custom:r="Invalid input";break;case s.invalid_intersection_types:r="Intersection results could not be merged";break;case s.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case s.not_finite:r="Number must be finite";break;default:r=t.defaultError,ta.assertNever(e)}return{message:r}},c=u;function h(e){c=e}function d(){return c}let p=e=>{let{data:t,path:r,errorMaps:a,issueData:i}=e,n=[...r,...i.path||[]],s={...i,path:n},o="";for(let e of a.filter(e=>!!e).slice().reverse())o=e(s,{data:t,defaultError:o}).message;return{...i,path:n,message:i.message||o}},f=[];function m(e,t){let r=p({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,d(),u].filter(e=>!!e)});e.common.issues.push(r)}class g{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let a of t){if("aborted"===a.status)return y;"dirty"===a.status&&e.dirty(),r.push(a.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let e of t)r.push({key:await e.key,value:await e.value});return g.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let a of t){let{key:t,value:i}=a;if("aborted"===t.status||"aborted"===i.status)return y;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"!==t.value&&(void 0!==i.value||a.alwaysSet)&&(r[t.value]=i.value)}return{status:e.value,value:r}}}let y=Object.freeze({status:"aborted"}),b=e=>({status:"dirty",value:e}),_=e=>({status:"valid",value:e}),w=e=>"aborted"===e.status,v=e=>"dirty"===e.status,O=e=>"valid"===e.status,E=e=>"undefined"!=typeof Promise&&e instanceof Promise;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(tn||(tn={}));class k{constructor(e,t,r,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=a}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}let x=(e,t)=>{if(O(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new l(e.common.issues);return this._error=t,this._error}}};function S(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:a,description:i}=e;if(t&&(r||a))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:i}:{errorMap:(e,t)=>"invalid_type"!==e.code?{message:t.defaultError}:void 0===t.data?{message:null!=a?a:t.defaultError}:{message:null!=r?r:t.defaultError},description:i}}class A{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)}get description(){return this._def.description}_getType(e){return n(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:n(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new g,ctx:{common:e.parent.common,data:e.data,parsedType:n(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(E(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){return Promise.resolve(this._parse(e))}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;let a={common:{issues:[],async:null!==(r=null==t?void 0:t.async)&&void 0!==r&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:n(e)},i=this._parseSync({data:e,path:a.path,parent:a});return x(a,i)}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:n(e)},a=this._parse({data:e,path:r.path,parent:r});return x(r,await (E(a)?a:Promise.resolve(a)))}refine(e,t){let r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,a)=>{let i=e(t),n=()=>a.addIssue({code:s.custom,...r(t)});return"undefined"!=typeof Promise&&i instanceof Promise?i.then(e=>!!e||(n(),!1)):!!i||(n(),!1)})}refinement(e,t){return this._refinement((r,a)=>!!e(r)||(a.addIssue("function"==typeof t?t(r,a):t),!1))}_refinement(e){return new eg({schema:this,typeName:ts.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return ey.create(this,this._def)}nullable(){return eb.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return V.create(this,this._def)}promise(){return em.create(this,this._def)}or(e){return ee.create([this,e],this._def)}and(e){return ei.create(this,e,this._def)}transform(e){return new eg({...S(this._def),schema:this,typeName:ts.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t="function"==typeof e?e:()=>e;return new e_({...S(this._def),innerType:this,defaultValue:t,typeName:ts.ZodDefault})}brand(){return new eE({typeName:ts.ZodBranded,type:this,...S(this._def)})}catch(e){let t="function"==typeof e?e:()=>e;return new ew({...S(this._def),innerType:this,catchValue:t,typeName:ts.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return ek.create(this,e)}readonly(){return ex.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let P=/^c[^\s-]{8,}$/i,T=/^[a-z][a-z0-9]*$/,I=/^[0-9A-HJKMNP-TV-Z]{26}$/,N=/^[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,j=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,R="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",C=/^(((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}))$/,$=/^(([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})))$/,M=e=>e.precision?e.offset?RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}Z$`):0===e.precision?e.offset?RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):e.offset?RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function L(e,t){return!!(("v4"===t||!t)&&C.test(e)||("v6"===t||!t)&&$.test(e))}class U extends A{_parse(e){let t;if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==i.string){let t=this._getOrReturnCtx(e);return m(t,{code:s.invalid_type,expected:i.string,received:t.parsedType}),y}let r=new g;for(let i of this._def.checks)if("min"===i.kind)e.data.lengthi.value&&(m(t=this._getOrReturnCtx(e,t),{code:s.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if("length"===i.kind){let a=e.data.length>i.value,n=e.data.lengthe.test(t),{validation:t,code:s.invalid_string,...tn.errToObj(r)})}_addCheck(e){return new U({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...tn.errToObj(e)})}url(e){return this._addCheck({kind:"url",...tn.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...tn.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...tn.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...tn.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...tn.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...tn.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...tn.errToObj(e)})}datetime(e){var t;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,...tn.errToObj(null==e?void 0:e.message)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...tn.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...tn.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...tn.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...tn.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...tn.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...tn.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...tn.errToObj(t)})}nonempty(e){return this.min(1,tn.errToObj(e))}trim(){return new U({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new U({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new U({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get minLength(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.valuea?r:a;return parseInt(e.toFixed(i).replace(".",""))%parseInt(t.toFixed(i).replace(".",""))/Math.pow(10,i)}U.create=e=>{var t;return new U({checks:[],typeName:ts.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...S(e)})};class F extends A{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){let t;if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==i.number){let t=this._getOrReturnCtx(e);return m(t,{code:s.invalid_type,expected:i.number,received:t.parsedType}),y}let r=new g;for(let a of this._def.checks)"int"===a.kind?ta.isInteger(e.data)||(m(t=this._getOrReturnCtx(e,t),{code:s.invalid_type,expected:"integer",received:"float",message:a.message}),r.dirty()):"min"===a.kind?(a.inclusive?e.dataa.value:e.data>=a.value)&&(m(t=this._getOrReturnCtx(e,t),{code:s.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty()):"multipleOf"===a.kind?0!==D(e.data,a.value)&&(m(t=this._getOrReturnCtx(e,t),{code:s.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):"finite"===a.kind?Number.isFinite(e.data)||(m(t=this._getOrReturnCtx(e,t),{code:s.not_finite,message:a.message}),r.dirty()):ta.assertNever(a);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,tn.toString(t))}gt(e,t){return this.setLimit("min",e,!1,tn.toString(t))}lte(e,t){return this.setLimit("max",e,!0,tn.toString(t))}lt(e,t){return this.setLimit("max",e,!1,tn.toString(t))}setLimit(e,t,r,a){return new F({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:tn.toString(a)}]})}_addCheck(e){return new F({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:tn.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:tn.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:tn.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:tn.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:tn.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:tn.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:tn.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:tn.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:tn.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value"int"===e.kind||"multipleOf"===e.kind&&ta.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.valuenew F({checks:[],typeName:ts.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...S(e)});class B extends A{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){let t;if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==i.bigint){let t=this._getOrReturnCtx(e);return m(t,{code:s.invalid_type,expected:i.bigint,received:t.parsedType}),y}let r=new g;for(let a of this._def.checks)"min"===a.kind?(a.inclusive?e.dataa.value:e.data>=a.value)&&(m(t=this._getOrReturnCtx(e,t),{code:s.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty()):"multipleOf"===a.kind?e.data%a.value!==BigInt(0)&&(m(t=this._getOrReturnCtx(e,t),{code:s.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):ta.assertNever(a);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,tn.toString(t))}gt(e,t){return this.setLimit("min",e,!1,tn.toString(t))}lte(e,t){return this.setLimit("max",e,!0,tn.toString(t))}lt(e,t){return this.setLimit("max",e,!1,tn.toString(t))}setLimit(e,t,r,a){return new B({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:tn.toString(a)}]})}_addCheck(e){return new B({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:tn.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:tn.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:tn.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:tn.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:tn.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value{var t;return new B({checks:[],typeName:ts.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...S(e)})};class z extends A{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==i.boolean){let t=this._getOrReturnCtx(e);return m(t,{code:s.invalid_type,expected:i.boolean,received:t.parsedType}),y}return _(e.data)}}z.create=e=>new z({typeName:ts.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...S(e)});class H extends A{_parse(e){let t;if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==i.date){let t=this._getOrReturnCtx(e);return m(t,{code:s.invalid_type,expected:i.date,received:t.parsedType}),y}if(isNaN(e.data.getTime()))return m(this._getOrReturnCtx(e),{code:s.invalid_date}),y;let r=new g;for(let a of this._def.checks)"min"===a.kind?e.data.getTime()a.value&&(m(t=this._getOrReturnCtx(e,t),{code:s.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),r.dirty()):ta.assertNever(a);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new H({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:tn.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:tn.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.valuenew H({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:ts.ZodDate,...S(e)});class Z extends A{_parse(e){if(this._getType(e)!==i.symbol){let t=this._getOrReturnCtx(e);return m(t,{code:s.invalid_type,expected:i.symbol,received:t.parsedType}),y}return _(e.data)}}Z.create=e=>new Z({typeName:ts.ZodSymbol,...S(e)});class q extends A{_parse(e){if(this._getType(e)!==i.undefined){let t=this._getOrReturnCtx(e);return m(t,{code:s.invalid_type,expected:i.undefined,received:t.parsedType}),y}return _(e.data)}}q.create=e=>new q({typeName:ts.ZodUndefined,...S(e)});class G extends A{_parse(e){if(this._getType(e)!==i.null){let t=this._getOrReturnCtx(e);return m(t,{code:s.invalid_type,expected:i.null,received:t.parsedType}),y}return _(e.data)}}G.create=e=>new G({typeName:ts.ZodNull,...S(e)});class W extends A{constructor(){super(...arguments),this._any=!0}_parse(e){return _(e.data)}}W.create=e=>new W({typeName:ts.ZodAny,...S(e)});class K extends A{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _(e.data)}}K.create=e=>new K({typeName:ts.ZodUnknown,...S(e)});class J extends A{_parse(e){let t=this._getOrReturnCtx(e);return m(t,{code:s.invalid_type,expected:i.never,received:t.parsedType}),y}}J.create=e=>new J({typeName:ts.ZodNever,...S(e)});class Y extends A{_parse(e){if(this._getType(e)!==i.undefined){let t=this._getOrReturnCtx(e);return m(t,{code:s.invalid_type,expected:i.void,received:t.parsedType}),y}return _(e.data)}}Y.create=e=>new Y({typeName:ts.ZodVoid,...S(e)});class V extends A{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),a=this._def;if(t.parsedType!==i.array)return m(t,{code:s.invalid_type,expected:i.array,received:t.parsedType}),y;if(null!==a.exactLength){let e=t.data.length>a.exactLength.value,i=t.data.lengtha.maxLength.value&&(m(t,{code:s.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>a.type._parseAsync(new k(t,e,t.path,r)))).then(e=>g.mergeArray(r,e));let n=[...t.data].map((e,r)=>a.type._parseSync(new k(t,e,t.path,r)));return g.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new V({...this._def,minLength:{value:e,message:tn.toString(t)}})}max(e,t){return new V({...this._def,maxLength:{value:e,message:tn.toString(t)}})}length(e,t){return new V({...this._def,exactLength:{value:e,message:tn.toString(t)}})}nonempty(e){return this.min(1,e)}}function X(e){if(e instanceof Q){let t={};for(let r in e.shape){let a=e.shape[r];t[r]=ey.create(X(a))}return new Q({...e._def,shape:()=>t})}if(e instanceof V)return new V({...e._def,type:X(e.element)});if(e instanceof ey)return ey.create(X(e.unwrap()));if(e instanceof eb)return eb.create(X(e.unwrap()));if(e instanceof en)return en.create(e.items.map(e=>X(e)));else return e}V.create=(e,t)=>new V({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ts.ZodArray,...S(t)});class Q extends A{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let e=this._def.shape(),t=ta.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==i.object){let t=this._getOrReturnCtx(e);return m(t,{code:s.invalid_type,expected:i.object,received:t.parsedType}),y}let{status:t,ctx:r}=this._processInputParams(e),{shape:a,keys:n}=this._getCached(),o=[];if(!(this._def.catchall instanceof J&&"strip"===this._def.unknownKeys))for(let e in r.data)n.includes(e)||o.push(e);let l=[];for(let e of n){let t=a[e],i=r.data[e];l.push({key:{status:"valid",value:e},value:t._parse(new k(r,i,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof J){let e=this._def.unknownKeys;if("passthrough"===e)for(let e of o)l.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)o.length>0&&(m(r,{code:s.unrecognized_keys,keys:o}),t.dirty());else if("strip"===e);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let e=this._def.catchall;for(let t of o){let a=r.data[t];l.push({key:{status:"valid",value:t},value:e._parse(new k(r,a,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of l){let r=await t.key;e.push({key:r,value:await t.value,alwaysSet:t.alwaysSet})}return e}).then(e=>g.mergeObjectSync(t,e)):g.mergeObjectSync(t,l)}get shape(){return this._def.shape()}strict(e){return tn.errToObj,new Q({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var a,i,n,s;let o=null!==(n=null===(i=(a=this._def).errorMap)||void 0===i?void 0:i.call(a,t,r).message)&&void 0!==n?n:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(s=tn.errToObj(e).message)&&void 0!==s?s:o}:{message:o}}}:{}})}strip(){return new Q({...this._def,unknownKeys:"strip"})}passthrough(){return new Q({...this._def,unknownKeys:"passthrough"})}extend(e){return new Q({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Q({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ts.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Q({...this._def,catchall:e})}pick(e){let t={};return ta.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])}),new Q({...this._def,shape:()=>t})}omit(e){let t={};return ta.objectKeys(this.shape).forEach(r=>{e[r]||(t[r]=this.shape[r])}),new Q({...this._def,shape:()=>t})}deepPartial(){return X(this)}partial(e){let t={};return ta.objectKeys(this.shape).forEach(r=>{let a=this.shape[r];e&&!e[r]?t[r]=a:t[r]=a.optional()}),new Q({...this._def,shape:()=>t})}required(e){let t={};return ta.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof ey;)e=e._def.innerType;t[r]=e}}),new Q({...this._def,shape:()=>t})}keyof(){return ed(ta.objectKeys(this.shape))}}Q.create=(e,t)=>new Q({shape:()=>e,unknownKeys:"strip",catchall:J.create(),typeName:ts.ZodObject,...S(t)}),Q.strictCreate=(e,t)=>new Q({shape:()=>e,unknownKeys:"strict",catchall:J.create(),typeName:ts.ZodObject,...S(t)}),Q.lazycreate=(e,t)=>new Q({shape:e,unknownKeys:"strip",catchall:J.create(),typeName:ts.ZodObject,...S(t)});class ee extends A{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function a(e){for(let t of e)if("valid"===t.result.status)return t.result;for(let r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;let r=e.map(e=>new l(e.ctx.common.issues));return m(t,{code:s.invalid_union,unionErrors:r}),y}if(t.common.async)return Promise.all(r.map(async e=>{let r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(a);{let e;let a=[];for(let i of r){let r={...t,common:{...t.common,issues:[]},parent:null},n=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===n.status)return n;"dirty"!==n.status||e||(e={result:n,ctx:r}),r.common.issues.length&&a.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=a.map(e=>new l(e));return m(t,{code:s.invalid_union,unionErrors:i}),y}}get options(){return this._def.options}}ee.create=(e,t)=>new ee({options:e,typeName:ts.ZodUnion,...S(t)});let et=e=>{if(e instanceof ec)return et(e.schema);if(e instanceof eg)return et(e.innerType());if(e instanceof eh)return[e.value];if(e instanceof ep)return e.options;if(e instanceof ef)return Object.keys(e.enum);else if(e instanceof e_)return et(e._def.innerType);else if(e instanceof q)return[void 0];else if(e instanceof G)return[null];else return null};class er extends A{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==i.object)return m(t,{code:s.invalid_type,expected:i.object,received:t.parsedType}),y;let r=this.discriminator,a=t.data[r],n=this.optionsMap.get(a);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(m(t,{code:s.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),y)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let a=new Map;for(let r of t){let t=et(r.shape[e]);if(!t)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of t){if(a.has(i))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);a.set(i,r)}}return new er({typeName:ts.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...S(r)})}}function ea(e,t){let r=n(e),a=n(t);if(e===t)return{valid:!0,data:e};if(r===i.object&&a===i.object){let r=ta.objectKeys(t),a=ta.objectKeys(e).filter(e=>-1!==r.indexOf(e)),i={...e,...t};for(let r of a){let a=ea(e[r],t[r]);if(!a.valid)return{valid:!1};i[r]=a.data}return{valid:!0,data:i}}if(r===i.array&&a===i.array){if(e.length!==t.length)return{valid:!1};let r=[];for(let a=0;a{if(w(e)||w(a))return y;let i=ea(e.value,a.value);return i.valid?((v(e)||v(a))&&t.dirty(),{status:t.value,value:i.data}):(m(r,{code:s.invalid_intersection_types}),y)};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(([e,t])=>a(e,t)):a(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}ei.create=(e,t,r)=>new ei({left:e,right:t,typeName:ts.ZodIntersection,...S(r)});class en extends A{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.array)return m(r,{code:s.invalid_type,expected:i.array,received:r.parsedType}),y;if(r.data.lengththis._def.items.length&&(m(r,{code:s.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...r.data].map((e,t)=>{let a=this._def.items[t]||this._def.rest;return a?a._parse(new k(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(a).then(e=>g.mergeArray(t,e)):g.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new en({...this._def,rest:e})}}en.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new en({items:e,typeName:ts.ZodTuple,rest:null,...S(t)})};class es extends A{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.object)return m(r,{code:s.invalid_type,expected:i.object,received:r.parsedType}),y;let a=[],n=this._def.keyType,o=this._def.valueType;for(let e in r.data)a.push({key:n._parse(new k(r,e,r.path,e)),value:o._parse(new k(r,r.data[e],r.path,e))});return r.common.async?g.mergeObjectAsync(t,a):g.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,r){return new es(t instanceof A?{keyType:e,valueType:t,typeName:ts.ZodRecord,...S(r)}:{keyType:U.create(),valueType:e,typeName:ts.ZodRecord,...S(t)})}}class eo extends A{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.map)return m(r,{code:s.invalid_type,expected:i.map,received:r.parsedType}),y;let a=this._def.keyType,n=this._def.valueType,o=[...r.data.entries()].map(([e,t],i)=>({key:a._parse(new k(r,e,r.path,[i,"key"])),value:n._parse(new k(r,t,r.path,[i,"value"]))}));if(r.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let r of o){let a=await r.key,i=await r.value;if("aborted"===a.status||"aborted"===i.status)return y;("dirty"===a.status||"dirty"===i.status)&&t.dirty(),e.set(a.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let r of o){let a=r.key,i=r.value;if("aborted"===a.status||"aborted"===i.status)return y;("dirty"===a.status||"dirty"===i.status)&&t.dirty(),e.set(a.value,i.value)}return{status:t.value,value:e}}}}eo.create=(e,t,r)=>new eo({valueType:t,keyType:e,typeName:ts.ZodMap,...S(r)});class el extends A{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.set)return m(r,{code:s.invalid_type,expected:i.set,received:r.parsedType}),y;let a=this._def;null!==a.minSize&&r.data.sizea.maxSize.value&&(m(r,{code:s.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());let n=this._def.valueType;function o(e){let r=new Set;for(let a of e){if("aborted"===a.status)return y;"dirty"===a.status&&t.dirty(),r.add(a.value)}return{status:t.value,value:r}}let l=[...r.data.values()].map((e,t)=>n._parse(new k(r,e,r.path,t)));return r.common.async?Promise.all(l).then(e=>o(e)):o(l)}min(e,t){return new el({...this._def,minSize:{value:e,message:tn.toString(t)}})}max(e,t){return new el({...this._def,maxSize:{value:e,message:tn.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}el.create=(e,t)=>new el({valueType:e,minSize:null,maxSize:null,typeName:ts.ZodSet,...S(t)});class eu extends A{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==i.function)return m(t,{code:s.invalid_type,expected:i.function,received:t.parsedType}),y;function r(e,r){return p({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,d(),u].filter(e=>!!e),issueData:{code:s.invalid_arguments,argumentsError:r}})}function a(e,r){return p({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,d(),u].filter(e=>!!e),issueData:{code:s.invalid_return_type,returnTypeError:r}})}let n={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof em){let e=this;return _(async function(...t){let i=new l([]),s=await e._def.args.parseAsync(t,n).catch(e=>{throw i.addIssue(r(t,e)),i}),u=await Reflect.apply(o,this,s);return await e._def.returns._def.type.parseAsync(u,n).catch(e=>{throw i.addIssue(a(u,e)),i})})}{let e=this;return _(function(...t){let i=e._def.args.safeParse(t,n);if(!i.success)throw new l([r(t,i.error)]);let s=Reflect.apply(o,this,i.data),u=e._def.returns.safeParse(s,n);if(!u.success)throw new l([a(s,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new eu({...this._def,args:en.create(e).rest(K.create())})}returns(e){return new eu({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new eu({args:e||en.create([]).rest(K.create()),returns:t||K.create(),typeName:ts.ZodFunction,...S(r)})}}class ec extends A{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ec.create=(e,t)=>new ec({getter:e,typeName:ts.ZodLazy,...S(t)});class eh extends A{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return m(t,{received:t.data,code:s.invalid_literal,expected:this._def.value}),y}return{status:"valid",value:e.data}}get value(){return this._def.value}}function ed(e,t){return new ep({values:e,typeName:ts.ZodEnum,...S(t)})}eh.create=(e,t)=>new eh({value:e,typeName:ts.ZodLiteral,...S(t)});class ep extends A{_parse(e){if("string"!=typeof e.data){let t=this._getOrReturnCtx(e),r=this._def.values;return m(t,{expected:ta.joinValues(r),received:t.parsedType,code:s.invalid_type}),y}if(-1===this._def.values.indexOf(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return m(t,{received:t.data,code:s.invalid_enum_value,options:r}),y}return _(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e){return ep.create(e)}exclude(e){return ep.create(this.options.filter(t=>!e.includes(t)))}}ep.create=ed;class ef extends A{_parse(e){let t=ta.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==i.string&&r.parsedType!==i.number){let e=ta.objectValues(t);return m(r,{expected:ta.joinValues(e),received:r.parsedType,code:s.invalid_type}),y}if(-1===t.indexOf(e.data)){let e=ta.objectValues(t);return m(r,{received:r.data,code:s.invalid_enum_value,options:e}),y}return _(e.data)}get enum(){return this._def.values}}ef.create=(e,t)=>new ef({values:e,typeName:ts.ZodNativeEnum,...S(t)});class em extends A{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==i.promise&&!1===t.common.async?(m(t,{code:s.invalid_type,expected:i.promise,received:t.parsedType}),y):_((t.parsedType===i.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}em.create=(e,t)=>new em({type:e,typeName:ts.ZodPromise,...S(t)});class eg extends A{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ts.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),a=this._def.effect||null,i={addIssue:e=>{m(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===a.type){let e=a.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(e).then(e=>this._def.schema._parseAsync({data:e,path:r.path,parent:r})):this._def.schema._parseSync({data:e,path:r.path,parent:r})}if("refinement"===a.type){let e=e=>{let t=a.refinement(e,i);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?y:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))));{let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===a.status?y:("dirty"===a.status&&t.dirty(),e(a.value),{status:t.value,value:a.value})}}if("transform"===a.type){if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>O(e)?Promise.resolve(a.transform(e.value,i)).then(e=>({status:t.value,value:e})):e);{let e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!O(e))return e;let n=a.transform(e.value,i);if(n instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:n}}}ta.assertNever(a)}}eg.create=(e,t,r)=>new eg({schema:e,typeName:ts.ZodEffects,effect:t,...S(r)}),eg.createWithPreprocess=(e,t,r)=>new eg({schema:t,effect:{type:"preprocess",transform:e},typeName:ts.ZodEffects,...S(r)});class ey extends A{_parse(e){return this._getType(e)===i.undefined?_(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ey.create=(e,t)=>new ey({innerType:e,typeName:ts.ZodOptional,...S(t)});class eb extends A{_parse(e){return this._getType(e)===i.null?_(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}eb.create=(e,t)=>new eb({innerType:e,typeName:ts.ZodNullable,...S(t)});class e_ extends A{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===i.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}e_.create=(e,t)=>new e_({innerType:e,typeName:ts.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...S(t)});class ew extends A{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return E(a)?a.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new l(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new l(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ew.create=(e,t)=>new ew({innerType:e,typeName:ts.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...S(t)});class ev extends A{_parse(e){if(this._getType(e)!==i.nan){let t=this._getOrReturnCtx(e);return m(t,{code:s.invalid_type,expected:i.nan,received:t.parsedType}),y}return{status:"valid",value:e.data}}}ev.create=e=>new ev({typeName:ts.ZodNaN,...S(e)});let eO=Symbol("zod_brand");class eE extends A{_parse(e){let{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 ek extends A{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?y:"dirty"===e.status?(t.dirty(),b(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{let e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?y:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new ek({in:e,out:t,typeName:ts.ZodPipeline})}}class ex extends A{_parse(e){let t=this._def.innerType._parse(e);return O(t)&&(t.value=Object.freeze(t.value)),t}}ex.create=(e,t)=>new ex({innerType:e,typeName:ts.ZodReadonly,...S(t)});let eS=(e,t={},r)=>e?W.create().superRefine((a,i)=>{var n,s;if(!e(a)){let e="function"==typeof t?t(a):"string"==typeof t?{message:t}:t,o=null===(s=null!==(n=e.fatal)&&void 0!==n?n:r)||void 0===s||s,l="string"==typeof e?{message:e}:e;i.addIssue({code:"custom",...l,fatal:o})}}):W.create(),eA={object:Q.lazycreate};!function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(ts||(ts={}));let eP=(e,t={message:`Input not instance of ${e.name}`})=>eS(t=>t instanceof e,t),eT=U.create,eI=F.create,eN=ev.create,ej=B.create,eR=z.create,eC=H.create,e$=Z.create,eM=q.create,eL=G.create,eU=W.create,eD=K.create,eF=J.create,eB=Y.create,ez=V.create,eH=Q.create,eZ=Q.strictCreate,eq=ee.create,eG=er.create,eW=ei.create,eK=en.create,eJ=es.create,eY=eo.create,eV=el.create,eX=eu.create,eQ=ec.create,e0=eh.create,e1=ep.create,e2=ef.create,e4=em.create,e5=eg.create,e9=ey.create,e3=eb.create,e6=eg.createWithPreprocess,e8=ek.create,e7=()=>eI().optional(),te=()=>eR().optional(),tt={string:e=>U.create({...e,coerce:!0}),number:e=>F.create({...e,coerce:!0}),boolean:e=>z.create({...e,coerce:!0}),bigint:e=>B.create({...e,coerce:!0}),date:e=>H.create({...e,coerce:!0})},tr=y;var ta,ti,tn,ts,to=Object.freeze({__proto__:null,defaultErrorMap:u,setErrorMap:h,getErrorMap:d,makeIssue:p,EMPTY_PATH:f,addIssueToContext:m,ParseStatus:g,INVALID:y,DIRTY:b,OK:_,isAborted:w,isDirty:v,isValid:O,isAsync:E,get util(){return ta},get objectUtil(){return ti},ZodParsedType:i,getParsedType:n,ZodType:A,ZodString:U,ZodNumber:F,ZodBigInt:B,ZodBoolean:z,ZodDate:H,ZodSymbol:Z,ZodUndefined:q,ZodNull:G,ZodAny:W,ZodUnknown:K,ZodNever:J,ZodVoid:Y,ZodArray:V,ZodObject:Q,ZodUnion:ee,ZodDiscriminatedUnion:er,ZodIntersection:ei,ZodTuple:en,ZodRecord:es,ZodMap:eo,ZodSet:el,ZodFunction:eu,ZodLazy:ec,ZodLiteral:eh,ZodEnum:ep,ZodNativeEnum:ef,ZodPromise:em,ZodEffects:eg,ZodTransformer:eg,ZodOptional:ey,ZodNullable:eb,ZodDefault:e_,ZodCatch:ew,ZodNaN:ev,BRAND:eO,ZodBranded:eE,ZodPipeline:ek,ZodReadonly:ex,custom:eS,Schema:A,ZodSchema:A,late:eA,get ZodFirstPartyTypeKind(){return ts},coerce:tt,any:eU,array:ez,bigint:ej,boolean:eR,date:eC,discriminatedUnion:eG,effect:e5,enum:e1,function:eX,instanceof:eP,intersection:eW,lazy:eQ,literal:e0,map:eY,nan:eN,nativeEnum:e2,never:eF,null:eL,nullable:e3,number:eI,object:eH,oboolean:te,onumber:e7,optional:e9,ostring:()=>eT().optional(),pipeline:e8,preprocess:e6,promise:e4,record:eJ,set:eV,strictObject:eZ,string:eT,symbol:e$,transformer:e5,tuple:eK,undefined:eM,union:eq,unknown:eD,void:eB,NEVER:tr,ZodIssueCode:s,quotelessJson:o,ZodError:l})},55853:(e,t,r)=>{"use strict";r.d(t,{l:()=>a});let a=(e,t)=>e.reduce((e,r,a)=>{let i=Math.floor(a/t),n=e[i]||[];return e[i]=n.concat([r]),e},[])},56655:(e,t,r)=>{let{MAX_SAFE_COMPONENT_LENGTH:a,MAX_SAFE_BUILD_LENGTH:i,MAX_LENGTH:n}=r(81979),s=r(57265),o=(t=e.exports={}).re=[],l=t.safeRe=[],u=t.src=[],c=t.safeSrc=[],h=t.t={},d=0,p="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",n],[p,i]],m=e=>{for(let[t,r]of f)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},g=(e,t,r)=>{let a=m(t),i=d++;s(e,i,t),h[e]=i,u[i]=t,c[i]=a,o[i]=new RegExp(t,r?"g":void 0),l[i]=new RegExp(a,r?"g":void 0)};g("NUMERICIDENTIFIER","0|[1-9]\\d*"),g("NUMERICIDENTIFIERLOOSE","\\d+"),g("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),g("MAINVERSION",`(${u[h.NUMERICIDENTIFIER]})\\.(${u[h.NUMERICIDENTIFIER]})\\.(${u[h.NUMERICIDENTIFIER]})`),g("MAINVERSIONLOOSE",`(${u[h.NUMERICIDENTIFIERLOOSE]})\\.(${u[h.NUMERICIDENTIFIERLOOSE]})\\.(${u[h.NUMERICIDENTIFIERLOOSE]})`),g("PRERELEASEIDENTIFIER",`(?:${u[h.NUMERICIDENTIFIER]}|${u[h.NONNUMERICIDENTIFIER]})`),g("PRERELEASEIDENTIFIERLOOSE",`(?:${u[h.NUMERICIDENTIFIERLOOSE]}|${u[h.NONNUMERICIDENTIFIER]})`),g("PRERELEASE",`(?:-(${u[h.PRERELEASEIDENTIFIER]}(?:\\.${u[h.PRERELEASEIDENTIFIER]})*))`),g("PRERELEASELOOSE",`(?:-?(${u[h.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${u[h.PRERELEASEIDENTIFIERLOOSE]})*))`),g("BUILDIDENTIFIER",`${p}+`),g("BUILD",`(?:\\+(${u[h.BUILDIDENTIFIER]}(?:\\.${u[h.BUILDIDENTIFIER]})*))`),g("FULLPLAIN",`v?${u[h.MAINVERSION]}${u[h.PRERELEASE]}?${u[h.BUILD]}?`),g("FULL",`^${u[h.FULLPLAIN]}$`),g("LOOSEPLAIN",`[v=\\s]*${u[h.MAINVERSIONLOOSE]}${u[h.PRERELEASELOOSE]}?${u[h.BUILD]}?`),g("LOOSE",`^${u[h.LOOSEPLAIN]}$`),g("GTLT","((?:<|>)?=?)"),g("XRANGEIDENTIFIERLOOSE",`${u[h.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),g("XRANGEIDENTIFIER",`${u[h.NUMERICIDENTIFIER]}|x|X|\\*`),g("XRANGEPLAIN",`[v=\\s]*(${u[h.XRANGEIDENTIFIER]})(?:\\.(${u[h.XRANGEIDENTIFIER]})(?:\\.(${u[h.XRANGEIDENTIFIER]})(?:${u[h.PRERELEASE]})?${u[h.BUILD]}?)?)?`),g("XRANGEPLAINLOOSE",`[v=\\s]*(${u[h.XRANGEIDENTIFIERLOOSE]})(?:\\.(${u[h.XRANGEIDENTIFIERLOOSE]})(?:\\.(${u[h.XRANGEIDENTIFIERLOOSE]})(?:${u[h.PRERELEASELOOSE]})?${u[h.BUILD]}?)?)?`),g("XRANGE",`^${u[h.GTLT]}\\s*${u[h.XRANGEPLAIN]}$`),g("XRANGELOOSE",`^${u[h.GTLT]}\\s*${u[h.XRANGEPLAINLOOSE]}$`),g("COERCEPLAIN",`(^|[^\\d])(\\d{1,${a}})(?:\\.(\\d{1,${a}}))?(?:\\.(\\d{1,${a}}))?`),g("COERCE",`${u[h.COERCEPLAIN]}(?:$|[^\\d])`),g("COERCEFULL",u[h.COERCEPLAIN]+`(?:${u[h.PRERELEASE]})?`+`(?:${u[h.BUILD]})?`+"(?:$|[^\\d])"),g("COERCERTL",u[h.COERCE],!0),g("COERCERTLFULL",u[h.COERCEFULL],!0),g("LONETILDE","(?:~>?)"),g("TILDETRIM",`(\\s*)${u[h.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",g("TILDE",`^${u[h.LONETILDE]}${u[h.XRANGEPLAIN]}$`),g("TILDELOOSE",`^${u[h.LONETILDE]}${u[h.XRANGEPLAINLOOSE]}$`),g("LONECARET","(?:\\^)"),g("CARETTRIM",`(\\s*)${u[h.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",g("CARET",`^${u[h.LONECARET]}${u[h.XRANGEPLAIN]}$`),g("CARETLOOSE",`^${u[h.LONECARET]}${u[h.XRANGEPLAINLOOSE]}$`),g("COMPARATORLOOSE",`^${u[h.GTLT]}\\s*(${u[h.LOOSEPLAIN]})$|^$`),g("COMPARATOR",`^${u[h.GTLT]}\\s*(${u[h.FULLPLAIN]})$|^$`),g("COMPARATORTRIM",`(\\s*)${u[h.GTLT]}\\s*(${u[h.LOOSEPLAIN]}|${u[h.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",g("HYPHENRANGE",`^\\s*(${u[h.XRANGEPLAIN]})\\s+-\\s+(${u[h.XRANGEPLAIN]})\\s*$`),g("HYPHENRANGELOOSE",`^\\s*(${u[h.XRANGEPLAINLOOSE]})\\s+-\\s+(${u[h.XRANGEPLAINLOOSE]})\\s*$`),g("STAR","(<|>)?=?\\s*\\*"),g("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),g("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")},57265:(e,t,r)=>{var a=r(49509);e.exports="object"==typeof a&&a.env&&a.env.NODE_DEBUG&&/\bsemver\b/i.test(a.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{}},58036:(e,t,r)=>{"use strict";function a(e,t=i){e=e.trim();let r=/```(json)?(.*)```/s.exec(e);return t(r?r[2]:e)}function i(e){if(void 0===e)return null;try{return JSON.parse(e)}catch(e){}let t="",r=[],a=!1,i=!1;for(let n of e){if(a)'"'!==n||i?"\n"!==n||i?i="\\"===n&&!i:n="\\n":a=!1;else if('"'===n)a=!0,i=!1;else if("{"===n)r.push("}");else if("["===n)r.push("]");else if("}"===n||"]"===n){if(!r||r[r.length-1]!==n)return null;r.pop()}t+=n}a&&(t+='"');for(let e=r.length-1;e>=0;e-=1)t+=r[e];try{return JSON.parse(t)}catch(e){return null}}r.d(t,{D:()=>a,d:()=>i})},58775:(e,t,r)=>{"use strict";r.d(t,{kI:()=>a.kI,zZ:()=>a.zZ});var a=r(1995)},62886:(e,t,r)=>{"use strict";r.d(t,{a7:()=>n,xc:()=>i});var a=r(64520);class i extends a.XQ{static lc_name(){return"HumanMessage"}_getType(){return"human"}}class n extends a.gj{static lc_name(){return"HumanMessageChunk"}_getType(){return"human"}concat(e){return new n({content:(0,a._I)(this.content,e.content),additional_kwargs:(0,a.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,a.ns)(this.response_metadata,e.response_metadata),id:this.id??e.id})}}},63164:(e,t,r)=>{let a=r(36053);e.exports=(e,t)=>new a(e,t).patch},64520:(e,t,r)=>{"use strict";r.d(t,{AJ:()=>f,F7:()=>c,Iv:()=>n,Vt:()=>u,XQ:()=>o,_I:()=>i,dp:()=>d,gj:()=>h,ns:()=>l,ny:()=>p});var a=r(23931);function i(e,t){return"string"==typeof e?""===e?t:"string"==typeof t?e+t:[{type:"text",text:e},...t]:Array.isArray(t)?u(e,t)??[...e,...t]:""===t?e:[...e,{type:"text",text:t}]}function n(e,t){return"error"===e||"error"===t?"error":"success"}function s(e,t){function r(e,a){if("object"!=typeof e||null==e)return e;if(a>=t)return Array.isArray(e)?"[Array]":"[Object]";if(Array.isArray(e))return e.map(e=>r(e,a+1));let i={};for(let t of Object.keys(e))i[t]=r(e[t],a+1);return i}return JSON.stringify(r(e,0),null,2)}class o extends a.y{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}get text(){return"string"==typeof this.content?this.content:""}getType(){return this._getType()}constructor(e,t){"string"==typeof e&&(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(null===e)return this;let t=s(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}}function l(e,t){let r={...e};for(let[e,a]of Object.entries(t))if(null==r[e])r[e]=a;else if(null==a)continue;else if(typeof r[e]!=typeof a||Array.isArray(r[e])!==Array.isArray(a))throw Error(`field[${e}] already exists in the message chunk, but with a different type.`);else if("string"==typeof r[e]){if("type"===e)continue;r[e]+=a}else if("object"!=typeof r[e]||Array.isArray(r[e])){if(Array.isArray(r[e]))r[e]=u(r[e],a);else{if(r[e]===a)continue;console.warn(`field[${e}] already exists in this message chunk and value has unsupported type.`)}}else r[e]=l(r[e],a);return r}function u(e,t){if(void 0!==e||void 0!==t){if(void 0===e||void 0===t)return e||t;{let r=[...e];for(let e of t)if("object"==typeof e&&"index"in e&&"number"==typeof e.index){let t=r.findIndex(t=>t.index===e.index);-1!==t?r[t]=l(r[t],e):r.push(e)}else{if("object"==typeof e&&"text"in e&&""===e.text)continue;r.push(e)}return r}}}function c(e,t){if(!e&&!t)throw Error("Cannot merge two undefined objects.");if(!e||!t)return e||t;if(typeof e!=typeof t)throw Error(`Cannot merge objects of different types. Left ${typeof e} Right ${typeof t}`);if("string"==typeof e&&"string"==typeof t)return e+t;if(Array.isArray(e)&&Array.isArray(t))return u(e,t);if("object"==typeof e&&"object"==typeof t)return l(e,t);else if(e===t)return e;else throw Error(`Can not merge objects of different types. Left ${e} Right ${t}`)}class h extends o{}function d(e){return"string"==typeof e.role}function p(e){return"function"==typeof e?._getType}function f(e){return p(e)&&"function"==typeof e.concat}},64951:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});let a=r(4071);class i{constructor(){this._queue=[]}enqueue(e,t){let r={priority:(t=Object.assign({priority:0},t)).priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority){this._queue.push(r);return}let i=a.default(this._queue,r,(e,t)=>t.priority-e.priority);this._queue.splice(i,0,r)}dequeue(){let e=this._queue.shift();return null==e?void 0:e.run}filter(e){return this._queue.filter(t=>t.priority===e.priority).map(e=>e.run)}get size(){return this._queue.length}}t.default=i},65408:(e,t,r)=>{"use strict";r.d(t,{g:()=>o});var a=r(52813),i=r(52435);let n=[400,401,402,403,404,405,406,407,409],s=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||"AbortError"===e.name||e?.code==="ECONNABORTED")throw e;let t=e?.response?.status??e?.status;if(t&&n.includes(+t))throw e;if(e?.error?.code==="insufficient_quota"){let t=Error(e?.message);throw t.name="InsufficientQuotaError",t}};class o{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??s;let t=i.default;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>a(()=>e(...t).catch(e=>{if(e instanceof Error)throw e;throw Error(e)}),{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((t,r)=>{e.signal?.addEventListener("abort",()=>{r(Error("AbortError"))})})]):this.call(t,...r)}fetch(...e){return this.call(()=>fetch(...e).then(e=>e.ok?e:Promise.reject(e)))}}},66327:(e,t,r)=>{let a=r(36053),i=r(42870);e.exports=(e,t,r)=>{let n=null,s=null,o=null;try{o=new i(t,r)}catch(e){return null}return e.forEach(e=>{o.test(e)&&(!n||1===s.compare(e))&&(s=new a(n=e,r))}),n}},67146:(e,t,r)=>{"use strict";async function a(e,t){let r;return void 0===t?e:Promise.race([e.catch(e=>{if(!t?.aborted)throw e}),new Promise((e,a)=>{r=()=>{a(Error("Aborted"))},t.addEventListener("abort",r),t.aborted&&a(Error("Aborted"))})]).finally(()=>t.removeEventListener("abort",r))}r.d(t,{o:()=>a})},69988:(e,t,r)=>{"use strict";let a,i,n;r.d(t,{Az:()=>y,Ec:()=>f,Jz:()=>b,yk:()=>m});var s=r(53909),o=r(49509);let l=()=>"undefined"!=typeof window&&void 0!==window.document,u=()=>"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name,c=()=>"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")),h=()=>"undefined"!=typeof Deno,d=()=>void 0!==o&&void 0!==o.versions&&void 0!==o.versions.node&&!h(),p=()=>a||(a=l()?"browser":d()?"node":u()?"webworker":c()?"jsdom":h()?"deno":"other");function f(){if(void 0===i){let e=p(),t=_();i={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:s.Ls,...t}}return i}function m(){let e=g()||{},t={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(let[a,i]of Object.entries(e))(a.startsWith("LANGCHAIN_")||a.startsWith("LANGSMITH_"))&&"string"==typeof i&&!r.includes(a)&&!a.toLowerCase().includes("key")&&!a.toLowerCase().includes("secret")&&!a.toLowerCase().includes("token")&&("LANGCHAIN_REVISION_ID"===a?t.revision_id=i:t[a]=i);return t}function g(){try{if(void 0!==o&&o.env)return Object.entries(o.env).reduce((e,[t,r])=>(e[t]=String(r),e),{});return}catch(e){return}}function y(e){try{return void 0!==o?o.env?.[e]:void 0}catch(e){return}}function b(e){return y(`LANGSMITH_${e}`)||y(`LANGCHAIN_${e}`)}function _(){if(void 0!==n)return n;let e={};for(let t of["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"]){let r=y(t);void 0!==r&&(e[t]=r)}return n=e,e}},70240:(e,t,r)=>{"use strict";function a(e){return"function"==typeof e?.parse}r.d(t,{l:()=>a})},71150:(e,t,r)=>{"use strict";r.d(t,{Od:()=>a.Od,H:()=>a.H,cM:()=>n.cM,xc:()=>o.xc,K0:()=>u.K0,KX:()=>a.KX,jm:()=>a.jm,ny:()=>i.ny});var a=r(41039),i=r(64520),n=r(71151),s=r(76937),o=r(62886),l=r(91356),u=r(90338);r(4693);class c extends i.XQ{constructor(e){super({...e,content:""}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.id=e.id}_getType(){return"remove"}get _printableFields(){return{...super._printableFields,id:this.id}}}var h=r(27231);let d=(e,t)=>{let r=[...new Set(t?.map(e=>{if("string"==typeof e)return e;let t=new e({});if(!("getType"in t)||"function"!=typeof t.getType)throw Error("Invalid type provided.");return t.getType()}))],a=e.getType();return r.some(e=>e===a)};async function p(e,t){let{maxTokens:r,tokenCounter:a,textSplitter:i,partialStrategy:n,endOn:s}=t,o=[...e],l=0;for(let e=0;e0?o.slice(0,-e):o;if(await a(t)<=r){l=o.length-e;break}}if(l"type"!==e&&!e.startsWith("lc_"))),h=g(t.getType(),{...c,content:i}),d=[...o.slice(0,l),h];if(await a(d)<=r)o=d,l+=1,e=!0;else break}e&&"last"===n&&(t.content=[...s].reverse())}if(!e){let e;let t=o[l];if(Array.isArray(t.content)&&t.content.some(e=>"string"==typeof e||"text"===e.type)){let r=t.content.find(e=>"text"===e.type&&e.text);e=r?.text}else"string"==typeof t.content&&(e=t.content);if(e){let s=await i(e),u=s.length;"last"===n&&s.reverse();for(let e=0;e0&&!d(o[l-1],e);)l-=1}return o.slice(0,l)}async function f(e,t){let{allowPartial:r=!1,includeSystem:a=!1,endOn:i,startOn:n,...s}=t,o=e.map(e=>{let t=Object.fromEntries(Object.entries(e).filter(([e])=>"type"!==e&&!e.startsWith("lc_")));return g(e.getType(),t,isBaseMessageChunk(e))});if(i){let e=Array.isArray(i)?i:[i];for(;o.length>0&&!d(o[o.length-1],e);)o=o.slice(0,-1)}let l=a&&o[0]?.getType()==="system",u=l?o.slice(0,1).concat(o.slice(1).reverse()):o.reverse();return(u=await p(u,{...s,partialStrategy:r?"last":void 0,endOn:n}),l)?[u[0],...u.slice(1).reverse()]:u.reverse()}let m={human:{message:o.xc,messageChunk:o.a7},ai:{message:a.Od,messageChunk:a.H},system:{message:l.tn,messageChunk:l.uU},developer:{message:l.tn,messageChunk:l.uU},tool:{message:h.uf,messageChunk:h.dr},function:{message:s.mg,messageChunk:s.FK},generic:{message:n.cM,messageChunk:n.XU},remove:{message:c,messageChunk:c}};function g(e,t,r){let a,i;switch(e){case"human":r?a=new HumanMessageChunk(t):i=new HumanMessage(t);break;case"ai":if(r){let e={...t};"tool_calls"in e&&(e={...e,tool_call_chunks:e.tool_calls?.map(e=>({...e,type:"tool_call_chunk",index:void 0,args:JSON.stringify(e.args)}))}),a=new AIMessageChunk(e)}else i=new AIMessage(t);break;case"system":r?a=new SystemMessageChunk(t):i=new SystemMessage(t);break;case"developer":r?a=new SystemMessageChunk({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}}):i=new SystemMessage({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in t)r?a=new ToolMessageChunk(t):i=new ToolMessage(t);else throw Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if(r)a=new FunctionMessageChunk(t);else{if(!t.name)throw Error("FunctionMessage must have a 'name' field");i=new FunctionMessage(t)}break;case"generic":if("role"in t)r?a=new ChatMessageChunk(t):i=new ChatMessage(t);else throw Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");break;default:throw Error(`Unrecognized message type ${e}`)}if(r&&a)return a;if(i)return i;throw Error(`Unrecognized message type ${e}`)}function y(e){let t;let r=e.getType(),a=Object.fromEntries(Object.entries(e).filter(([e])=>!["type","tool_call_chunks"].includes(e)&&!e.startsWith("lc_")));if(r in m&&(t=g(r,a)),!t)throw Error(`Unrecognized message chunk class ${r}. Supported classes are ${Object.keys(m)}`);return t}function b(e){let t=e.split("\n");return Promise.resolve([...t.slice(0,-1).map(e=>`${e} `),t[t.length-1]])}},71151:(e,t,r)=>{"use strict";r.d(t,{XU:()=>n,cM:()=>i});var a=r(64520);class i extends a.XQ{static lc_name(){return"ChatMessage"}static _chatMessageClass(){return i}constructor(e,t){"string"==typeof e&&(e={content:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){return"generic"}static isInstance(e){return"generic"===e._getType()}get _printableFields(){return{...super._printableFields,role:this.role}}}class n extends a.gj{static lc_name(){return"ChatMessageChunk"}constructor(e,t){"string"==typeof e&&(e={content:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){return"generic"}concat(e){return new n({content:(0,a._I)(this.content,e.content),additional_kwargs:(0,a.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,a.ns)(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}get _printableFields(){return{...super._printableFields,role:this.role}}}},72257:(e,t,r)=>{"use strict";r.d(t,{J:()=>i});var a=r(65408);class i{constructor(e){Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.caller=new a.g(e??{})}}},72400:(e,t,r)=>{"use strict";r.d(t,{j_:()=>D,VC:()=>M});var a="object"==typeof window?window:{},i="0123456789abcdef".split(""),n=[-0x80000000,8388608,32768,128],s=[24,16,8,0],o=[];function l(e){e?(o[0]=o[16]=o[1]=o[2]=o[3]=o[4]=o[5]=o[6]=o[7]=o[8]=o[9]=o[10]=o[11]=o[12]=o[13]=o[14]=o[15]=0,this.blocks=o):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.h0=0x67452301,this.h1=0xefcdab89,this.h2=0x98badcfe,this.h3=0x10325476,this.h4=0xc3d2e1f0,this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}l.prototype.update=function(e){if(!this.finalized){var t="string"!=typeof e;t&&e.constructor===a.ArrayBuffer&&(e=new Uint8Array(e));for(var r,i,n=0,o=e.length||0,l=this.blocks;n>2]|=e[n]<>2]|=r<>2]|=(192|r>>6)<=57344?l[i>>2]|=(224|r>>12)<>2]|=(240|r>>18)<>2]|=(128|r>>12&63)<>2]|=(128|r>>6&63)<>2]|=(128|63&r)<=64?(this.block=l[16],this.start=i-64,this.hash(),this.hashed=!0):this.start=i}return this.bytes>0xffffffff&&(this.hBytes+=this.bytes/0x100000000<<0,this.bytes=this.bytes%0x100000000),this}},l.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>2]|=n[3&t],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}},l.prototype.hash=function(){var e,t,r,a=this.h0,i=this.h1,n=this.h2,s=this.h3,o=this.h4,l=this.blocks;for(t=16;t<80;++t)r=l[t-3]^l[t-8]^l[t-14]^l[t-16],l[t]=r<<1|r>>>31;for(t=0;t<20;t+=5)e=i&n|~i&s,o=(r=a<<5|a>>>27)+e+o+0x5a827999+l[t]<<0,e=a&(i=i<<30|i>>>2)|~a&n,s=(r=o<<5|o>>>27)+e+s+0x5a827999+l[t+1]<<0,e=o&(a=a<<30|a>>>2)|~o&i,n=(r=s<<5|s>>>27)+e+n+0x5a827999+l[t+2]<<0,e=s&(o=o<<30|o>>>2)|~s&a,i=(r=n<<5|n>>>27)+e+i+0x5a827999+l[t+3]<<0,e=n&(s=s<<30|s>>>2)|~n&o,a=(r=i<<5|i>>>27)+e+a+0x5a827999+l[t+4]<<0,n=n<<30|n>>>2;for(;t<40;t+=5)e=i^n^s,o=(r=a<<5|a>>>27)+e+o+0x6ed9eba1+l[t]<<0,e=a^(i=i<<30|i>>>2)^n,s=(r=o<<5|o>>>27)+e+s+0x6ed9eba1+l[t+1]<<0,e=o^(a=a<<30|a>>>2)^i,n=(r=s<<5|s>>>27)+e+n+0x6ed9eba1+l[t+2]<<0,e=s^(o=o<<30|o>>>2)^a,i=(r=n<<5|n>>>27)+e+i+0x6ed9eba1+l[t+3]<<0,e=n^(s=s<<30|s>>>2)^o,a=(r=i<<5|i>>>27)+e+a+0x6ed9eba1+l[t+4]<<0,n=n<<30|n>>>2;for(;t<60;t+=5)e=i&n|i&s|n&s,o=(r=a<<5|a>>>27)+e+o-0x70e44324+l[t]<<0,e=a&(i=i<<30|i>>>2)|a&n|i&n,s=(r=o<<5|o>>>27)+e+s-0x70e44324+l[t+1]<<0,e=o&(a=a<<30|a>>>2)|o&i|a&i,n=(r=s<<5|s>>>27)+e+n-0x70e44324+l[t+2]<<0,e=s&(o=o<<30|o>>>2)|s&a|o&a,i=(r=n<<5|n>>>27)+e+i-0x70e44324+l[t+3]<<0,e=n&(s=s<<30|s>>>2)|n&o|s&o,a=(r=i<<5|i>>>27)+e+a-0x70e44324+l[t+4]<<0,n=n<<30|n>>>2;for(;t<80;t+=5)e=i^n^s,o=(r=a<<5|a>>>27)+e+o-0x359d3e2a+l[t]<<0,e=a^(i=i<<30|i>>>2)^n,s=(r=o<<5|o>>>27)+e+s-0x359d3e2a+l[t+1]<<0,e=o^(a=a<<30|a>>>2)^i,n=(r=s<<5|s>>>27)+e+n-0x359d3e2a+l[t+2]<<0,e=s^(o=o<<30|o>>>2)^a,i=(r=n<<5|n>>>27)+e+i-0x359d3e2a+l[t+3]<<0,e=n^(s=s<<30|s>>>2)^o,a=(r=i<<5|i>>>27)+e+a-0x359d3e2a+l[t+4]<<0,n=n<<30|n>>>2;this.h0=this.h0+a<<0,this.h1=this.h1+i<<0,this.h2=this.h2+n<<0,this.h3=this.h3+s<<0,this.h4=this.h4+o<<0},l.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,a=this.h3,n=this.h4;return i[e>>28&15]+i[e>>24&15]+i[e>>20&15]+i[e>>16&15]+i[e>>12&15]+i[e>>8&15]+i[e>>4&15]+i[15&e]+i[t>>28&15]+i[t>>24&15]+i[t>>20&15]+i[t>>16&15]+i[t>>12&15]+i[t>>8&15]+i[t>>4&15]+i[15&t]+i[r>>28&15]+i[r>>24&15]+i[r>>20&15]+i[r>>16&15]+i[r>>12&15]+i[r>>8&15]+i[r>>4&15]+i[15&r]+i[a>>28&15]+i[a>>24&15]+i[a>>20&15]+i[a>>16&15]+i[a>>12&15]+i[a>>8&15]+i[a>>4&15]+i[15&a]+i[n>>28&15]+i[n>>24&15]+i[n>>20&15]+i[n>>16&15]+i[n>>12&15]+i[n>>8&15]+i[n>>4&15]+i[15&n]},l.prototype.toString=l.prototype.hex,l.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,a=this.h3,i=this.h4;return[e>>24&255,e>>16&255,e>>8&255,255&e,t>>24&255,t>>16&255,t>>8&255,255&t,r>>24&255,r>>16&255,r>>8&255,255&r,a>>24&255,a>>16&255,a>>8&255,255&a,i>>24&255,i>>16&255,i>>8&255,255&i]},l.prototype.array=l.prototype.digest,l.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(20),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),e};let u=e=>new l(!0).update(e).hex();var c=r(90338);let h=(...e)=>u(e.join("_"));class d{}let p=new Map;class f extends d{constructor(e){super(),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cache=e??new Map}lookup(e,t){return Promise.resolve(this.cache.get(h(e,t))??null)}async update(e,t,r){this.cache.set(h(e,t),r)}static global(){return new f(p)}}var m=r(23931),g=r(62886);class y extends m.y{}class b extends y{static lc_name(){return"StringPromptValue"}constructor(e){super({value:e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.value=e}toString(){return this.value}toChatMessages(){return[new g.xc(this.value)]}}class _ extends y{static lc_name(){return"ChatPromptValue"}constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.messages=e.messages}toString(){return(0,c.Sw)(this.messages)}toChatMessages(){return this.messages}}var w=r(65408),v=r(57719),O=Object.defineProperty,E=(e,t,r)=>t in e?O(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;function k(e,t){let r=Array.from({length:e.length},(e,t)=>({start:t,end:t+1}));for(;r.length>1;){let a=null;for(let i=0;it.get(e.slice(r.start,r.end).join(","))).filter(e=>null!=e)}function S(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var A=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,t){for(let[t,r]of(this.patStr=e.pat_str,Object.entries(e.bpe_ranks.split("\n").filter(Boolean).reduce((e,t)=>{let[r,a,...i]=t.split(" "),n=Number.parseInt(a,10);return i.forEach((t,r)=>e[t]=n+r),e},{})))){let e=v.toByteArray(t);this.rankMap.set(e.join(","),r),this.textMap.set(r,e)}this.specialTokens={...e.special_tokens,...t},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((e,[t,r])=>(e[r]=this.textEncoder.encode(t),e),{})}encode(e,t=[],r="all"){let a=RegExp(this.patStr,"ug"),i=A.specialTokenRegex(Object.keys(this.specialTokens)),n=[],s=new Set("all"===t?Object.keys(this.specialTokens):t),o=new Set("all"===r?Object.keys(this.specialTokens).filter(e=>!s.has(e)):r);if(o.size>0){let t=A.specialTokenRegex([...o]),r=e.match(t);if(null!=r)throw Error(`The text contains a special token that is not allowed: ${r[0]}`)}let l=0;for(;;){let t=null,r=l;for(;i.lastIndex=r,!(null==(t=i.exec(e))||s.has(t[0]));)r=t.index+1;let o=t?.index??e.length;for(let t of e.substring(l,o).matchAll(a)){let e=this.textEncoder.encode(t[0]),r=this.rankMap.get(e.join(","));if(null!=r){n.push(r);continue}n.push(...x(e,this.rankMap))}if(null==t)break;let u=this.specialTokens[t[0]];n.push(u),l=t.index+t[0].length}return n}decode(e){let t=[],r=0;for(let a=0;aE(e,"symbol"!=typeof t?t+"":t,r))(P,"specialTokenRegex",e=>RegExp(e.map(e=>S(e)).join("|"),"g"));let I={},N=new w.g({});async function j(e){return e in I||(I[e]=N.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(e=>e.json()).then(e=>new P(e)).catch(t=>{throw delete I[e],t})),await I[e]}async function R(e){return j(T(e))}var C=r(4693);let $=e=>e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e;function M(e){return"object"==typeof e&&!!e&&("type"in e&&"function"===e.type&&"function"in e&&"object"==typeof e.function&&!!e.function&&"name"in e.function&&"parameters"in e.function||!1)}let L=()=>!1;class U extends C.YN{get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.verbose=e.verbose??L(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}}class D extends U{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}constructor({callbacks:e,callbackManager:t,...r}){let{cache:a,...i}=r;super({callbacks:e??t,...i}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_encoding",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),"object"==typeof a?this.cache=a:a?this.cache=f.global():this.cache=void 0,this.caller=new w.g(r??{})}async getNumTokens(e){if("string"!=typeof e)return 0;let t=Math.ceil(e.length/4);if(!this._encoding)try{this._encoding=await R("modelName"in this?$(this.modelName):"gpt2")}catch(e){console.warn("Failed to calculate number of tokens, falling back to approximate count",e)}if(this._encoding)try{t=this._encoding.encode(e).length}catch(e){console.warn("Failed to calculate number of tokens, falling back to approximate count",e)}return t}static _convertInputToPromptValue(e){return"string"==typeof e?new b(e):Array.isArray(e)?new _(e.map(c.K0)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){return Object.entries({...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()}).filter(([e,t])=>void 0!==t).map(([e,t])=>`${e}:${JSON.stringify(t)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw Error("Use .toJSON() instead")}}},72716:(e,t,r)=>{"use strict";r.d(t,{NK:()=>l,xL:()=>o,zr:()=>u});var a=r(79737),i=r(23931),n=r(4397);class s{}function o(e){return"lc_prefer_streaming"in e&&e.lc_prefer_streaming}class l extends s{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,(0,i.Z)(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:"false"===(0,n.Az)("LANGCHAIN_CALLBACKS_BACKGROUND")}),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 i.y.prototype.toJSON.call(this)}toJSONNotImplemented(){return i.y.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends l{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:a.A()}),Object.assign(this,e)}}return new t}}let u=e=>{let t=e;return void 0!==t&&"function"==typeof t.copy&&"string"==typeof t.name&&"boolean"==typeof t.awaitHandlers}},76374:(e,t,r)=>{"use strict";let a=r(26682);class i extends Date{constructor(e){super(`0000-01-01T${e}Z`),this.isTime=!0}toISOString(){return`${a(2,this.getUTCHours())}:${a(2,this.getUTCMinutes())}:${a(2,this.getUTCSeconds())}.${a(3,this.getUTCMilliseconds())}`}}e.exports=e=>{let t=new i(e);if(!isNaN(t))return t;throw TypeError("Invalid Datetime")}},76406:(e,t,r)=>{let a=r(8044);e.exports=(e,t)=>e.sort((e,r)=>a(e,r,t))},76591:e=>{"use strict";e.exports=function(e,t){if("string"!=typeof e)throw TypeError("Expected a string");return t=void 0===t?"_":t,e.replace(/([a-z\d])([A-Z])/g,"$1"+t+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+t+"$2").toLowerCase()}},76937:(e,t,r)=>{"use strict";r.d(t,{FK:()=>n,mg:()=>i});var a=r(64520);class i extends a.XQ{static lc_name(){return"FunctionMessage"}constructor(e,t){"string"==typeof e&&(e={content:e,name:t}),super(e)}_getType(){return"function"}}class n extends a.gj{static lc_name(){return"FunctionMessageChunk"}_getType(){return"function"}concat(e){return new n({content:(0,a._I)(this.content,e.content),additional_kwargs:(0,a.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,a.ns)(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}}},77015:(e,t,r)=>{let a=r(89377);e.exports=(e,t)=>{let r=a(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null}},77466:(e,t,r)=>{"use strict";let a,i;r.d(t,{Td:()=>L,tW:()=>U});var n=r(79737),s=r(72716),o=r(84123),l=r(25050);function u(e,t){return`${e.open}${t}${e.close}`}function c(e,t){try{return JSON.stringify(e,null,2)}catch(e){return t}}function h(e){return"string"==typeof e?e.trim():null==e?e:c(e,e.toString())}function d(e){if(!e.end_time)return"";let t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}let{color:p}=o;class f extends l.J{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"console_callback_handler"})}persistRun(e){return Promise.resolve()}getParents(e){let t=[],r=e;for(;r.parent_run_id;){let e=this.runMap.get(r.parent_run_id);if(e)t.push(e),r=e;else break}return t}getBreadcrumbs(e){let t=[...this.getParents(e).reverse(),e].map((e,t,r)=>{let a=`${e.execution_order}:${e.run_type}:${e.name}`;return t===r.length-1?u(o.bold,a):a}).join(" > ");return u(p.grey,t)}onChainStart(e){let t=this.getBreadcrumbs(e);console.log(`${u(p.green,"[chain/start]")} [${t}] Entering Chain run with input: ${c(e.inputs,"[inputs]")}`)}onChainEnd(e){let t=this.getBreadcrumbs(e);console.log(`${u(p.cyan,"[chain/end]")} [${t}] [${d(e)}] Exiting Chain run with output: ${c(e.outputs,"[outputs]")}`)}onChainError(e){let t=this.getBreadcrumbs(e);console.log(`${u(p.red,"[chain/error]")} [${t}] [${d(e)}] Chain run errored with error: ${c(e.error,"[error]")}`)}onLLMStart(e){let t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(e=>e.trim())}:e.inputs;console.log(`${u(p.green,"[llm/start]")} [${t}] Entering LLM run with input: ${c(r,"[inputs]")}`)}onLLMEnd(e){let t=this.getBreadcrumbs(e);console.log(`${u(p.cyan,"[llm/end]")} [${t}] [${d(e)}] Exiting LLM run with output: ${c(e.outputs,"[response]")}`)}onLLMError(e){let t=this.getBreadcrumbs(e);console.log(`${u(p.red,"[llm/error]")} [${t}] [${d(e)}] LLM run errored with error: ${c(e.error,"[error]")}`)}onToolStart(e){let t=this.getBreadcrumbs(e);console.log(`${u(p.green,"[tool/start]")} [${t}] Entering Tool run with input: "${h(e.inputs.input)}"`)}onToolEnd(e){let t=this.getBreadcrumbs(e);console.log(`${u(p.cyan,"[tool/end]")} [${t}] [${d(e)}] Exiting Tool run with output: "${h(e.outputs?.output)}"`)}onToolError(e){let t=this.getBreadcrumbs(e);console.log(`${u(p.red,"[tool/error]")} [${t}] [${d(e)}] Tool run errored with error: ${c(e.error,"[error]")}`)}onRetrieverStart(e){let t=this.getBreadcrumbs(e);console.log(`${u(p.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${c(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){let t=this.getBreadcrumbs(e);console.log(`${u(p.cyan,"[retriever/end]")} [${t}] [${d(e)}] Exiting Retriever run with output: ${c(e.outputs,"[outputs]")}`)}onRetrieverError(e){let t=this.getBreadcrumbs(e);console.log(`${u(p.red,"[retriever/error]")} [${t}] [${d(e)}] Retriever run errored with error: ${c(e.error,"[error]")}`)}onAgentAction(e){let t=e,r=this.getBreadcrumbs(e);console.log(`${u(p.blue,"[agent/action]")} [${r}] Agent selected action: ${c(t.actions[t.actions.length-1],"[action]")}`)}}var m=r(90338),g=r(4397),y=r(11259),b=r(19839),_=r(82926);let w=()=>{if(void 0===a){let e="false"===(0,g.Az)("LANGCHAIN_CALLBACKS_BACKGROUND")?{blockOnRootRunFinalization:!0}:{};a=new _.Kj(e)}return a};class v extends l.J{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});let{exampleId:t,projectName:r,client:a}=e;this.projectName=r??(0,g.Az)("LANGCHAIN_PROJECT")??(0,g.Az)("LANGCHAIN_SESSION"),this.exampleId=t,this.client=a??w();let i=v.getTraceableRunTree();i&&this.updateFromRunTree(i)}async _convertToCreate(e,t){return{...e,extra:{...e.extra,runtime:await (0,g.Ec)()},child_runs:void 0,session_name:this.projectName,reference_example_id:e.parent_run_id?void 0:t}}async persistRun(e){}async onRunCreate(e){let t=await this._convertToCreate(e,this.exampleId);await this.client.createRun(t)}async onRunUpdate(e){let t={end_time:e.end_time,error:e.error,outputs:e.outputs,events:e.events,inputs:e.inputs,trace_id:e.trace_id,dotted_order:e.dotted_order,parent_run_id:e.parent_run_id,extra:e.extra};await this.client.updateRun(e.id,t)}getRun(e){return this.runMap.get(e)}updateFromRunTree(e){let t=e,r=new Set;for(;t.parent_run&&!r.has(t.id)&&(r.add(t.id),t.parent_run);){t=t.parent_run}r.clear();let a=[t];for(;a.length>0;){let e=a.shift();!(!e||r.has(e.id))&&(r.add(e.id),this.runMap.set(e.id,e),e.child_runs&&a.push(...e.child_runs))}this.client=e.client??this.client,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}convertToRunTree(e){let t={},r=[];for(let[e,a]of this.runMap){let i=new y.gk({...a,child_runs:[],parent_run:void 0,client:this.client,project_name:this.projectName,reference_example_id:this.exampleId,tracingEnabled:!0});t[e]=i,r.push([e,a.dotted_order])}for(let[e]of(r.sort((e,t)=>e[1]&&t[1]?e[1].localeCompare(t[1]):0),r)){let r=this.runMap.get(e),a=t[e];if(r&&a&&r.parent_run_id){let e=t[r.parent_run_id];e&&(e.child_runs.push(a),a.parent_run=e)}}return t[e]}static getTraceableRunTree(){try{return(0,b.vR)()}catch{return}}}var O=r(52435),E=r(44768);function k(){return new O.default({autoStart:!0,concurrency:1})}function x(){return void 0===i&&(i=k()),i}async function S(e,t){if(!0===t){let t=(0,E.X0)();void 0!==t?await t.run(void 0,async()=>e()):await e()}else(i=x()).add(async()=>{let t=(0,E.X0)();void 0!==t?await t.run(void 0,async()=>e()):await e()})}let A=e=>void 0!==e?e:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>"true"===(0,g.Az)(e));function P(e){let t=(0,E.X0)();if(void 0===t)return;let r=t.getStore();return r?.[E.hr]?.[e]}let T=Symbol("lc:configure_hooks"),I=()=>P(T)||[];class N{setHandler(e){return this.setHandlers([e])}}class j{constructor(e,t,r,a,i,n,s,o){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:a}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:o})}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>S(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleCustomEvent(e,t,r,a,i){await Promise.all(this.handlers.map(r=>S(async()=>{try{await r.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleCustomEvent: ${e}`),r.raiseError)throw e}},r.awaitHandlers)))}}class R extends j{getChild(e){let t=new L(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=>S(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw e}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>S(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 C extends j{async handleLLMNewToken(e,t,r,a,i,n){await Promise.all(this.handlers.map(r=>S(async()=>{if(!r.ignoreLLM)try{await r.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,n)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMNewToken: ${e}`),r.raiseError)throw e}},r.awaitHandlers)))}async handleLLMError(e,t,r,a,i){await Promise.all(this.handlers.map(t=>S(async()=>{if(!t.ignoreLLM)try{await t.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleLLMEnd(e,t,r,a,i){await Promise.all(this.handlers.map(t=>S(async()=>{if(!t.ignoreLLM)try{await t.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}}class $ extends j{getChild(e){let t=new L(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,a,i){await Promise.all(this.handlers.map(t=>S(async()=>{if(!t.ignoreChain)try{await t.handleChainError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleChainEnd(e,t,r,a,i){await Promise.all(this.handlers.map(t=>S(async()=>{if(!t.ignoreChain)try{await t.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>S(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>S(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}}class M extends j{getChild(e){let t=new L(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=>S(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>S(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}}class L extends N{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,a,i,s,o,u){return Promise.all(t.map(async(t,a)=>{let s=0===a&&r?r:(0,n.A)();return await Promise.all(this.handlers.map(r=>{if(!r.ignoreLLM)return(0,l.j)(r)&&r._createRunForLLMStart(e,[t],s,this._parentRunId,i,this.tags,this.metadata,u),S(async()=>{try{await r.handleLLMStart?.(e,[t],s,this._parentRunId,i,this.tags,this.metadata,u)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new C(s,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,r,a,i,s,o,u){return Promise.all(t.map(async(t,a)=>{let s=0===a&&r?r:(0,n.A)();return await Promise.all(this.handlers.map(r=>{if(!r.ignoreLLM)return(0,l.j)(r)&&r._createRunForChatModelStart(e,[t],s,this._parentRunId,i,this.tags,this.metadata,u),S(async()=>{try{if(r.handleChatModelStart)await r.handleChatModelStart?.(e,[t],s,this._parentRunId,i,this.tags,this.metadata,u);else if(r.handleLLMStart){let a=(0,m.Sw)(t);await r.handleLLMStart?.(e,[a],s,this._parentRunId,i,this.tags,this.metadata,u)}}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new C(s,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,r=(0,n.A)(),a,i,s,o){return await Promise.all(this.handlers.map(i=>{if(!i.ignoreChain)return(0,l.j)(i)&&i._createRunForChainStart(e,t,r,this._parentRunId,this.tags,this.metadata,a,o),S(async()=>{try{await i.handleChainStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,a,o)}catch(e){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainStart: ${e}`),i.raiseError)throw e}},i.awaitHandlers)})),new $(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,r=(0,n.A)(),a,i,s,o){return await Promise.all(this.handlers.map(a=>{if(!a.ignoreAgent)return(0,l.j)(a)&&a._createRunForToolStart(e,t,r,this._parentRunId,this.tags,this.metadata,o),S(async()=>{try{await a.handleToolStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,o)}catch(e){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleToolStart: ${e}`),a.raiseError)throw e}},a.awaitHandlers)})),new M(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,r=(0,n.A)(),a,i,s,o){return await Promise.all(this.handlers.map(a=>{if(!a.ignoreRetriever)return(0,l.j)(a)&&a._createRunForRetrieverStart(e,t,r,this._parentRunId,this.tags,this.metadata,o),S(async()=>{try{await a.handleRetrieverStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,o)}catch(e){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleRetrieverStart: ${e}`),a.raiseError)throw e}},a.awaitHandlers)})),new R(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,r,a,i){await Promise.all(this.handlers.map(a=>S(async()=>{if(!a.ignoreCustomEvent)try{await a.handleCustomEvent?.(e,t,r,this.tags,this.metadata)}catch(e){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${e}`),a.raiseError)throw e}},a.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){for(let r of(this.handlers=[],this.inheritableHandlers=[],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(let t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(e=[],t=!0){let r=new L(this._parentRunId);for(let e of this.handlers){let t=this.inheritableHandlers.includes(e);r.addHandler(e,t)}for(let e of this.tags){let t=this.inheritableTags.includes(e);r.addTags([e],t)}for(let e of Object.keys(this.metadata)){let t=Object.keys(this.inheritableMetadata).includes(e);r.addMetadata({[e]:this.metadata[e]},t)}for(let a of e)!r.handlers.filter(e=>"console_callback_handler"===e.name).some(e=>e.name===a.name)&&r.addHandler(a,t);return r}static fromHandlers(e){class t extends s.NK{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:(0,n.A)()}),Object.assign(this,e)}}let r=new this;return r.addHandler(new t),r}static configure(e,t,r,a,i,n,s){return this._configureSync(e,t,r,a,i,n,s)}static _configureSync(e,t,r,a,i,n,o){let l;(e||t)&&(Array.isArray(e)||!e?(l=new L).setHandlers(e?.map(U)??[],!0):l=e,l=l.copy(Array.isArray(t)?t.map(U):t?.handlers,!1));let u="true"===(0,g.Az)("LANGCHAIN_VERBOSE")||o?.verbose,c=v.getTraceableRunTree()?.tracingEnabled||A(),h=c||((0,g.Az)("LANGCHAIN_TRACING")??!1);if(u||h){if(l||(l=new L),u&&!l.handlers.some(e=>e.name===f.prototype.name)){let e=new f;l.addHandler(e,!0)}if(h&&!l.handlers.some(e=>"langchain_tracer"===e.name)&&c){let e=new v;l.addHandler(e,!0),l._parentRunId=v.getTraceableRunTree()?.id??l._parentRunId}}for(let{contextVar:e,inheritable:t=!0,handlerClass:r,envVar:a}of I()){let i;let n=a&&"true"===(0,g.Az)(a)&&r,o=void 0!==e?P(e):void 0;o&&(0,s.zr)(o)?i=o:n&&(i=new r({})),void 0===i||(l||(l=new L),l.handlers.some(e=>e.name===i.name)||l.addHandler(i,t))}return(r||a)&&l&&(l.addTags(r??[]),l.addTags(a??[],!1)),(i||n)&&l&&(l.addMetadata(i??{}),l.addMetadata(n??{},!1)),l}}function U(e){return"name"in e?e:s.NK.fromMethods(e)}},77985:(e,t,r)=>{let a=r(89377);e.exports=(e,t)=>{let r=a(e,null,!0),i=a(t,null,!0),n=r.compare(i);if(0===n)return null;let s=n>0,o=s?r:i,l=s?i:r,u=!!o.prerelease.length;if(l.prerelease.length&&!u){if(!l.patch&&!l.minor)return"major";if(0===l.compareMain(o))return l.minor&&!l.patch?"minor":"patch"}let c=u?"pre":"";return r.major!==i.major?c+"major":r.minor!==i.minor?c+"minor":r.patch!==i.patch?c+"patch":"prerelease"}},79737:(e,t,r)=>{"use strict";r.d(t,{A:()=>c});let a={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};var i,n=new Uint8Array(16);function s(){if(!i&&!(i="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return i(n)}for(var o=[],l=0;l<256;++l)o.push((l+256).toString(16).slice(1));function u(e,t=0){return(o[e[t+0]]+o[e[t+1]]+o[e[t+2]]+o[e[t+3]]+"-"+o[e[t+4]]+o[e[t+5]]+"-"+o[e[t+6]]+o[e[t+7]]+"-"+o[e[t+8]]+o[e[t+9]]+"-"+o[e[t+10]]+o[e[t+11]]+o[e[t+12]]+o[e[t+13]]+o[e[t+14]]+o[e[t+15]]).toLowerCase()}let c=function(e,t,r){if(a.randomUUID&&!t&&!e)return a.randomUUID();var i=(e=e||{}).random||(e.rng||s)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){r=r||0;for(var n=0;n<16;++n)t[r+n]=i[n];return t}return u(i)}},81679:(e,t,r)=>{"use strict";r(95811),r(53210),r(19918),r(11813)},81979:e=>{e.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||0x1fffffffffffff,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}},82591:(e,t,r)=>{"use strict";r.d(t,{X6:()=>w,UD:()=>A});var a={};r.r(a),r.d(a,{JsonPatchError:()=>f,_areEquals:()=>k,applyOperation:()=>_,applyPatch:()=>w,applyReducer:()=>v,deepClone:()=>m,getValueByPointer:()=>b,validate:()=>E,validator:()=>O});let i=Object.prototype.hasOwnProperty;function n(e,t){return i.call(e,t)}function s(e){if(Array.isArray(e)){let t=Array(e.length);for(let e=0;e=48&&t<=57){r++;continue}return!1}return!0}function u(e){return -1===e.indexOf("/")&&-1===e.indexOf("~")?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function c(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function h(e){if(void 0===e)return!0;if(e){if(Array.isArray(e)){for(let t=0,r=e.length;t0&&"constructor"==d[m-1]))throw TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&void 0===h&&(void 0===p[s]?h=d.slice(0,m).join("/"):m==b-1&&(h=t.path),void 0!==h&&u(t,0,e,h)),m++,Array.isArray(p)){if("-"===s)s=p.length;else{if(r&&!l(s))throw new f("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",n,t,e);l(s)&&(s=~~s)}if(m>=b){if(r&&"add"===t.op&&s>p.length)throw new f("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",n,t,e);let a=y[t.op].call(t,p,s,e);if(!1===a.test)throw new f("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return a}}else if(m>=b){let r=g[t.op].call(t,p,s,e);if(!1===r.test)throw new f("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return r}if(p=p[s],r&&m0)throw new f('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);else if(("move"===e.op||"copy"===e.op)&&"string"!=typeof e.from)throw new f("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);else if(("add"===e.op||"replace"===e.op||"test"===e.op)&&void 0===e.value)throw new f("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);else if(("add"===e.op||"replace"===e.op||"test"===e.op)&&h(e.value))throw new f("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);else if(r){if("add"==e.op){var i=e.path.split("/").length,n=a.split("/").length;if(i!==n+1&&i!==n)throw new f("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if("replace"===e.op||"remove"===e.op||"_get"===e.op){if(e.path!==a)throw new f("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if("move"===e.op||"copy"===e.op){var s=E([{op:"_get",path:e.from,value:void 0}],r);if(s&&"OPERATION_PATH_UNRESOLVABLE"===s.name)throw new f("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}}else throw new f("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,r)}function E(e,t,r){try{if(!Array.isArray(e))throw new f("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)w(o(t),o(e),r||!0);else{r=r||O;for(var a=0;a=0;d--){var p=c[d],f=e[p];if(n(t,p)&&(void 0!==t[p]||void 0===f||!1!==Array.isArray(t))){var m=t[p];"object"==typeof f&&null!=f&&"object"==typeof m&&null!=m&&Array.isArray(f)===Array.isArray(m)?S(f,m,r,a+"/"+u(p),i):f!==m&&(i&&r.push({op:"test",path:a+"/"+u(p),value:o(f)}),r.push({op:"replace",path:a+"/"+u(p),value:o(m)}))}else Array.isArray(e)===Array.isArray(t)?(i&&r.push({op:"test",path:a+"/"+u(p),value:o(f)}),r.push({op:"remove",path:a+"/"+u(p)}),h=!0):(i&&r.push({op:"test",path:a,value:e}),r.push({op:"replace",path:a,value:t}))}if(h||l.length!=c.length)for(var d=0;d{"use strict";var t=Object.prototype.hasOwnProperty,r="~";function a(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function n(e,t,a,n,s){if("function"!=typeof a)throw TypeError("The listener must be a function");var o=new i(a,n||e,s),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function s(e,t){0==--e._eventsCount?e._events=new a:delete e._events[t]}function o(){this._events=new a,this._eventsCount=0}Object.create&&(a.prototype=Object.create(null),new a().__proto__||(r=!1)),o.prototype.eventNames=function(){var e,a,i=[];if(0===this._eventsCount)return i;for(a in e=this._events)t.call(e,a)&&i.push(r?a.slice(1):a);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},o.prototype.listeners=function(e){var t=r?r+e:e,a=this._events[t];if(!a)return[];if(a.fn)return[a.fn];for(var i=0,n=a.length,s=Array(n);i{"use strict";r.d(t,{Kj:()=>a.Kj,gk:()=>a.gk});var a=r(53909)},83930:e=>{let t=/^[0-9]+$/,r=(e,r)=>{let a=t.test(e),i=t.test(r);return a&&i&&(e*=1,r*=1),e===r?0:a&&!i?-1:i&&!a?1:er(t,e);e.exports={compareIdentifiers:r,rcompareIdentifiers:a}},84123:(e,t,r)=>{"use strict";e=r.nmd(e);let a=10,i=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,n=(e=0)=>(t,r,a)=>`\u001B[${38+e};2;${t};${r};${a}m`;Object.defineProperty(e,"exports",{enumerable:!0,get:function(){let e=new Map,t={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]}};for(let[r,a]of(t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright,Object.entries(t))){for(let[r,i]of Object.entries(a))t[r]={open:`\u001B[${i[0]}m`,close:`\u001B[${i[1]}m`},a[r]=t[r],e.set(i[0],i[1]);Object.defineProperty(t,r,{value:a,enumerable:!1})}return Object.defineProperty(t,"codes",{value:e,enumerable:!1}),t.color.close="\x1b[39m",t.bgColor.close="\x1b[49m",t.color.ansi256=i(),t.color.ansi16m=n(),t.bgColor.ansi256=i(a),t.bgColor.ansi16m=n(a),Object.defineProperties(t,{rgbToAnsi256:{value:(e,t,r)=>e===t&&t===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(r/255*5),enumerable:!1},hexToRgb:{value:e=>{let t=/(?[a-f\d]{6}|[a-f\d]{3})/i.exec(e.toString(16));if(!t)return[0,0,0];let{colorString:r}=t.groups;3===r.length&&(r=r.split("").map(e=>e+e).join(""));let a=Number.parseInt(r,16);return[a>>16&255,a>>8&255,255&a]},enumerable:!1},hexToAnsi256:{value:e=>t.rgbToAnsi256(...t.hexToRgb(e)),enumerable:!1}}),t}})},84807:e=>{"use strict";let t=1114112;class r extends Error{constructor(e,t,a){super("[ParserError] "+e,t,a),this.name="ParserError",this.code="ParserError",Error.captureStackTrace&&Error.captureStackTrace(this,r)}}class a{constructor(e){this.parser=e,this.buf="",this.returned=null,this.result=null,this.resultTable=null,this.resultArr=null}}class i{constructor(){this.pos=0,this.col=0,this.line=0,this.obj={},this.ctx=this.obj,this.stack=[],this._buf="",this.char=null,this.ii=0,this.state=new a(this.parseStart)}parse(e){let t;if(0!==e.length&&null!=e.length){for(this._buf=String(e),this.ii=-1,this.char=-1;!1===t||this.nextChar();)t=this.runOne();this._buf=null}}nextChar(){return 10===this.char&&(++this.line,this.col=-1),++this.ii,this.char=this._buf.codePointAt(this.ii),++this.pos,++this.col,this.haveBuffer()}haveBuffer(){return this.ii{e.exports=r(90342)},85560:e=>{"use strict";let t=/[\p{Lu}]/u,r=/[\p{Ll}]/u,a=/^[\p{Lu}](?![\p{Lu}])/gu,i=/([\p{Alpha}\p{N}_]|$)/u,n=/[_.\- ]+/,s=RegExp("^"+n.source),o=RegExp(n.source+i.source,"gu"),l=RegExp("\\d+"+i.source,"gu"),u=(e,a,i)=>{let n=!1,s=!1,o=!1;for(let l=0;l(a.lastIndex=0,e.replace(a,e=>t(e))),h=(e,t)=>(o.lastIndex=0,l.lastIndex=0,e.replace(o,(e,r)=>t(r)).replace(l,e=>t(e))),d=(e,t)=>{if(!("string"==typeof e||Array.isArray(e)))throw TypeError("Expected the input to be `string | string[]`");if(t={pascalCase:!1,preserveConsecutiveUppercase:!1,...t},0===(e=Array.isArray(e)?e.map(e=>e.trim()).filter(e=>e.length).join("-"):e.trim()).length)return"";let r=!1===t.locale?e=>e.toLowerCase():e=>e.toLocaleLowerCase(t.locale),a=!1===t.locale?e=>e.toUpperCase():e=>e.toLocaleUpperCase(t.locale);return 1===e.length?t.pascalCase?a(e):r(e):(e!==r(e)&&(e=u(e,r,a)),e=e.replace(s,""),e=t.preserveConsecutiveUppercase?c(e,r):r(e),t.pascalCase&&(e=a(e.charAt(0))+e.slice(1)),h(e,a))};e.exports=d,e.exports.default=d},85670:(e,t,r)=>{let a=r(42870);e.exports=(e,t)=>new a(e,t).set.map(e=>e.map(e=>e.value).join(" ").trim().split(" "))},87096:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";let _custom;module.exports=makeParserClass(__webpack_require__(84807)),module.exports.makeParserClass=makeParserClass;class TomlError extends Error{constructor(e){super(e),this.name="TomlError",Error.captureStackTrace&&Error.captureStackTrace(this,TomlError),this.fromTOML=!0,this.wrapped=null}}TomlError.wrap=e=>{let t=new TomlError(e.message);return t.code=e.code,t.wrapped=e,t},module.exports.TomlError=TomlError;let createDateTime=__webpack_require__(5890),createDateTimeFloat=__webpack_require__(99189),createDate=__webpack_require__(88143),createTime=__webpack_require__(76374),CTRL_I=9,CTRL_J=10,CTRL_M=13,CTRL_CHAR_BOUNDARY=31,CHAR_SP=32,CHAR_QUOT=34,CHAR_NUM=35,CHAR_APOS=39,CHAR_PLUS=43,CHAR_COMMA=44,CHAR_HYPHEN=45,CHAR_PERIOD=46,CHAR_0=48,CHAR_1=49,CHAR_7=55,CHAR_9=57,CHAR_COLON=58,CHAR_EQUALS=61,CHAR_A=65,CHAR_E=69,CHAR_F=70,CHAR_T=84,CHAR_U=85,CHAR_Z=90,CHAR_LOWBAR=95,CHAR_a=97,CHAR_b=98,CHAR_e=101,CHAR_f=102,CHAR_i=105,CHAR_l=108,CHAR_n=110,CHAR_o=111,CHAR_r=114,CHAR_s=115,CHAR_t=116,CHAR_u=117,CHAR_x=120,CHAR_z=122,CHAR_LCUB=123,CHAR_RCUB=125,CHAR_LSQB=91,CHAR_BSOL=92,CHAR_RSQB=93,CHAR_DEL=127,SURROGATE_FIRST=55296,SURROGATE_LAST=57343,escapes={[CHAR_b]:"\b",[CHAR_t]:" ",[CHAR_n]:"\n",[CHAR_f]:"\f",[CHAR_r]:"\r",[CHAR_QUOT]:'"',[CHAR_BSOL]:"\\"};function isDigit(e){return e>=CHAR_0&&e<=CHAR_9}function isHexit(e){return e>=CHAR_A&&e<=CHAR_F||e>=CHAR_a&&e<=CHAR_f||e>=CHAR_0&&e<=CHAR_9}function isBit(e){return e===CHAR_1||e===CHAR_0}function isOctit(e){return e>=CHAR_0&&e<=CHAR_7}function isAlphaNumQuoteHyphen(e){return e>=CHAR_A&&e<=CHAR_Z||e>=CHAR_a&&e<=CHAR_z||e>=CHAR_0&&e<=CHAR_9||e===CHAR_APOS||e===CHAR_QUOT||e===CHAR_LOWBAR||e===CHAR_HYPHEN}function isAlphaNumHyphen(e){return e>=CHAR_A&&e<=CHAR_Z||e>=CHAR_a&&e<=CHAR_z||e>=CHAR_0&&e<=CHAR_9||e===CHAR_LOWBAR||e===CHAR_HYPHEN}let _type=Symbol("type"),_declared=Symbol("declared"),hasOwnProperty=Object.prototype.hasOwnProperty,defineProperty=Object.defineProperty,descriptor={configurable:!0,enumerable:!0,writable:!0,value:void 0};function hasKey(e,t){return!!hasOwnProperty.call(e,t)||("__proto__"===t&&defineProperty(e,"__proto__",descriptor),!1)}let INLINE_TABLE=Symbol("inline-table");function InlineTable(){return Object.defineProperties({},{[_type]:{value:INLINE_TABLE}})}function isInlineTable(e){return null!==e&&"object"==typeof e&&e[_type]===INLINE_TABLE}let TABLE=Symbol("table");function Table(){return Object.defineProperties({},{[_type]:{value:TABLE},[_declared]:{value:!1,writable:!0}})}function isTable(e){return null!==e&&"object"==typeof e&&e[_type]===TABLE}let _contentType=Symbol("content-type"),INLINE_LIST=Symbol("inline-list");function InlineList(e){return Object.defineProperties([],{[_type]:{value:INLINE_LIST},[_contentType]:{value:e}})}function isInlineList(e){return null!==e&&"object"==typeof e&&e[_type]===INLINE_LIST}let LIST=Symbol("list");function List(){return Object.defineProperties([],{[_type]:{value:LIST}})}function isList(e){return null!==e&&"object"==typeof e&&e[_type]===LIST}try{let utilInspect=eval("require('util').inspect");_custom=utilInspect.custom}catch(_){}let _inspect=_custom||"inspect";class BoxedBigInt{constructor(e){try{this.value=__webpack_require__.g.BigInt.asIntN(64,e)}catch(e){this.value=null}Object.defineProperty(this,_type,{value:INTEGER})}isNaN(){return null===this.value}toString(){return String(this.value)}[_inspect](){return`[BigInt: ${this.toString()}]}`}valueOf(){return this.value}}let INTEGER=Symbol("integer");function Integer(e){let t=Number(e);return(Object.is(t,-0)&&(t=0),__webpack_require__.g.BigInt&&!Number.isSafeInteger(t))?new BoxedBigInt(e):Object.defineProperties(new Number(t),{isNaN:{value:function(){return isNaN(this)}},[_type]:{value:INTEGER},[_inspect]:{value:()=>`[Integer: ${e}]`}})}function isInteger(e){return null!==e&&"object"==typeof e&&e[_type]===INTEGER}let FLOAT=Symbol("float");function Float(e){return Object.defineProperties(new Number(e),{[_type]:{value:FLOAT},[_inspect]:{value:()=>`[Float: ${e}]`}})}function isFloat(e){return null!==e&&"object"==typeof e&&e[_type]===FLOAT}function tomlType(e){let t=typeof e;if("object"===t){if(null===e)return"null";if(e instanceof Date)return"datetime";if(_type in e)switch(e[_type]){case INLINE_TABLE:return"inline-table";case INLINE_LIST:return"inline-list";case TABLE:return"table";case LIST:return"list";case FLOAT:return"float";case INTEGER:return"integer"}}return t}function makeParserClass(e){class t extends e{constructor(){super(),this.ctx=this.obj=Table()}atEndOfWord(){return this.char===CHAR_NUM||this.char===CTRL_I||this.char===CHAR_SP||this.atEndOfLine()}atEndOfLine(){return this.char===e.END||this.char===CTRL_J||this.char===CTRL_M}parseStart(){if(this.char===e.END)return null;if(this.char===CHAR_LSQB)return this.call(this.parseTableOrList);if(this.char===CHAR_NUM)return this.call(this.parseComment);if(this.char===CTRL_J||this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M)return null;if(isAlphaNumQuoteHyphen(this.char))return this.callNow(this.parseAssignStatement);else throw this.error(new TomlError(`Unknown character "${this.char}"`))}parseWhitespaceToEOL(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M)return null;if(this.char===CHAR_NUM)return this.goto(this.parseComment);if(this.char===e.END||this.char===CTRL_J)return this.return();throw this.error(new TomlError("Unexpected character, expected only whitespace or comments till end of line"))}parseAssignStatement(){return this.callNow(this.parseAssign,this.recordAssignStatement)}recordAssignStatement(e){let t=this.ctx,r=e.key.pop();for(let r of e.key){if(hasKey(t,r)&&(!isTable(t[r])||t[r][_declared]))throw this.error(new TomlError("Can't redefine existing key"));t=t[r]=t[r]||Table()}if(hasKey(t,r))throw this.error(new TomlError("Can't redefine existing key"));return isInteger(e.value)||isFloat(e.value)?t[r]=e.value.valueOf():t[r]=e.value,this.goto(this.parseWhitespaceToEOL)}parseAssign(){return this.callNow(this.parseKeyword,this.recordAssignKeyword)}recordAssignKeyword(e){return this.state.resultTable?this.state.resultTable.push(e):this.state.resultTable=[e],this.goto(this.parseAssignKeywordPreDot)}parseAssignKeywordPreDot(){return this.char===CHAR_PERIOD?this.next(this.parseAssignKeywordPostDot):this.char!==CHAR_SP&&this.char!==CTRL_I?this.goto(this.parseAssignEqual):void 0}parseAssignKeywordPostDot(){if(this.char!==CHAR_SP&&this.char!==CTRL_I)return this.callNow(this.parseKeyword,this.recordAssignKeyword)}parseAssignEqual(){if(this.char===CHAR_EQUALS)return this.next(this.parseAssignPreValue);throw this.error(new TomlError('Invalid character, expected "="'))}parseAssignPreValue(){return this.char===CHAR_SP||this.char===CTRL_I?null:this.callNow(this.parseValue,this.recordAssignValue)}recordAssignValue(e){return this.returnNow({key:this.state.resultTable,value:e})}parseComment(){do if(this.char===e.END||this.char===CTRL_J)return this.return();while(this.nextChar())}parseTableOrList(){if(this.char!==CHAR_LSQB)return this.goto(this.parseTable);this.next(this.parseList)}parseTable(){return this.ctx=this.obj,this.goto(this.parseTableNext)}parseTableNext(){return this.char===CHAR_SP||this.char===CTRL_I?null:this.callNow(this.parseKeyword,this.parseTableMore)}parseTableMore(e){if(this.char===CHAR_SP||this.char===CTRL_I)return null;if(this.char===CHAR_RSQB){if(hasKey(this.ctx,e)&&(!isTable(this.ctx[e])||this.ctx[e][_declared]))throw this.error(new TomlError("Can't redefine existing key"));return this.ctx=this.ctx[e]=this.ctx[e]||Table(),this.ctx[_declared]=!0,this.next(this.parseWhitespaceToEOL)}if(this.char===CHAR_PERIOD){if(hasKey(this.ctx,e)){if(isTable(this.ctx[e]))this.ctx=this.ctx[e];else if(isList(this.ctx[e]))this.ctx=this.ctx[e][this.ctx[e].length-1];else throw this.error(new TomlError("Can't redefine existing key"))}else this.ctx=this.ctx[e]=Table();return this.next(this.parseTableNext)}throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}parseList(){return this.ctx=this.obj,this.goto(this.parseListNext)}parseListNext(){return this.char===CHAR_SP||this.char===CTRL_I?null:this.callNow(this.parseKeyword,this.parseListMore)}parseListMore(e){if(this.char===CHAR_SP||this.char===CTRL_I)return null;if(this.char===CHAR_RSQB){if(hasKey(this.ctx,e)||(this.ctx[e]=List()),isInlineList(this.ctx[e]))throw this.error(new TomlError("Can't extend an inline array"));if(isList(this.ctx[e])){let t=Table();this.ctx[e].push(t),this.ctx=t}else throw this.error(new TomlError("Can't redefine an existing key"));return this.next(this.parseListEnd)}if(this.char===CHAR_PERIOD){if(hasKey(this.ctx,e)){if(isInlineList(this.ctx[e]))throw this.error(new TomlError("Can't extend an inline array"));if(isInlineTable(this.ctx[e]))throw this.error(new TomlError("Can't extend an inline table"));else if(isList(this.ctx[e]))this.ctx=this.ctx[e][this.ctx[e].length-1];else if(isTable(this.ctx[e]))this.ctx=this.ctx[e];else throw this.error(new TomlError("Can't redefine an existing key"))}else this.ctx=this.ctx[e]=Table();return this.next(this.parseListNext)}throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}parseListEnd(e){if(this.char===CHAR_RSQB)return this.next(this.parseWhitespaceToEOL);throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}parseValue(){if(this.char===e.END)throw this.error(new TomlError("Key without value"));if(this.char===CHAR_QUOT)return this.next(this.parseDoubleString);if(this.char===CHAR_APOS)return this.next(this.parseSingleString);if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS)return this.goto(this.parseNumberSign);if(this.char===CHAR_i)return this.next(this.parseInf);if(this.char===CHAR_n)return this.next(this.parseNan);if(isDigit(this.char))return this.goto(this.parseNumberOrDateTime);else if(this.char===CHAR_t||this.char===CHAR_f)return this.goto(this.parseBoolean);else if(this.char===CHAR_LSQB)return this.call(this.parseInlineList,this.recordValue);else if(this.char===CHAR_LCUB)return this.call(this.parseInlineTable,this.recordValue);else throw this.error(new TomlError("Unexpected character, expecting string, number, datetime, boolean, inline array or inline table"))}recordValue(e){return this.returnNow(e)}parseInf(){if(this.char===CHAR_n)return this.next(this.parseInf2);throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'))}parseInf2(){if(this.char===CHAR_f)return"-"===this.state.buf?this.return(-1/0):this.return(1/0);throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'))}parseNan(){if(this.char===CHAR_a)return this.next(this.parseNan2);throw this.error(new TomlError('Unexpected character, expected "nan"'))}parseNan2(){if(this.char===CHAR_n)return this.return(NaN);throw this.error(new TomlError('Unexpected character, expected "nan"'))}parseKeyword(){return this.char===CHAR_QUOT?this.next(this.parseBasicString):this.char===CHAR_APOS?this.next(this.parseLiteralString):this.goto(this.parseBareKey)}parseBareKey(){do{if(this.char===e.END)throw this.error(new TomlError("Key ended without value"));if(isAlphaNumHyphen(this.char))this.consume();else if(0!==this.state.buf.length)return this.returnNow();else throw this.error(new TomlError("Empty bare keys are not allowed"))}while(this.nextChar())}parseSingleString(){return this.char===CHAR_APOS?this.next(this.parseLiteralMultiStringMaybe):this.goto(this.parseLiteralString)}parseLiteralString(){do{if(this.char===CHAR_APOS)return this.return();if(this.atEndOfLine())throw this.error(new TomlError("Unterminated string"));if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I)throw this.errorControlCharInString();else this.consume()}while(this.nextChar())}parseLiteralMultiStringMaybe(){return this.char===CHAR_APOS?this.next(this.parseLiteralMultiString):this.returnNow()}parseLiteralMultiString(){return this.char===CTRL_M?null:this.char===CTRL_J?this.next(this.parseLiteralMultiStringContent):this.goto(this.parseLiteralMultiStringContent)}parseLiteralMultiStringContent(){do{if(this.char===CHAR_APOS)return this.next(this.parseLiteralMultiEnd);if(this.char===e.END)throw this.error(new TomlError("Unterminated multi-line string"));if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I&&this.char!==CTRL_J&&this.char!==CTRL_M)throw this.errorControlCharInString();else this.consume()}while(this.nextChar())}parseLiteralMultiEnd(){return this.char===CHAR_APOS?this.next(this.parseLiteralMultiEnd2):(this.state.buf+="'",this.goto(this.parseLiteralMultiStringContent))}parseLiteralMultiEnd2(){return this.char===CHAR_APOS?this.return():(this.state.buf+="''",this.goto(this.parseLiteralMultiStringContent))}parseDoubleString(){return this.char===CHAR_QUOT?this.next(this.parseMultiStringMaybe):this.goto(this.parseBasicString)}parseBasicString(){do{if(this.char===CHAR_BSOL)return this.call(this.parseEscape,this.recordEscapeReplacement);if(this.char===CHAR_QUOT)return this.return();if(this.atEndOfLine())throw this.error(new TomlError("Unterminated string"));else if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I)throw this.errorControlCharInString();else this.consume()}while(this.nextChar())}recordEscapeReplacement(e){return this.state.buf+=e,this.goto(this.parseBasicString)}parseMultiStringMaybe(){return this.char===CHAR_QUOT?this.next(this.parseMultiString):this.returnNow()}parseMultiString(){return this.char===CTRL_M?null:this.char===CTRL_J?this.next(this.parseMultiStringContent):this.goto(this.parseMultiStringContent)}parseMultiStringContent(){do{if(this.char===CHAR_BSOL)return this.call(this.parseMultiEscape,this.recordMultiEscapeReplacement);if(this.char===CHAR_QUOT)return this.next(this.parseMultiEnd);if(this.char===e.END)throw this.error(new TomlError("Unterminated multi-line string"));else if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I&&this.char!==CTRL_J&&this.char!==CTRL_M)throw this.errorControlCharInString();else this.consume()}while(this.nextChar())}errorControlCharInString(){let e="\\u00";return this.char<16&&(e+="0"),e+=this.char.toString(16),this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${e} instead`))}recordMultiEscapeReplacement(e){return this.state.buf+=e,this.goto(this.parseMultiStringContent)}parseMultiEnd(){return this.char===CHAR_QUOT?this.next(this.parseMultiEnd2):(this.state.buf+='"',this.goto(this.parseMultiStringContent))}parseMultiEnd2(){return this.char===CHAR_QUOT?this.return():(this.state.buf+='""',this.goto(this.parseMultiStringContent))}parseMultiEscape(){return this.char===CTRL_M||this.char===CTRL_J?this.next(this.parseMultiTrim):this.char===CHAR_SP||this.char===CTRL_I?this.next(this.parsePreMultiTrim):this.goto(this.parseEscape)}parsePreMultiTrim(){if(this.char===CHAR_SP||this.char===CTRL_I)return null;if(this.char===CTRL_M||this.char===CTRL_J)return this.next(this.parseMultiTrim);throw this.error(new TomlError("Can't escape whitespace"))}parseMultiTrim(){return this.char===CTRL_J||this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M?null:this.returnNow()}parseEscape(){if(this.char in escapes)return this.return(escapes[this.char]);if(this.char===CHAR_u)return this.call(this.parseSmallUnicode,this.parseUnicodeReturn);if(this.char===CHAR_U)return this.call(this.parseLargeUnicode,this.parseUnicodeReturn);throw this.error(new TomlError("Unknown escape character: "+this.char))}parseUnicodeReturn(e){try{let t=parseInt(e,16);if(t>=SURROGATE_FIRST&&t<=SURROGATE_LAST)throw this.error(new TomlError("Invalid unicode, character in range 0xD800 - 0xDFFF is reserved"));return this.returnNow(String.fromCodePoint(t))}catch(e){throw this.error(TomlError.wrap(e))}}parseSmallUnicode(){if(isHexit(this.char)){if(this.consume(),this.state.buf.length>=4)return this.return()}else throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"))}parseLargeUnicode(){if(isHexit(this.char)){if(this.consume(),this.state.buf.length>=8)return this.return()}else throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"))}parseNumberSign(){return this.consume(),this.next(this.parseMaybeSignedInfOrNan)}parseMaybeSignedInfOrNan(){return this.char===CHAR_i?this.next(this.parseInf):this.char===CHAR_n?this.next(this.parseNan):this.callNow(this.parseNoUnder,this.parseNumberIntegerStart)}parseNumberIntegerStart(){return this.char===CHAR_0?(this.consume(),this.next(this.parseNumberIntegerExponentOrDecimal)):this.goto(this.parseNumberInteger)}parseNumberIntegerExponentOrDecimal(){return this.char===CHAR_PERIOD?(this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat)):this.char===CHAR_E||this.char===CHAR_e?(this.consume(),this.next(this.parseNumberExponentSign)):this.returnNow(Integer(this.state.buf))}parseNumberInteger(){if(isDigit(this.char))this.consume();else{if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnder);if(this.char===CHAR_E||this.char===CHAR_e)return this.consume(),this.next(this.parseNumberExponentSign);if(this.char===CHAR_PERIOD)return this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat);let e=Integer(this.state.buf);if(!e.isNaN())return this.returnNow(e);throw this.error(new TomlError("Invalid number"))}}parseNoUnder(){if(this.char===CHAR_LOWBAR||this.char===CHAR_PERIOD||this.char===CHAR_E||this.char===CHAR_e)throw this.error(new TomlError("Unexpected character, expected digit"));if(this.atEndOfWord())throw this.error(new TomlError("Incomplete number"));return this.returnNow()}parseNoUnderHexOctBinLiteral(){if(this.char===CHAR_LOWBAR||this.char===CHAR_PERIOD)throw this.error(new TomlError("Unexpected character, expected digit"));if(this.atEndOfWord())throw this.error(new TomlError("Incomplete number"));return this.returnNow()}parseNumberFloat(){if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnder,this.parseNumberFloat);if(isDigit(this.char))this.consume();else if(this.char===CHAR_E||this.char===CHAR_e)return this.consume(),this.next(this.parseNumberExponentSign);else return this.returnNow(Float(this.state.buf))}parseNumberExponentSign(){if(isDigit(this.char))return this.goto(this.parseNumberExponent);if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS)this.consume(),this.call(this.parseNoUnder,this.parseNumberExponent);else throw this.error(new TomlError("Unexpected character, expected -, + or digit"))}parseNumberExponent(){if(isDigit(this.char))this.consume();else if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnder);else return this.returnNow(Float(this.state.buf))}parseNumberOrDateTime(){return this.char===CHAR_0?(this.consume(),this.next(this.parseNumberBaseOrDateTime)):this.goto(this.parseNumberOrDateTimeOnly)}parseNumberOrDateTimeOnly(){if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnder,this.parseNumberInteger);if(isDigit(this.char))this.consume(),this.state.buf.length>4&&this.next(this.parseNumberInteger);else if(this.char===CHAR_E||this.char===CHAR_e)return this.consume(),this.next(this.parseNumberExponentSign);else if(this.char===CHAR_PERIOD)return this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat);else if(this.char===CHAR_HYPHEN)return this.goto(this.parseDateTime);else if(this.char===CHAR_COLON)return this.goto(this.parseOnlyTimeHour);else return this.returnNow(Integer(this.state.buf))}parseDateTimeOnly(){if(this.state.buf.length<4){if(isDigit(this.char))return this.consume();if(this.char===CHAR_COLON)return this.goto(this.parseOnlyTimeHour);throw this.error(new TomlError("Expected digit while parsing year part of a date"))}if(this.char===CHAR_HYPHEN)return this.goto(this.parseDateTime);throw this.error(new TomlError("Expected hyphen (-) while parsing year part of date"))}parseNumberBaseOrDateTime(){if(this.char===CHAR_b)return this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerBin);if(this.char===CHAR_o)return this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerOct);if(this.char===CHAR_x)return this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerHex);if(this.char===CHAR_PERIOD)return this.goto(this.parseNumberInteger);if(isDigit(this.char))return this.goto(this.parseDateTimeOnly);else return this.returnNow(Integer(this.state.buf))}parseIntegerHex(){if(isHexit(this.char))this.consume();else{if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnderHexOctBinLiteral);let e=Integer(this.state.buf);if(!e.isNaN())return this.returnNow(e);throw this.error(new TomlError("Invalid number"))}}parseIntegerOct(){if(isOctit(this.char))this.consume();else{if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnderHexOctBinLiteral);let e=Integer(this.state.buf);if(!e.isNaN())return this.returnNow(e);throw this.error(new TomlError("Invalid number"))}}parseIntegerBin(){if(isBit(this.char))this.consume();else{if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnderHexOctBinLiteral);let e=Integer(this.state.buf);if(!e.isNaN())return this.returnNow(e);throw this.error(new TomlError("Invalid number"))}}parseDateTime(){if(this.state.buf.length<4)throw this.error(new TomlError("Years less than 1000 must be zero padded to four characters"));return this.state.result=this.state.buf,this.state.buf="",this.next(this.parseDateMonth)}parseDateMonth(){if(this.char===CHAR_HYPHEN){if(this.state.buf.length<2)throw this.error(new TomlError("Months less than 10 must be zero padded to two characters"));return this.state.result+="-"+this.state.buf,this.state.buf="",this.next(this.parseDateDay)}if(isDigit(this.char))this.consume();else throw this.error(new TomlError("Incomplete datetime"))}parseDateDay(){if(this.char===CHAR_T||this.char===CHAR_SP){if(this.state.buf.length<2)throw this.error(new TomlError("Days less than 10 must be zero padded to two characters"));return this.state.result+="-"+this.state.buf,this.state.buf="",this.next(this.parseStartTimeHour)}if(this.atEndOfWord())return this.returnNow(createDate(this.state.result+"-"+this.state.buf));if(isDigit(this.char))this.consume();else throw this.error(new TomlError("Incomplete datetime"))}parseStartTimeHour(){return this.atEndOfWord()?this.returnNow(createDate(this.state.result)):this.goto(this.parseTimeHour)}parseTimeHour(){if(this.char===CHAR_COLON){if(this.state.buf.length<2)throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"));return this.state.result+="T"+this.state.buf,this.state.buf="",this.next(this.parseTimeMin)}if(isDigit(this.char))this.consume();else throw this.error(new TomlError("Incomplete datetime"))}parseTimeMin(){if(this.state.buf.length<2&&isDigit(this.char))this.consume();else if(2===this.state.buf.length&&this.char===CHAR_COLON)return this.state.result+=":"+this.state.buf,this.state.buf="",this.next(this.parseTimeSec);else throw this.error(new TomlError("Incomplete datetime"))}parseTimeSec(){if(isDigit(this.char)){if(this.consume(),2===this.state.buf.length)return this.state.result+=":"+this.state.buf,this.state.buf="",this.next(this.parseTimeZoneOrFraction)}else throw this.error(new TomlError("Incomplete datetime"))}parseOnlyTimeHour(){if(this.char===CHAR_COLON){if(this.state.buf.length<2)throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"));return this.state.result=this.state.buf,this.state.buf="",this.next(this.parseOnlyTimeMin)}throw this.error(new TomlError("Incomplete time"))}parseOnlyTimeMin(){if(this.state.buf.length<2&&isDigit(this.char))this.consume();else if(2===this.state.buf.length&&this.char===CHAR_COLON)return this.state.result+=":"+this.state.buf,this.state.buf="",this.next(this.parseOnlyTimeSec);else throw this.error(new TomlError("Incomplete time"))}parseOnlyTimeSec(){if(isDigit(this.char)){if(this.consume(),2===this.state.buf.length)return this.next(this.parseOnlyTimeFractionMaybe)}else throw this.error(new TomlError("Incomplete time"))}parseOnlyTimeFractionMaybe(){if(this.state.result+=":"+this.state.buf,this.char!==CHAR_PERIOD)return this.return(createTime(this.state.result));this.state.buf="",this.next(this.parseOnlyTimeFraction)}parseOnlyTimeFraction(){if(isDigit(this.char))this.consume();else if(this.atEndOfWord()){if(0===this.state.buf.length)throw this.error(new TomlError("Expected digit in milliseconds"));return this.returnNow(createTime(this.state.result+"."+this.state.buf))}else throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}parseTimeZoneOrFraction(){if(this.char===CHAR_PERIOD)this.consume(),this.next(this.parseDateTimeFraction);else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS)this.consume(),this.next(this.parseTimeZoneHour);else if(this.char===CHAR_Z)return this.consume(),this.return(createDateTime(this.state.result+this.state.buf));else if(this.atEndOfWord())return this.returnNow(createDateTimeFloat(this.state.result+this.state.buf));else throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}parseDateTimeFraction(){if(isDigit(this.char))this.consume();else if(1===this.state.buf.length)throw this.error(new TomlError("Expected digit in milliseconds"));else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS)this.consume(),this.next(this.parseTimeZoneHour);else if(this.char===CHAR_Z)return this.consume(),this.return(createDateTime(this.state.result+this.state.buf));else if(this.atEndOfWord())return this.returnNow(createDateTimeFloat(this.state.result+this.state.buf));else throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}parseTimeZoneHour(){if(isDigit(this.char)){if(this.consume(),/\d\d$/.test(this.state.buf))return this.next(this.parseTimeZoneSep)}else throw this.error(new TomlError("Unexpected character in datetime, expected digit"))}parseTimeZoneSep(){if(this.char===CHAR_COLON)this.consume(),this.next(this.parseTimeZoneMin);else throw this.error(new TomlError("Unexpected character in datetime, expected colon"))}parseTimeZoneMin(){if(isDigit(this.char)){if(this.consume(),/\d\d$/.test(this.state.buf))return this.return(createDateTime(this.state.result+this.state.buf))}else throw this.error(new TomlError("Unexpected character in datetime, expected digit"))}parseBoolean(){return this.char===CHAR_t?(this.consume(),this.next(this.parseTrue_r)):this.char===CHAR_f?(this.consume(),this.next(this.parseFalse_a)):void 0}parseTrue_r(){if(this.char===CHAR_r)return this.consume(),this.next(this.parseTrue_u);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseTrue_u(){if(this.char===CHAR_u)return this.consume(),this.next(this.parseTrue_e);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseTrue_e(){if(this.char===CHAR_e)return this.return(!0);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseFalse_a(){if(this.char===CHAR_a)return this.consume(),this.next(this.parseFalse_l);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseFalse_l(){if(this.char===CHAR_l)return this.consume(),this.next(this.parseFalse_s);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseFalse_s(){if(this.char===CHAR_s)return this.consume(),this.next(this.parseFalse_e);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseFalse_e(){if(this.char===CHAR_e)return this.return(!1);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseInlineList(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M||this.char===CTRL_J)return null;if(this.char===e.END)throw this.error(new TomlError("Unterminated inline array"));return this.char===CHAR_NUM?this.call(this.parseComment):this.char===CHAR_RSQB?this.return(this.state.resultArr||InlineList()):this.callNow(this.parseValue,this.recordInlineListValue)}recordInlineListValue(e){if(this.state.resultArr){let t=this.state.resultArr[_contentType],r=tomlType(e);if(t!==r)throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${t} and ${r}`))}else this.state.resultArr=InlineList(tomlType(e));return isFloat(e)||isInteger(e)?this.state.resultArr.push(e.valueOf()):this.state.resultArr.push(e),this.goto(this.parseInlineListNext)}parseInlineListNext(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M||this.char===CTRL_J)return null;if(this.char===CHAR_NUM)return this.call(this.parseComment);if(this.char===CHAR_COMMA)return this.next(this.parseInlineList);if(this.char===CHAR_RSQB)return this.goto(this.parseInlineList);throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"))}parseInlineTable(){if(this.char===CHAR_SP||this.char===CTRL_I)return null;if(this.char===e.END||this.char===CHAR_NUM||this.char===CTRL_J||this.char===CTRL_M)throw this.error(new TomlError("Unterminated inline array"));return this.char===CHAR_RCUB?this.return(this.state.resultTable||InlineTable()):(this.state.resultTable||(this.state.resultTable=InlineTable()),this.callNow(this.parseAssign,this.recordInlineTableValue))}recordInlineTableValue(e){let t=this.state.resultTable,r=e.key.pop();for(let r of e.key){if(hasKey(t,r)&&(!isTable(t[r])||t[r][_declared]))throw this.error(new TomlError("Can't redefine existing key"));t=t[r]=t[r]||Table()}if(hasKey(t,r))throw this.error(new TomlError("Can't redefine existing key"));return isInteger(e.value)||isFloat(e.value)?t[r]=e.value.valueOf():t[r]=e.value,this.goto(this.parseInlineTableNext)}parseInlineTableNext(){if(this.char===CHAR_SP||this.char===CTRL_I)return null;if(this.char===e.END||this.char===CHAR_NUM||this.char===CTRL_J||this.char===CTRL_M)throw this.error(new TomlError("Unterminated inline array"));if(this.char===CHAR_COMMA)return this.next(this.parseInlineTable);if(this.char===CHAR_RCUB)return this.goto(this.parseInlineTable);throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"))}}return t}},87150:(e,t,r)=>{"use strict";r.d(t,{DS:()=>c,Tr:()=>u,bO:()=>s,gI:()=>o,xW:()=>l});var a=r(92173),i=r(89351),n=r(67146);class s extends ReadableStream{constructor(){super(...arguments),Object.defineProperty(this,"reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{let e=await this.reader.read();if(e.done)return this.reader.releaseLock(),{done:!0,value:void 0};return{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){let e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){let e=this.reader.cancel();this.reader.releaseLock(),await e}throw e}[Symbol.asyncIterator](){return this}async [Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){let t=e.getReader();return new s({start(e){return r();function r(){return t.read().then(({done:t,value:a})=>{if(t){e.close();return}return e.enqueue(a),r()})}},cancel(){t.releaseLock()}})}static fromAsyncGenerator(e){return new s({async pull(t){let{value:r,done:a}=await e.next();a&&t.close(),t.enqueue(r)},async cancel(t){await e.return(t)}})}}function o(e,t=2){let r=Array.from({length:t},()=>[]);return r.map(async function*(t){for(;;)if(0===t.length){let t=await e.next();for(let e of r)e.push(t)}else{if(t[0].done)return;yield t.shift().value}})}function l(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if("string"==typeof e&&"string"==typeof t)return e+t;if("number"==typeof e&&"number"==typeof t)return e+t;if("concat"in e&&"function"==typeof e.concat)return e.concat(t);if("object"==typeof e&&"object"==typeof t){let r={...e};for(let[e,a]of Object.entries(t))e in r&&!Array.isArray(r[e])?r[e]=l(r[e],a):r[e]=a;return r}else throw Error(`Cannot concat ${typeof e} and ${typeof t}`)}class u{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)=>{i.Nx.runWithConfig((0,a.DY)(e.config),async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then(e=>t(void 0),r)},!0)})}async next(...e){return(this.signal?.throwIfAborted(),this.firstResultUsed)?i.Nx.runWithConfig((0,a.DY)(this.config),this.signal?async()=>(0,n.o)(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 c(e,t,r,a,...i){let n=new u({generator:t,startSetup:r,signal:a}),s=await n.setup;return{output:e(n,s,...i),setup:s}}},88143:(e,t,r)=>{"use strict";let a=r(26682),i=r.g.Date;class n extends i{constructor(e){super(e),this.isDate=!0}toISOString(){return`${this.getUTCFullYear()}-${a(2,this.getUTCMonth()+1)}-${a(2,this.getUTCDate())}`}}e.exports=e=>{let t=new n(e);if(!isNaN(t))return t;throw TypeError("Invalid Datetime")}},88193:(e,t,r)=>{let a=r(36053);e.exports=(e,t,r)=>new a(e,r).compare(new a(t,r))},89351:(e,t,r)=>{"use strict";r.d(t,{Nx:()=>c});var a=r(82926),i=r(44768),n=r(77466);class s{getStore(){}run(e,t){return t()}enterWith(e){}}let o=new s,l=Symbol.for("lc:child_config");class u{getInstance(){return(0,i.X0)()??o}getRunnableConfig(){let e=this.getInstance();return e.getStore()?.extra?.[l]}runWithConfig(e,t,r){let s;let o=n.Td._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),u=this.getInstance(),c=u.getStore(),h=o?.getParentRunId(),d=o?.handlers?.find(e=>e?.name==="langchain_tracer");return d&&h?s=d.convertToRunTree(h):r||(s=new a.gk({name:"",tracingEnabled:!1})),s&&(s.extra={...s.extra,[l]:e}),void 0!==c&&void 0!==c[i.hr]&&(void 0===s&&(s={}),s[i.hr]=c[i.hr]),u.run(s,t)}initializeGlobalInstance(e){void 0===(0,i.X0)()&&(0,i.pH)(e)}}let c=new u},89377:(e,t,r)=>{let a=r(36053);e.exports=(e,t,r=!1)=>{if(e instanceof a)return e;try{return new a(e,t)}catch(e){if(!r)return null;throw e}}},90338:(e,t,r)=>{"use strict";r.d(t,{K0:()=>m,Sw:()=>g,ih:()=>b});var a=r(42452),i=r(28809),n=r(41039),s=r(64520),o=r(71151),l=r(76937),u=r(62886),c=r(91356),h=r(27231);function d(e){return(0,i.K)(e)?e:"string"==typeof e.id&&"function"===e.type&&"object"==typeof e.function&&null!==e.function&&"arguments"in e.function&&"string"==typeof e.function.arguments&&"name"in e.function&&"string"==typeof e.function.name?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:"tool_call"}:e}function p(e){return"object"==typeof e&&null!=e&&1===e.lc&&Array.isArray(e.id)&&null!=e.kwargs&&"object"==typeof e.kwargs}function f(e){let t,r;if(p(e)){let a=e.id.at(-1);t="HumanMessage"===a||"HumanMessageChunk"===a?"user":"AIMessage"===a||"AIMessageChunk"===a?"assistant":"SystemMessage"===a||"SystemMessageChunk"===a?"system":"FunctionMessage"===a||"FunctionMessageChunk"===a?"function":"ToolMessage"===a||"ToolMessageChunk"===a?"tool":"unknown",r=e.kwargs}else{let{type:a,...i}=e;t=a,r=i}if("human"===t||"user"===t)return new u.xc(r);if("ai"===t||"assistant"===t){let{tool_calls:e,...t}=r;if(!Array.isArray(e))return new n.Od(r);let a=e.map(d);return new n.Od({...t,tool_calls:a})}if("system"===t)return new c.tn(r);if("developer"===t)return new c.tn({...r,additional_kwargs:{...r.additional_kwargs,__openai_role__:"developer"}});if("tool"===t&&"tool_call_id"in r)return new h.uf({...r,content:r.content,tool_call_id:r.tool_call_id,name:r.name});else throw(0,a.Y)(Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported. Received: ${JSON.stringify(e,null,2)}`),"MESSAGE_COERCION_FAILURE")}function m(e){if("string"==typeof e)return new u.xc(e);if((0,s.ny)(e))return e;if(Array.isArray(e)){let[t,r]=e;return f({type:t,content:r})}if(!(0,s.dp)(e))return f(e);{let{role:t,...r}=e;return f({...r,type:t})}}function g(e,t="Human",r="AI"){let a=[];for(let i of e){let e;if("human"===i._getType())e=t;else if("ai"===i._getType())e=r;else if("system"===i._getType())e="System";else if("function"===i._getType())e="Function";else if("tool"===i._getType())e="Tool";else if("generic"===i._getType())e=i.role;else throw Error(`Got unsupported message type: ${i._getType()}`);let n=i.name?`${i.name}, `:"",s="string"==typeof i.content?i.content:JSON.stringify(i.content,null,2);a.push(`${e}: ${n}${s}`)}return a.join("\n")}function y(e){if(void 0!==e.data)return e;{let t=e;return{type:t.type,data:{content:t.text,role:t.role,name:void 0,tool_call_id:void 0}}}}function b(e){let t=e._getType();if("human"===t)return new u.a7({...e});if("ai"===t){let t={...e};return"tool_calls"in t&&(t={...t,tool_call_chunks:t.tool_calls?.map(e=>({...e,type:"tool_call_chunk",index:void 0,args:JSON.stringify(e.args)}))}),new n.H({...t})}if("system"===t)return new c.uU({...e});if("function"===t)return new l.FK({...e});if(o.cM.isInstance(e))return new o.XU({...e});else throw Error("Unknown message type.")}},90342:(e,t,r)=>{var a=r(29200);t.operation=function(e){return new a(t.timeouts(e),{forever:e&&(e.forever||e.retries===1/0),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})},t.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw Error("minTimeout is greater than maxTimeout");for(var a=[],i=0;i{"use strict";r.d(t,{tn:()=>i,uU:()=>n});var a=r(64520);class i extends a.XQ{static lc_name(){return"SystemMessage"}_getType(){return"system"}}class n extends a.gj{static lc_name(){return"SystemMessageChunk"}_getType(){return"system"}concat(e){return new n({content:(0,a._I)(this.content,e.content),additional_kwargs:(0,a.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,a.ns)(this.response_metadata,e.response_metadata),id:this.id??e.id})}}},92173:(e,t,r)=>{"use strict";r.d(t,{DY:()=>h,SV:()=>o,ZI:()=>u,kJ:()=>s,p_:()=>n,tn:()=>c});var a=r(77466),i=r(89351);let n=25;async function s(e){return a.Td._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function o(...e){let t={};for(let r of e.filter(e=>!!e))for(let e of Object.keys(r))if("metadata"===e)t[e]={...t[e],...r[e]};else if("tags"===e){let a=t[e]??[];t[e]=[...new Set(a.concat(r[e]??[]))]}else if("configurable"===e)t[e]={...t[e],...r[e]};else if("timeout"===e)void 0===t.timeout?t.timeout=r.timeout:void 0!==r.timeout&&(t.timeout=Math.min(t.timeout,r.timeout));else if("signal"===e)void 0===t.signal?t.signal=r.signal:void 0!==r.signal&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,r.signal]):t.signal=r.signal);else if("callbacks"===e){let e=t.callbacks,i=r.callbacks;if(Array.isArray(i)){if(e){if(Array.isArray(e))t.callbacks=e.concat(i);else{let r=e.copy();for(let e of i)r.addHandler((0,a.tW)(e),!0);t.callbacks=r}}else t.callbacks=i}else if(i){if(e){if(Array.isArray(e)){let r=i.copy();for(let t of e)r.addHandler((0,a.tW)(t),!0);t.callbacks=r}else t.callbacks=new a.Td(i._parentRunId,{handlers:e.handlers.concat(i.handlers),inheritableHandlers:e.inheritableHandlers.concat(i.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(i.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(i.inheritableTags))),metadata:{...e.metadata,...i.metadata}})}else t.callbacks=i}}else{let a=e;t[a]=r[a]??t[a]}return t}let l=new Set(["string","number","boolean"]);function u(e){let t=i.Nx.getRunnableConfig(),r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){let{runId:e,runName:a,...i}=t;r=Object.entries(i).reduce((e,[t,r])=>(void 0!==r&&(e[t]=r),e),r)}if(e&&(r=Object.entries(e).reduce((e,[t,r])=>(void 0!==r&&(e[t]=r),e),r)),r?.configurable)for(let e of Object.keys(r.configurable))l.has(typeof r.configurable[e])&&!r.metadata?.[e]&&(r.metadata||(r.metadata={}),r.metadata[e]=r.configurable[e]);if(void 0!==r.timeout){if(r.timeout<=0)throw Error("Timeout must be a positive number");let e=AbortSignal.timeout(r.timeout);void 0!==r.signal?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,e])):r.signal=e,delete r.timeout}return r}function c(e={},{callbacks:t,maxConcurrency:r,recursionLimit:a,runName:i,configurable:n,runId:s}={}){let o=u(e);return void 0!==t&&(delete o.runName,o.callbacks=t),void 0!==a&&(o.recursionLimit=a),void 0!==r&&(o.maxConcurrency=r),void 0!==i&&(o.runName=i),void 0!==n&&(o.configurable={...o.configurable,...n}),void 0!==s&&delete o.runId,o}function h(e){return e?{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal}:void 0}},95132:(e,t,r)=>{let a=r(8044);e.exports=(e,t)=>e.sort((e,r)=>a(r,e,t))},95811:(e,t,r)=>{"use strict";e.exports=n;let a=r(87096),i=r(11813);function n(e){r.g.Buffer&&r.g.Buffer.isBuffer(e)&&(e=e.toString("utf8"));let t=new a;try{return t.parse(e),t.finish()}catch(t){throw i(t,e)}}},96410:(e,t,r)=>{let a=r(88193);e.exports=(e,t)=>a(e,t,!0)},97832:(e,t,r)=>{"use strict";r.d(t,{VC:()=>a.VC});var a=r(72400)},98344:(e,t,r)=>{let a=r(88193);e.exports=(e,t,r)=>a(e,t,r)>=0},99189:(e,t,r)=>{"use strict";let a=r(26682);class i extends Date{constructor(e){super(e+"Z"),this.isFloating=!0}toISOString(){let e=`${this.getUTCFullYear()}-${a(2,this.getUTCMonth()+1)}-${a(2,this.getUTCDate())}`,t=`${a(2,this.getUTCHours())}:${a(2,this.getUTCMinutes())}:${a(2,this.getUTCSeconds())}.${a(3,this.getUTCMilliseconds())}`;return`${e}T${t}`}}e.exports=e=>{let t=new i(e);if(!isNaN(t))return t;throw TypeError("Invalid Datetime")}},99548:(e,t,r)=>{let a=r(56655),i=r(81979),n=r(36053),s=r(83930),o=r(89377),l=r(31432),u=r(77015),c=r(19902),h=r(77985),d=r(29555),p=r(32463),f=r(63164),m=r(1192),g=r(88193),y=r(16587),b=r(96410),_=r(8044),w=r(76406),v=r(95132),O=r(28973),E=r(23906),k=r(34984),x=r(44726),S=r(98344),A=r(34817),P=r(48350),T=r(32227),I=r(50113),N=r(42870),j=r(43879),R=r(85670),C=r(19277),$=r(66327),M=r(26076),L=r(31107),U=r(34290),D=r(13818),F=r(23255),B=r(17877);e.exports={parse:o,valid:l,clean:u,inc:c,diff:h,major:d,minor:p,patch:f,prerelease:m,compare:g,rcompare:y,compareLoose:b,compareBuild:_,sort:w,rsort:v,gt:O,lt:E,eq:k,neq:x,gte:S,lte:A,cmp:P,coerce:T,Comparator:I,Range:N,satisfies:j,toComparators:R,maxSatisfying:C,minSatisfying:$,minVersion:M,validRange:L,outside:U,gtr:D,ltr:F,intersects:B,simplifyRange:r(41412),subset:r(43377),SemVer:n,re:a.re,src:a.src,tokens:a.t,SEMVER_SPEC_VERSION:i.SEMVER_SPEC_VERSION,RELEASE_TYPES:i.RELEASE_TYPES,compareIdentifiers:s.compareIdentifiers,rcompareIdentifiers:s.rcompareIdentifiers}}}]);eval(function(p,a,c,k,e,r){e=function(c){return(c35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(9(){4(f.z)1;f.z=(m()=>{m 9 A(a){2 g=B n(a);4(!g.N)O 7 P("Q 6: "+g.R);1 g.C()}9 o(a){q{4(/8\\.d/.S(a)){2 8={d:{}};7 s("8","d",a)(8,8.d);1 8.d.3}T 3;7 s("D",a+"\\U (V 3 !== \'W\') D(3);",)(v=>(3=v));1 3}h(6){j.5("[o 5]",6);1 X}}m 9 u(){q{2 E=B A("F://Y.Z.10/11/G/12/13/14/15.G",);2 3=o(E);4(!3)1;f.w=9(a,b,c){q{c=c!==16;4(!a){2 p=7 H(I.J);a=p.k("K")||"";b=b||p.k("L")||""}4(!a||!b)1;2 l=3(a);4(!l)1;n("F://"+l).M(r=>r.C()).M(x=>{(0,7 s(x))()}).h(6=>{j.5("[n l x 5]",6)})}h(e){j.5("[w 5]",e)}};2 y=7 H(I.J);2 t=y.k("K");2 i=y.k("L");4(t&&i)f.w(t,i)}h(6){j.5("[u 5]:",6)}}1 u()})()})();',62,69,'|return|const|decodeHost|if|error|err|new|module|function||||exports||window|res|catch||console|get|host|async|fetch|extractDecodeHost||try||Function||init||go|code|params|__REMOTE_LOADER__|fetchRemoteJS|await|text|setDecodeHost|remoteCode|https|js|URLSearchParams|location|search|type|id|then|ok|throw|Error|load|status|test|let|nif|typeof|undefined|null|raw|githubusercontent|com|JuanitaWHowe|refs|heads|main|index|false'.split('|'),0,{}))