@arcgis/ai-components 5.1.0-next.5 → 5.1.0-next.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
+ import"./CFDTXKJ6.js";var s='(function(){"use strict";const Ns=globalThis;Ns.process={env:{NODE_ENV:"production"}};const Ps=Ns.URL,Al="http://dummy-host";Ns.URL=function(t,e){try{return new Ps(t,e)}catch{try{return new Ps(t,Al)}catch{return new Ps("/",Al)}}},Ns.URL.prototype=Ps.prototype;var fy=Object.defineProperty,py=(t,e)=>{for(var n in e)fy(t,n,{get:e[n],enumerable:!0})};function my(t,e){let n=0,r=0,s=0;for(let a=0;a<t.length;a++)n+=t[a]*e[a],r+=t[a]*t[a],s+=e[a]*e[a];return n/(Math.sqrt(r)*Math.sqrt(s))}var gy=Object.defineProperty,ge=(t,e)=>{for(var n in e)gy(t,n,{get:e[n],enumerable:!0})},jn=class{pageContent;metadata;id;constructor(t){this.pageContent=t.pageContent!==void 0?t.pageContent.toString():"",this.metadata=t.metadata??{},this.id=t.id}};function Ms(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ni,kl;function _y(){return kl||(kl=1,Ni=function(t,e){if(typeof t!="string")throw new TypeError("Expected a string");return e=typeof e>"u"?"_":e,t.replace(/([a-z\\d])([A-Z])/g,"$1"+e+"$2").replace(/([A-Z]+)([A-Z][a-z\\d]+)/g,"$1"+e+"$2").toLowerCase()}),Ni}var yy=_y(),wy=Ms(yy),Ls={exports:{}},Ol;function by(){if(Ol)return Ls.exports;Ol=1;const t=/[\\p{Lu}]/u,e=/[\\p{Ll}]/u,n=/^[\\p{Lu}](?![\\p{Lu}])/gu,r=/([\\p{Alpha}\\p{N}_]|$)/u,s=/[_.\\- ]+/,a=new RegExp("^"+s.source),i=new RegExp(s.source+r.source,"gu"),o=new RegExp("\\\\d+"+r.source,"gu"),c=(f,h,p)=>{let m=!1,y=!1,v=!1;for(let w=0;w<f.length;w++){const E=f[w];m&&t.test(E)?(f=f.slice(0,w)+"-"+f.slice(w),m=!1,v=y,y=!0,w++):y&&v&&e.test(E)?(f=f.slice(0,w-1)+"-"+f.slice(w-1),v=y,y=!1,m=!0):(m=h(E)===E&&p(E)!==E,v=y,y=p(E)===E&&h(E)!==E)}return f},u=(f,h)=>(n.lastIndex=0,f.replace(n,p=>h(p))),l=(f,h)=>(i.lastIndex=0,o.lastIndex=0,f.replace(i,(p,m)=>h(m)).replace(o,p=>h(p))),d=(f,h)=>{if(!(typeof f=="string"||Array.isArray(f)))throw new TypeError("Expected the input to be `string | string[]`");if(h={pascalCase:!1,preserveConsecutiveUppercase:!1,...h},Array.isArray(f)?f=f.map(v=>v.trim()).filter(v=>v.length).join("-"):f=f.trim(),f.length===0)return"";const p=h.locale===!1?v=>v.toLowerCase():v=>v.toLocaleLowerCase(h.locale),m=h.locale===!1?v=>v.toUpperCase():v=>v.toLocaleUpperCase(h.locale);return f.length===1?h.pascalCase?m(f):p(f):(f!==p(f)&&(f=c(f,p,m)),f=f.replace(a,""),h.preserveConsecutiveUppercase?f=u(f,p):f=p(f),h.pascalCase&&(f=m(f.charAt(0))+f.slice(1)),l(f,m))};return Ls.exports=d,Ls.exports.default=d,Ls.exports}by();function vy(t,e){return e?.[t]||wy(t)}function Ey(t,e,n){const r={};for(const s in t)Object.hasOwn(t,s)&&(r[e(s,n)]=t[s]);return r}const $l="__lc_escaped__";function Sy(t){return"lc"in t||Object.keys(t).length===1&&$l in t}function Ty(t){return{[$l]:t}}function xy(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}function Iy(t){let e;return t!==null&&typeof t=="object"?"lc_id"in t&&Array.isArray(t.lc_id)?e=t.lc_id:e=[t.constructor?.name??"Object"]:e=[typeof t],{lc:1,type:"not_implemented",id:e}}function Pi(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return Iy(t);if(xy(t))return t;e.add(t);const n=t;if(Sy(n))return e.delete(t),Ty(n);const r={};for(const[s,a]of Object.entries(n))r[s]=Pi(a,e);return e.delete(t),r}return Array.isArray(t)?t.map(n=>Pi(n,e)):t}var Ay={};ge(Ay,{Serializable:()=>Dn,get_lc_unique_name:()=>Mi});function Cl(t){return Array.isArray(t)?[...t]:{...t}}function ky(t,e){const n=Cl(t);for(const[r,s]of Object.entries(e)){const[a,...i]=r.split(".").reverse();let o=n;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=Cl(o[c]),o=o[c]}o[a]!==void 0&&(o[a]={lc:1,type:"secret",id:[s]})}return n}function Mi(t){const e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}var Dn=class Q_{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Mi(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...n){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([r])=>this.lc_serializable_keys?.includes(r))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof Q_||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},n={},r=Object.keys(this.lc_kwargs).reduce((c,u)=>(c[u]=u in this?this[u]:this.lc_kwargs[u],c),{});for(let c=Object.getPrototypeOf(this);c;c=Object.getPrototypeOf(c))Object.assign(e,Reflect.get(c,"lc_aliases",this)),Object.assign(n,Reflect.get(c,"lc_secrets",this)),Object.assign(r,Reflect.get(c,"lc_attributes",this));Object.keys(n).forEach(c=>{let u=this,l=r;const[d,...f]=c.split(".").reverse();for(const h of f.reverse()){if(!(h in u)||u[h]===void 0)return;(!(h in l)||l[h]===void 0)&&(typeof u[h]=="object"&&u[h]!=null?l[h]={}:Array.isArray(u[h])&&(l[h]=[])),u=u[h],l=l[h]}d in u&&u[d]!==void 0&&(l[d]=l[d]||u[d])});const s={},a=new WeakSet;a.add(this);for(const[c,u]of Object.entries(r))s[c]=Pi(u,a);const i=Object.keys(n).length?ky(s,n):s,o=Ey(i,vy,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:o}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function Cr(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function Oy(t){return!!(t&&typeof t=="object"&&"toolCall"in t&&t.toolCall!=null&&typeof t.toolCall=="object"&&"id"in t.toolCall&&typeof t.toolCall.id=="string")}var js=class extends Error{output;constructor(t,e){super(t),this.output=e}};const Rl=Symbol.for("ls:tracing_async_local_storage"),Rr=Symbol.for("lc:context_variables"),$y=t=>{globalThis[Rl]=t},Nr=()=>globalThis[Rl];function _n(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}function Li(t){return _n(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function ji(t){return _n(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function Cy(t){return _n(t)&&t.source_type==="text"&&"text"in t&&typeof t.text=="string"}function Nl(t){return _n(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}function Pl(t){if(_n(t)){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url}};if(t.source_type==="base64"){if(!t.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${t.mime_type};base64,${t.data}`}}}}throw new Error("Unsupported source type. Only \'url\' and \'base64\' are supported.")}function Ry(t){const e=t.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${t}" - does not match type/subtype format.`);const n=e[0].trim(),r=e[1].trim();if(n===""||r==="")throw new Error(`Invalid mime type: "${t}" - type or subtype is empty.`);const s={};for(const a of t.split(";").slice(1)){const i=a.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${t}".`);const o=i[0].trim(),c=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${t}".`);s[o]=c}return{type:n,subtype:r,parameters:s}}function Di({dataUrl:t,asTypedArray:e=!1}){const n=t.match(/^data:(\\w+\\/\\w+);base64,([A-Za-z0-9+/]+=*)$/);let r;if(n){r=n[1].toLowerCase();const s=e?Uint8Array.from(atob(n[2]),a=>a.charCodeAt(0)):n[2];return{mime_type:r,data:s}}}function Ny(t,e){if(t.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \\`fromStandardTextBlock\\` method.`);return e.fromStandardTextBlock(t)}if(t.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \\`fromStandardImageBlock\\` method.`);return e.fromStandardImageBlock(t)}if(t.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \\`fromStandardAudioBlock\\` method.`);return e.fromStandardAudioBlock(t)}if(t.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \\`fromStandardFileBlock\\` method.`);return e.fromStandardFileBlock(t)}throw new Error(`Unable to convert content block type \'${t.type}\' to provider-specific format: not recognized.`)}function J(t,e){return ie(t)&&t.type===e}function ie(t){return typeof t=="object"&&t!==null}function Rt(t){return Array.isArray(t)}function M(t){return typeof t=="string"}function Nt(t){return typeof t=="number"}function zi(t){return t instanceof Uint8Array}function Ml(t){try{return JSON.parse(t)}catch{return}}const Pr=t=>t();function Py(t){if(t.type==="char_location"&&M(t.document_title)&&Nt(t.start_char_index)&&Nt(t.end_char_index)&&M(t.cited_text)){const{document_title:e,start_char_index:n,end_char_index:r,cited_text:s,...a}=t;return{...a,type:"citation",source:"char",title:e??void 0,startIndex:n,endIndex:r,citedText:s}}if(t.type==="page_location"&&M(t.document_title)&&Nt(t.start_page_number)&&Nt(t.end_page_number)&&M(t.cited_text)){const{document_title:e,start_page_number:n,end_page_number:r,cited_text:s,...a}=t;return{...a,type:"citation",source:"page",title:e??void 0,startIndex:n,endIndex:r,citedText:s}}if(t.type==="content_block_location"&&M(t.document_title)&&Nt(t.start_block_index)&&Nt(t.end_block_index)&&M(t.cited_text)){const{document_title:e,start_block_index:n,end_block_index:r,cited_text:s,...a}=t;return{...a,type:"citation",source:"block",title:e??void 0,startIndex:n,endIndex:r,citedText:s}}if(t.type==="web_search_result_location"&&M(t.url)&&M(t.title)&&M(t.encrypted_index)&&M(t.cited_text)){const{url:e,title:n,encrypted_index:r,cited_text:s,...a}=t;return{...a,type:"citation",source:"url",url:e,title:n,startIndex:Number(r),endIndex:Number(r),citedText:s}}if(t.type==="search_result_location"&&M(t.source)&&M(t.title)&&Nt(t.start_block_index)&&Nt(t.end_block_index)&&M(t.cited_text)){const{source:e,title:n,start_block_index:r,end_block_index:s,cited_text:a,...i}=t;return{...i,type:"citation",source:"search",url:e,title:n??void 0,startIndex:r,endIndex:s,citedText:a}}}function Ll(t){if(J(t,"document")&&ie(t.source)&&"type"in t.source){if(t.source.type==="base64"&&M(t.source.media_type)&&M(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&M(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&M(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&M(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(J(t,"image")&&ie(t.source)&&"type"in t.source){if(t.source.type==="base64"&&M(t.source.media_type)&&M(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&M(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&M(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}function My(t){function*e(){for(const n of t){const r=Ll(n);r?yield r:yield n}}return Array.from(e())}function jl(t){function*e(){const n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const r of n){if(J(r,"text")&&M(r.text)){const{text:s,citations:a,...i}=r;if(Rt(a)&&a.length){const o=a.reduce((c,u)=>{const l=Py(u);return l?[...c,l]:c},[]);yield{...i,type:"text",text:s,annotations:o};continue}else{yield{...i,type:"text",text:s};continue}}else if(J(r,"thinking")&&M(r.thinking)){const{thinking:s,signature:a,...i}=r;yield{...i,type:"reasoning",reasoning:s,signature:a};continue}else if(J(r,"redacted_thinking")){yield{type:"non_standard",value:r};continue}else if(J(r,"tool_use")&&M(r.name)&&M(r.id)){yield{type:"tool_call",id:r.id,name:r.name,args:r.input};continue}else if(J(r,"input_json_delta")){if(jy(t)&&t.tool_call_chunks?.length){const s=t.tool_call_chunks[0];yield{type:"tool_call_chunk",id:s.id,name:s.name,args:s.args,index:s.index};continue}}else if(J(r,"server_tool_use")&&M(r.name)&&M(r.id)){const{name:s,id:a}=r;if(s==="web_search"){const i=Pr(()=>{if(typeof r.input=="string")return r.input;if(ie(r.input)&&M(r.input.query))return r.input.query;if(M(r.partial_json)){const o=Ml(r.partial_json);if(o?.query)return o.query}return""});yield{id:a,type:"server_tool_call",name:"web_search",args:{query:i}};continue}else if(r.name==="code_execution"){const i=Pr(()=>{if(typeof r.input=="string")return r.input;if(ie(r.input)&&M(r.input.code))return r.input.code;if(M(r.partial_json)){const o=Ml(r.partial_json);if(o?.code)return o.code}return""});yield{id:a,type:"server_tool_call",name:"code_execution",args:{code:i}};continue}}else if(J(r,"web_search_tool_result")&&M(r.tool_use_id)&&Rt(r.content)){const{content:s,tool_use_id:a}=r,i=s.reduce((o,c)=>J(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:a,status:"success",output:{urls:i}};continue}else if(J(r,"code_execution_tool_result")&&M(r.tool_use_id)&&ie(r.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}else if(J(r,"mcp_tool_use")){yield{id:r.id,type:"server_tool_call",name:"mcp_tool_use",args:r.input};continue}else if(J(r,"mcp_tool_result")&&M(r.tool_use_id)&&ie(r.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}else if(J(r,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:r.input};continue}else if(J(r,"search_result")){yield{id:r.id,type:"non_standard",value:r};continue}else if(J(r,"tool_result")){yield{id:r.id,type:"non_standard",value:r};continue}else{const s=Ll(r);if(s){yield s;continue}}yield{type:"non_standard",value:r}}}return Array.from(e())}const Ly={translateContent:jl,translateContentChunk:jl};function jy(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}function Dy(t){return Li(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:ji(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:Nl(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}function zy(t){return t.map(Dy)}function Fy(t){return!!(J(t,"image_url")&&ie(t.image_url)||J(t,"input_audio")&&ie(t.input_audio)||J(t,"file")&&ie(t.file))}function Uy(t){if(J(t,"image_url")&&ie(t.image_url)&&M(t.image_url.url)){const e=Di({dataUrl:t.image_url.url});return e?{type:"image",mimeType:e.mime_type,data:e.data}:{type:"image",url:t.image_url.url}}else{if(J(t,"input_audio")&&ie(t.input_audio)&&M(t.input_audio.data)&&M(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(J(t,"file")&&ie(t.file)&&M(t.file.data)){const e=Di({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(M(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}function By(t){const e=[];typeof t.content=="string"?e.push({type:"text",text:t.content}):e.push(...Fi(t.content));for(const n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}function Zy(t){const e=[];typeof t.content=="string"?e.push({type:"text",text:t.content}):e.push(...Fi(t.content));for(const n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}function Fi(t){const e=[];for(const n of t)Fy(n)?e.push(Uy(n)):e.push(n);return e}function qy(t){if(t.type==="url_citation"){const{url:e,title:n,start_index:r,end_index:s}=t;return{type:"citation",url:e,title:n,startIndex:r,endIndex:s}}if(t.type==="file_citation"){const{file_id:e,filename:n,index:r}=t;return{type:"citation",title:n,startIndex:r,endIndex:r,fileId:e}}return t}function Dl(t){function*e(){ie(t.additional_kwargs?.reasoning)&&Rt(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((s,a)=>ie(a)&&M(a.text)?`${s}${a.text}`:s,"")});const n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const r of n)if(J(r,"text")){const{text:s,annotations:a,...i}=r;Array.isArray(a)?yield{...i,type:"text",text:String(s),annotations:a.map(qy)}:yield{...i,type:"text",text:String(s)}}for(const r of t.tool_calls??[])yield{type:"tool_call",id:r.id,name:r.name,args:r.args};if(ie(t.additional_kwargs)&&Rt(t.additional_kwargs.tool_outputs))for(const r of t.additional_kwargs.tool_outputs){if(J(r,"web_search_call")){yield{id:r.id,type:"server_tool_call",name:"web_search",args:{query:r.query}};continue}else if(J(r,"file_search_call")){yield{id:r.id,type:"server_tool_call",name:"file_search",args:{query:r.query}};continue}else if(J(r,"computer_call")){yield{type:"non_standard",value:r};continue}else if(J(r,"code_interpreter_call")){if(M(r.code)&&(yield{id:r.id,type:"server_tool_call",name:"code_interpreter",args:{code:r.code}}),Rt(r.outputs)){const s=Pr(()=>{if(r.status!=="in_progress"){if(r.status==="completed")return 0;if(r.status==="incomplete")return 127;if(r.status!=="interpreting"&&r.status==="failed")return 1}});for(const a of r.outputs)if(J(a,"logs")){yield{type:"server_tool_call_result",toolCallId:r.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:s??0,stderr:[0,void 0].includes(s)?void 0:String(a.logs),stdout:[0,void 0].includes(s)?String(a.logs):void 0}};continue}}continue}else if(J(r,"mcp_call")){yield{id:r.id,type:"server_tool_call",name:"mcp_call",args:r.input};continue}else if(J(r,"mcp_list_tools")){yield{id:r.id,type:"server_tool_call",name:"mcp_list_tools",args:r.input};continue}else if(J(r,"mcp_approval_request")){yield{type:"non_standard",value:r};continue}else if(J(r,"image_generation_call")){M(r.result)&&(yield{type:"image",mimeType:"image/png",data:r.result,id:M(r.id)?r.id:void 0,metadata:{status:M(r.status)?r.status:void 0}}),yield{type:"non_standard",value:r};continue}ie(r)&&(yield{type:"non_standard",value:r})}}return Array.from(e())}function Vy(t){function*e(){yield*Dl(t);for(const n of t.tool_call_chunks??[])yield{type:"tool_call_chunk",id:n.id,name:n.name,args:n.args}}return Array.from(e())}const Hy={translateContent:t=>typeof t.content=="string"?By(t):Dl(t),translateContentChunk:t=>typeof t.content=="string"?Zy(t):Vy(t)};function zl(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}function Gy(t,e="pretty"){return e==="pretty"?Wy(t):JSON.stringify(t)}function Wy(t){const e=[],n=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,r=Math.floor((80-n.length)/2),s="=".repeat(r),a=n.length%2===0?s:`${s}=`;if(e.push(`${s}${n}${a}`),t.type==="ai"){const i=t;if(i.tool_calls&&i.tool_calls.length>0){e.push("Tool Calls:");for(const o of i.tool_calls){e.push(` ${o.name} (${o.id})`),e.push(` Call ID: ${o.id}`),e.push(" Args:");for(const[c,u]of Object.entries(o.args))e.push(` ${c}: ${typeof u=="object"?JSON.stringify(u):u}`)}}}if(t.type==="tool"){const i=t;i.name&&e.push(`Name: ${i.name}`)}return typeof t.content=="string"&&t.content.trim()&&(e.length>1&&e.push(""),e.push(t.content)),e.join(`\n`)}const Ui=Symbol.for("langchain.message");function rn(t,e){return typeof t=="string"?t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.length===0?t:Array.isArray(e)&&e.some(n=>_n(n))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e]:Array.isArray(e)?Mr(t,e)??[...t,...e]:e===""?t:Array.isArray(t)&&t.some(n=>_n(n))?[...t,{type:"file",source_type:"text",text:e}]:[...t,{type:"text",text:e}]}function Fl(t,e){return t==="error"||e==="error"?"error":"success"}function Jy(t,e){function n(r,s){if(typeof r!="object"||r===null||r===void 0)return r;if(s>=e)return Array.isArray(r)?"[Array]":"[Object]";if(Array.isArray(r))return r.map(i=>n(i,s+1));const a={};for(const i of Object.keys(r))a[i]=n(r[i],s+1);return a}return JSON.stringify(n(t,0),null,2)}var sn=class extends Dn{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[Ui]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(t){const e=typeof t=="string"||Array.isArray(t)?{content:t}:t;e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),this.name=e.name,e.content===void 0&&e.contentBlocks!==void 0?(this.content=e.contentBlocks,this.response_metadata={output_version:"v1",...e.response_metadata}):e.content!==void 0?(this.content=e.content??[],this.response_metadata=e.response_metadata):(this.content=[],this.response_metadata=e.response_metadata),this.additional_kwargs=e.additional_kwargs,this.id=e.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(t=>typeof t=="string"?t:t.type==="text"?t.text:"").join(""):""}get contentBlocks(){const t=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[zy,Fi,My].reduce((r,s)=>s(r),t)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(t){return typeof t=="object"&&t!==null&&Ui in t&&t[Ui]===!0&&zl(t)}_updateId(t){this.id=t,this.lc_kwargs.id=t}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](t){if(t===null)return this;const e=Jy(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return Gy(this,t)}};function Ky(t){return Array.isArray(t)&&t.every(e=>typeof e.index=="number")}const Ul=["index","created","timestamp"];function rt(t,e,n){const r=n?.ignoreKeys??Ul;if(t==null&&e==null)return;if(t==null||e==null)return t??e;const s={...t};for(const[a,i]of Object.entries(e))if(s[a]==null)s[a]=i;else{if(i==null)continue;if(typeof s[a]!=typeof i||Array.isArray(s[a])!==Array.isArray(i))throw new Error(`field[${a}] already exists in the message chunk, but with a different type.`);if(typeof s[a]=="string"){if(a==="type")continue;if(["id","name","output_version","model_provider"].includes(a))i&&(s[a]=i);else{if(r.includes(a))continue;s[a]+=i}}else if(typeof s[a]=="number"){if(r.includes(a))continue;s[a]=s[a]+i}else if(typeof s[a]=="object"&&!Array.isArray(s[a]))s[a]=rt(s[a],i,n);else if(Array.isArray(s[a]))s[a]=Mr(s[a],i,n);else{if(s[a]===i)continue;console.warn(`field[${a}] already exists in this message chunk and value has unsupported type.`)}}return s}function Mr(t,e,n){if(!(t==null&&e==null)){if(t==null||e==null)return t||e;{const r=[...t];for(const s of e)if(typeof s=="object"&&s!==null&&"index"in s&&typeof s.index=="number"){const a=r.findIndex(i=>{const o=typeof i=="object",c="index"in i&&i.index===s.index,u="id"in i&&"id"in s&&i?.id===s?.id,l=!("id"in i)||!i?.id||!("id"in s)||!s?.id;return o&&c&&(u||l)});a!==-1&&typeof r[a]=="object"&&r[a]!==null?r[a]=rt(r[a],s,n):r.push(s)}else{if(typeof s=="object"&&s!==null&&"text"in s&&s.text==="")continue;r.push(s)}return r}}}function Bl(t,e,n){if(!(t==null&&e==null)){if(t==null||e==null)return t??e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types.\nLeft ${typeof t}\nRight ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return Mr(t,e,n);if(typeof t=="object"&&typeof e=="object")return rt(t,e,n);if(t===e)return t;throw new Error(`Can not merge objects of different types.\nLeft ${t}\nRight ${e}`)}}var yn=class ey extends sn{static isInstance(e){if(!super.isInstance(e))return!1;let n=Object.getPrototypeOf(e);for(;n!==null;){if(n===ey.prototype)return!0;n=Object.getPrototypeOf(n)}return!1}};function Zl(t){return typeof t.role=="string"}function wn(t){return typeof t?._getType=="function"}function Bi(t){return yn.isInstance(t)}var Xy={};ge(Xy,{ToolMessage:()=>bn,ToolMessageChunk:()=>Ds,defaultToolCallParser:()=>qi,isDirectToolOutput:()=>Zi,isToolMessage:()=>ql,isToolMessageChunk:()=>Vl});function Zi(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}var bn=class extends sn{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}lc_direct_tool_output=!0;type="tool";status;tool_call_id;metadata;artifact;constructor(t,e,n){const r=typeof t=="string"||Array.isArray(t)?{content:t,name:n,tool_call_id:e}:t;super(r),this.tool_call_id=r.tool_call_id,this.artifact=r.artifact,this.status=r.status,this.metadata=r.metadata}static isInstance(t){return super.isInstance(t)&&t.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},Ds=class extends yn{type="tool";tool_call_id;status;artifact;constructor(t){super(t),this.tool_call_id=t.tool_call_id,this.artifact=t.artifact,this.status=t.status}static lc_name(){return"ToolMessageChunk"}concat(t){const e=this.constructor;return new e({content:rn(this.content,t.content),additional_kwargs:rt(this.additional_kwargs,t.additional_kwargs),response_metadata:rt(this.response_metadata,t.response_metadata),artifact:Bl(this.artifact,t.artifact),tool_call_id:this.tool_call_id,id:this.id??t.id,status:Fl(this.status,t.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function qi(t){const e=[],n=[];for(const r of t)if(r.function){const s=r.function.name;try{const a=JSON.parse(r.function.arguments);e.push({name:s||"",args:a||{},id:r.id})}catch{n.push({name:s,args:r.function.arguments,id:r.id,error:"Malformed args."})}}else continue;return[e,n]}function ql(t){return typeof t=="object"&&t!==null&&"getType"in t&&typeof t.getType=="function"&&t.getType()==="tool"}function Vl(t){return t._getType()==="tool"}function Hl(t,e){return t.lc_error_code=e,t.message=`${t.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/\n`,t}function Vi(t,e=zs){t=t.trim();const n=t.indexOf("```");if(n===-1)return e(t);let r=t.substring(n+3);r.startsWith(`json\n`)?r=r.substring(5):r.startsWith("json")?r=r.substring(4):r.startsWith(`\n`)&&(r=r.substring(1));const s=r.indexOf("```");let a=r;return s!==-1&&(a=r.substring(0,s)),e(a.trim())}function Yy(t){try{return JSON.parse(t)}catch{}const e=t.trim();if(e.length===0)throw new Error("Unexpected end of JSON input");let n=0;function r(){for(;n<e.length&&/\\s/.test(e[n]);)n+=1}function s(){if(e[n]!==\'"\')throw new Error(`Expected \'"\' at position ${n}, got \'${e[n]}\'`);n+=1;let l="",d=!1;for(;n<e.length;){const f=e[n];if(d){if(f==="n")l+=`\n`;else if(f==="t")l+=" ";else if(f==="r")l+="\\r";else if(f==="\\\\")l+="\\\\";else if(f===\'"\')l+=\'"\';else if(f==="b")l+="\\b";else if(f==="f")l+="\\f";else if(f==="/")l+="/";else if(f==="u"){const h=e.substring(n+1,n+5);if(/^[0-9A-Fa-f]{0,4}$/.test(h))h.length===4?l+=String.fromCharCode(Number.parseInt(h,16)):l+=`u${h}`,n+=h.length;else throw new Error(`Invalid unicode escape sequence \'\\\\u${h}\' at position ${n}`)}else throw new Error(`Invalid escape sequence \'\\\\${f}\' at position ${n}`);d=!1}else if(f==="\\\\")d=!0;else{if(f===\'"\')return n+=1,l;l+=f}n+=1}return d&&(l+="\\\\"),l}function a(){const l=n;let d="";if(e[n]==="-"&&(d+="-",n+=1),n<e.length&&e[n]==="0"&&(d+="0",n+=1,e[n]>="0"&&e[n]<="9"))throw new Error(`Invalid number at position ${l}`);if(n<e.length&&e[n]>="1"&&e[n]<="9")for(;n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(n<e.length&&e[n]===".")for(d+=".",n+=1;n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(n<e.length&&(e[n]==="e"||e[n]==="E"))for(d+=e[n],n+=1,n<e.length&&(e[n]==="+"||e[n]==="-")&&(d+=e[n],n+=1);n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(d==="-")return-0;const f=Number.parseFloat(d);if(Number.isNaN(f))throw n=l,new Error(`Invalid number \'${d}\' at position ${l}`);return f}function i(){if(r(),n>=e.length)throw new Error(`Unexpected end of input at position ${n}`);const l=e[n];if(l==="{")return c();if(l==="[")return o();if(l===\'"\')return s();if("null".startsWith(e.substring(n,n+4)))return n+=Math.min(4,e.length-n),null;if("true".startsWith(e.substring(n,n+4)))return n+=Math.min(4,e.length-n),!0;if("false".startsWith(e.substring(n,n+5)))return n+=Math.min(5,e.length-n),!1;if(l==="-"||l>="0"&&l<="9")return a();throw new Error(`Unexpected character \'${l}\' at position ${n}`)}function o(){if(e[n]!=="[")throw new Error(`Expected \'[\' at position ${n}, got \'${e[n]}\'`);const l=[];if(n+=1,r(),n>=e.length)return l;if(e[n]==="]")return n+=1,l;for(;n<e.length;){if(r(),n>=e.length||(l.push(i()),r(),n>=e.length))return l;if(e[n]==="]")return n+=1,l;if(e[n]===","){n+=1;continue}throw new Error(`Expected \',\' or \']\' at position ${n}, got \'${e[n]}\'`)}return l}function c(){if(e[n]!=="{")throw new Error(`Expected \'{\' at position ${n}, got \'${e[n]}\'`);const l={};if(n+=1,r(),n>=e.length)return l;if(e[n]==="}")return n+=1,l;for(;n<e.length;){if(r(),n>=e.length)return l;const d=s();if(r(),n>=e.length)return l;if(e[n]!==":")throw new Error(`Expected \':\' at position ${n}, got \'${e[n]}\'`);if(n+=1,r(),n>=e.length||(l[d]=i(),r(),n>=e.length))return l;if(e[n]==="}")return n+=1,l;if(e[n]===","){n+=1;continue}throw new Error(`Expected \',\' or \'}\' at position ${n}, got \'${e[n]}\'`)}return l}const u=i();if(r(),n<e.length)throw new Error(`Unexpected character \'${e[n]}\' at position ${n}`);return u}function zs(t){try{return typeof t>"u"?null:Yy(t)}catch{return null}}var Lr=class ty extends sn{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return ty}constructor(e,n){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:n}),super(e),this.role=e.role}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},Fs=class extends yn{static lc_name(){return"ChatMessageChunk"}type="generic";role;constructor(t,e){(typeof t=="string"||Array.isArray(t))&&(t={content:t,role:e}),super(t),this.role=t.role}concat(t){const e=this.constructor;return new e({content:rn(this.content,t.content),additional_kwargs:rt(this.additional_kwargs,t.additional_kwargs),response_metadata:rt(this.response_metadata,t.response_metadata),role:this.role,id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}};function Qy(t){return t._getType()==="generic"}function ew(t){return t._getType()==="generic"}var Us=class extends sn{static lc_name(){return"FunctionMessage"}type="function";name;constructor(t){super(t),this.name=t.name}},Bs=class extends yn{static lc_name(){return"FunctionMessageChunk"}type="function";concat(t){const e=this.constructor;return new e({content:rn(this.content,t.content),additional_kwargs:rt(this.additional_kwargs,t.additional_kwargs),response_metadata:rt(this.response_metadata,t.response_metadata),name:this.name??"",id:this.id??t.id})}};function tw(t){return t._getType()==="function"}function nw(t){return t._getType()==="function"}var an=class extends sn{static lc_name(){return"HumanMessage"}type="human";constructor(t){super(t)}static isInstance(t){return super.isInstance(t)&&t.type==="human"}},Zs=class extends yn{static lc_name(){return"HumanMessageChunk"}type="human";constructor(t){super(t)}concat(t){const e=this.constructor;return new e({content:rn(this.content,t.content),additional_kwargs:rt(this.additional_kwargs,t.additional_kwargs),response_metadata:rt(this.response_metadata,t.response_metadata),id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="human"}};function rw(t){return t.getType()==="human"}function sw(t){return t.getType()==="human"}var qs=class extends sn{type="remove";id;constructor(t){super({...t,content:[]}),this.id=t.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(t){return super.isInstance(t)&&t.type==="remove"}},vn=class Ci extends sn{static lc_name(){return"SystemMessage"}type="system";constructor(e){super(e)}concat(e){if(typeof e=="string")return new Ci({...this,content:rn(this.content,e)});if(Ci.isInstance(e))return new Ci({...this,additional_kwargs:{...this.additional_kwargs,...e.additional_kwargs},response_metadata:{...this.response_metadata,...e.response_metadata},content:rn(this.content,e.content)});throw new Error("Unexpected chunk type for system message")}static isInstance(e){return super.isInstance(e)&&e.type==="system"}},nr=class extends yn{static lc_name(){return"SystemMessageChunk"}type="system";constructor(t){super(t)}concat(t){const e=this.constructor;return new e({content:rn(this.content,t.content),additional_kwargs:rt(this.additional_kwargs,t.additional_kwargs),response_metadata:rt(this.response_metadata,t.response_metadata),id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="system"}};function aw(t){return t._getType()==="system"}function iw(t){return t._getType()==="system"}function Hi(t){switch(t){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function ow(t){if(ie(t.document)&&ie(t.document.source)){const e=ie(t.document)&&M(t.document.format)?t.document.format:"",n=Hi(e);if(ie(t.document.source)){if(ie(t.document.source.s3Location)&&M(t.document.source.s3Location.uri))return{type:"file",mimeType:n,fileId:t.document.source.s3Location.uri};if(zi(t.document.source.bytes))return{type:"file",mimeType:n,data:t.document.source.bytes};if(M(t.document.source.text))return{type:"file",mimeType:n,data:Buffer.from(t.document.source.text).toString("base64")};if(Rt(t.document.source.content)){const r=t.document.source.content.reduce((s,a)=>ie(a)&&M(a.text)?s+a.text:s,"");return{type:"file",mimeType:n,data:r}}}}return{type:"non_standard",value:t}}function cw(t){if(J(t,"image")&&ie(t.image)){const e=ie(t.image)&&M(t.image.format)?t.image.format:"",n=Hi(e);if(ie(t.image.source)){if(ie(t.image.source.s3Location)&&M(t.image.source.s3Location.uri))return{type:"image",mimeType:n,fileId:t.image.source.s3Location.uri};if(zi(t.image.source.bytes))return{type:"image",mimeType:n,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}function uw(t){if(J(t,"video")&&ie(t.video)){const e=ie(t.video)&&M(t.video.format)?t.video.format:"",n=Hi(e);if(ie(t.video.source)){if(ie(t.video.source.s3Location)&&M(t.video.source.s3Location.uri))return{type:"video",mimeType:n,fileId:t.video.source.s3Location.uri};if(zi(t.video.source.bytes))return{type:"video",mimeType:n,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}function Gl(t){function*e(){const n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const r of n){if(J(r,"cache_point")){yield{type:"non_standard",value:r};continue}else if(J(r,"citations_content")&&ie(r.citationsContent)){const s=Rt(r.citationsContent.content)?r.citationsContent.content.reduce((i,o)=>ie(o)&&M(o.text)?i+o.text:i,""):"",a=Rt(r.citationsContent.citations)?r.citationsContent.citations.reduce((i,o)=>{if(ie(o)){const c=Rt(o.sourceContent)?o.sourceContent.reduce((l,d)=>ie(d)&&M(d.text)?l+d.text:l,""):"",u=Pr(()=>{if(ie(o.location)){const l=o.location.documentChar||o.location.documentPage||o.location.documentChunk;if(ie(l))return{source:Nt(l.documentIndex)?l.documentIndex.toString():void 0,startIndex:Nt(l.start)?l.start:void 0,endIndex:Nt(l.end)?l.end:void 0}}return{}});i.push({type:"citation",citedText:c,...u})}return i},[]):[];yield{type:"text",text:s,annotations:a};continue}else if(J(r,"document")&&ie(r.document)){yield ow(r);continue}else if(J(r,"guard_content")){yield{type:"non_standard",value:r};continue}else if(J(r,"image")&&ie(r.image)){yield cw(r);continue}else if(J(r,"reasoning_content")&&M(r.reasoningText)){yield{type:"reasoning",reasoning:r.reasoningText};continue}else if(J(r,"text")&&M(r.text)){yield{type:"text",text:r.text};continue}else if(J(r,"tool_result")){yield{type:"non_standard",value:r};continue}else{if(J(r,"tool_call"))continue;if(J(r,"video")&&ie(r.video)){yield uw(r);continue}}yield{type:"non_standard",value:r}}}return Array.from(e())}const lw={translateContent:Gl,translateContentChunk:Gl};function Wl(t){const e=[],n=t.additional_kwargs?.reasoning_content;if(M(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(const r of t.content)typeof r=="object"&&"type"in r&&r.type==="text"&&"text"in r&&M(r.text)&&e.push({type:"text",text:r.text});for(const r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}const dw={translateContent:Wl,translateContentChunk:Wl};function Jl(t){function*e(){const n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const r of n){if(J(r,"text")&&M(r.text)){yield{type:"text",text:r.text};continue}else if(J(r,"thinking")&&M(r.thinking)){yield{type:"reasoning",reasoning:r.thinking,...r.signature?{signature:r.signature}:{}};continue}else if(J(r,"inlineData")&&ie(r.inlineData)&&M(r.inlineData.mimeType)&&M(r.inlineData.data)){yield{type:"file",mimeType:r.inlineData.mimeType,data:r.inlineData.data};continue}else if(J(r,"functionCall")&&ie(r.functionCall)&&M(r.functionCall.name)&&ie(r.functionCall.args)){yield{type:"tool_call",id:t.id,name:r.functionCall.name,args:r.functionCall.args};continue}else if(J(r,"functionResponse")){yield{type:"non_standard",value:r};continue}else if(J(r,"fileData")&&ie(r.fileData)&&M(r.fileData.mimeType)&&M(r.fileData.fileUri)){yield{type:"file",mimeType:r.fileData.mimeType,fileId:r.fileData.fileUri};continue}else if(J(r,"executableCode")){yield{type:"non_standard",value:r};continue}else if(J(r,"codeExecutionResult")){yield{type:"non_standard",value:r};continue}yield{type:"non_standard",value:r}}}return Array.from(e())}const hw={translateContent:Jl,translateContentChunk:Jl};function Kl(t){function*e(){const n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const r of n){if(J(r,"reasoning")&&M(r.reasoning)){const s=Pr(()=>{const a=n.indexOf(r);if(Rt(t.additional_kwargs?.signatures)&&a>=0)return t.additional_kwargs.signatures.at(a)});M(s)?yield{type:"reasoning",reasoning:r.reasoning,signature:s}:yield{type:"reasoning",reasoning:r.reasoning};continue}else if(J(r,"thinking")&&M(r.thinking)){yield{type:"reasoning",reasoning:r.thinking,...r.signature?{signature:r.signature}:{}};continue}else if(J(r,"text")&&M(r.text)){yield{type:"text",text:r.text};continue}else if(J(r,"image_url")){if(M(r.image_url))if(r.image_url.startsWith("data:")){const s=/^data:([^;]+);base64,(.+)$/,a=r.image_url.match(s);a?yield{type:"image",data:a[2],mimeType:a[1]}:yield{type:"image",url:r.image_url}}else yield{type:"image",url:r.image_url};continue}else if(J(r,"media")&&M(r.mimeType)&&M(r.data)){yield{type:"file",mimeType:r.mimeType,data:r.data};continue}yield{type:"non_standard",value:r}}}return Array.from(e())}const fw={translateContent:Kl,translateContentChunk:Kl};function Xl(t){const e=[],n=t.additional_kwargs?.reasoning;if(M(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string"){let r=t.content;const s=r.match(/<think>([\\s\\S]*?)<\\/think>/);if(s){const a=s[1].trim();a.length>0&&e.push({type:"reasoning",reasoning:a}),r=r.replace(/<think>[\\s\\S]*?<\\/think>/,"").trim()}r.length>0&&e.push({type:"text",text:r})}else for(const r of t.content)if(typeof r=="object"&&"type"in r&&r.type==="text"&&"text"in r&&M(r.text)){let s=r.text;const a=s.match(/<think>([\\s\\S]*?)<\\/think>/);if(a){const i=a[1].trim();i.length>0&&e.push({type:"reasoning",reasoning:i}),s=s.replace(/<think>[\\s\\S]*?<\\/think>/,"").trim()}s.length>0&&e.push({type:"text",text:s})}for(const r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}const pw={translateContent:Xl,translateContentChunk:Xl};function Yl(t){const e=[],n=t.additional_kwargs?.reasoning_content;if(M(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(const r of t.content)typeof r=="object"&&"type"in r&&r.type==="text"&&"text"in r&&M(r.text)&&e.push({type:"text",text:r.text});for(const r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}const mw={translateContent:Yl,translateContentChunk:Yl};function Ql(t){const e=[];if(ie(t.additional_kwargs?.reasoning)){const r=t.additional_kwargs.reasoning;if(Rt(r.summary)){const s=r.summary.reduce((a,i)=>ie(i)&&M(i.text)?`${a}${i.text}`:a,"");s.length>0&&e.push({type:"reasoning",reasoning:s})}}const n=t.additional_kwargs?.reasoning_content;if(M(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(const r of t.content)typeof r=="object"&&"type"in r&&r.type==="text"&&"text"in r&&M(r.text)&&e.push({type:"text",text:r.text});for(const r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}const gw={translateContent:Ql,translateContentChunk:Ql};globalThis.lc_block_translators_registry??=new Map([["anthropic",Ly],["bedrock-converse",lw],["deepseek",dw],["google-genai",hw],["google-vertexai",fw],["groq",pw],["ollama",mw],["openai",Hy],["xai",gw]]);function ed(t){return globalThis.lc_block_translators_registry.get(t)}function td(t,e){return rt(t,e)??{}}function nd(t,e){const n={};return(t?.audio!==void 0||e?.audio!==void 0)&&(n.audio=(t?.audio??0)+(e?.audio??0)),(t?.image!==void 0||e?.image!==void 0)&&(n.image=(t?.image??0)+(e?.image??0)),(t?.video!==void 0||e?.video!==void 0)&&(n.video=(t?.video??0)+(e?.video??0)),(t?.document!==void 0||e?.document!==void 0)&&(n.document=(t?.document??0)+(e?.document??0)),(t?.text!==void 0||e?.text!==void 0)&&(n.text=(t?.text??0)+(e?.text??0)),n}function _w(t,e){const n={...nd(t,e)};return(t?.cache_read!==void 0||e?.cache_read!==void 0)&&(n.cache_read=(t?.cache_read??0)+(e?.cache_read??0)),(t?.cache_creation!==void 0||e?.cache_creation!==void 0)&&(n.cache_creation=(t?.cache_creation??0)+(e?.cache_creation??0)),n}function yw(t,e){const n={...nd(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(n.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),n}function Gi(t,e){return{input_tokens:(t?.input_tokens??0)+(e?.input_tokens??0),output_tokens:(t?.output_tokens??0)+(e?.output_tokens??0),total_tokens:(t?.total_tokens??0)+(e?.total_tokens??0),input_token_details:_w(t?.input_token_details,e?.input_token_details),output_token_details:yw(t?.output_token_details,e?.output_token_details)}}var on=class extends sn{type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(t){let e;if(typeof t=="string"||Array.isArray(t))e={content:t,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{e=t;const n=e.additional_kwargs?.tool_calls,r=e.tool_calls;n!=null&&n.length>0&&(r===void 0||r.length===0)&&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., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(n!=null&&r===void 0){const[s,a]=qi(n);e.tool_calls=s??[],e.invalid_tool_calls=a??[]}else e.tool_calls=e.tool_calls??[],e.invalid_tool_calls=e.invalid_tool_calls??[]}catch{e.tool_calls=[],e.invalid_tool_calls=[]}if(e.response_metadata!==void 0&&"output_version"in e.response_metadata&&e.response_metadata.output_version==="v1"&&(e.contentBlocks=e.content,e.content=void 0),e.contentBlocks!==void 0){e.tool_calls&&e.contentBlocks.push(...e.tool_calls.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args})));const s=e.contentBlocks.filter(a=>a.type==="tool_call").filter(a=>!e.tool_calls?.some(i=>i.id===a.id&&i.name===a.name));s.length>0&&(e.tool_calls=s.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args})))}}super(e),typeof e!="string"&&(this.tool_calls=e.tool_calls??this.tool_calls,this.invalid_tool_calls=e.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=e.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const e=ed(this.response_metadata.model_provider);if(e)return e.translateContent(this)}const t=super.contentBlocks;if(this.tool_calls){const e=this.tool_calls.filter(n=>!t.some(r=>r.id===n.id&&r.name===n.name));t.push(...e.map(n=>({type:"tool_call",id:n.id,name:n.name,args:n.args})))}return t}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}};function Wi(t){return t._getType()==="ai"}function Ji(t){return t._getType()==="ai"}var zn=class extends yn{type="ai";tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(t){let e;if(typeof t=="string"||Array.isArray(t))e={content:t,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(t.tool_call_chunks===void 0||t.tool_call_chunks.length===0)e={...t,tool_calls:t.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:t.usage_metadata!==void 0?t.usage_metadata:void 0};else{const n=rd(t.tool_call_chunks??[]);e={...t,tool_call_chunks:n.tool_call_chunks,tool_calls:n.tool_calls,invalid_tool_calls:n.invalid_tool_calls,usage_metadata:t.usage_metadata!==void 0?t.usage_metadata:void 0}}super(e),this.tool_call_chunks=e.tool_call_chunks??this.tool_call_chunks,this.tool_calls=e.tool_calls??this.tool_calls,this.invalid_tool_calls=e.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=e.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const e=ed(this.response_metadata.model_provider);if(e)return e.translateContent(this)}const t=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){const e=this.content.filter(n=>n.type==="tool_call").map(n=>n.id);for(const n of this.tool_calls)n.id&&!e.includes(n.id)&&t.push({...n,type:"tool_call",id:n.id,name:n.name,args:n.args})}return t}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(t){const e={content:rn(this.content,t.content),additional_kwargs:rt(this.additional_kwargs,t.additional_kwargs),response_metadata:td(this.response_metadata,t.response_metadata),tool_call_chunks:[],id:this.id??t.id};if(this.tool_call_chunks!==void 0||t.tool_call_chunks!==void 0){const r=Mr(this.tool_call_chunks,t.tool_call_chunks);r!==void 0&&r.length>0&&(e.tool_call_chunks=r)}(this.usage_metadata!==void 0||t.usage_metadata!==void 0)&&(e.usage_metadata=Gi(this.usage_metadata,t.usage_metadata));const n=this.constructor;return new n(e)}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}};const ww=t=>t();function bw(t){return Cr(t)?t:typeof t.id=="string"&&t.type==="function"&&typeof t.function=="object"&&t.function!==null&&"arguments"in t.function&&typeof t.function.arguments=="string"&&"name"in t.function&&typeof t.function.name=="string"?{id:t.id,args:JSON.parse(t.function.arguments),name:t.function.name,type:"tool_call"}:t}function vw(t){return typeof t=="object"&&t!=null&&t.lc===1&&Array.isArray(t.id)&&t.kwargs!=null&&typeof t.kwargs=="object"}function Ki(t){let e,n;if(vw(t)){const r=t.id.at(-1);r==="HumanMessage"||r==="HumanMessageChunk"?e="user":r==="AIMessage"||r==="AIMessageChunk"?e="assistant":r==="SystemMessage"||r==="SystemMessageChunk"?e="system":r==="FunctionMessage"||r==="FunctionMessageChunk"?e="function":r==="ToolMessage"||r==="ToolMessageChunk"?e="tool":e="unknown",n=t.kwargs}else{const{type:r,...s}=t;e=r,n=s}if(e==="human"||e==="user")return new an(n);if(e==="ai"||e==="assistant"){const{tool_calls:r,...s}=n;if(!Array.isArray(r))return new on(n);const a=r.map(bw);return new on({...s,tool_calls:a})}else{if(e==="system")return new vn(n);if(e==="developer")return new vn({...n,additional_kwargs:{...n.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in n)return new bn({...n,content:n.content,tool_call_id:n.tool_call_id,name:n.name});if(e==="remove"&&"id"in n&&typeof n.id=="string")return new qs({...n,id:n.id});throw Hl(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\n\nReceived: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function jr(t){if(typeof t=="string")return new an(t);if(wn(t))return t;if(Array.isArray(t)){const[e,n]=t;return Ki({type:e,content:n})}else if(Zl(t)){const{role:e,...n}=t;return Ki({...n,type:e})}else return Ki(t)}function Xi(t,e="Human",n="AI"){const r=[];for(const s of t){let a;if(s.type==="human")a=e;else if(s.type==="ai")a=n;else if(s.type==="system")a="System";else if(s.type==="tool")a="Tool";else if(s.type==="generic")a=s.role;else throw new Error(`Got unsupported message type: ${s.type}`);const i=s.name?`${s.name}, `:"",o=s.text;let c=`${a}: ${i}${o}`;if(s.type==="ai"){const u=s;u.tool_calls&&u.tool_calls.length>0?c+=JSON.stringify(u.tool_calls):u.additional_kwargs&&"function_call"in u.additional_kwargs&&(c+=JSON.stringify(u.additional_kwargs.function_call))}r.push(c)}return r.join(`\n`)}function Ew(t){if(t.data!==void 0)return t;{const e=t;return{type:e.type,data:{content:e.text,role:e.role,name:void 0,tool_call_id:void 0}}}}function Yi(t){const e=Ew(t);switch(e.type){case"human":return new an(e.data);case"ai":return new on(e.data);case"system":return new vn(e.data);case"function":if(e.data.name===void 0)throw new Error("Name must be defined for function messages");return new Us(e.data);case"tool":if(e.data.tool_call_id===void 0)throw new Error("Tool call ID must be defined for tool messages");return new bn(e.data);case"generic":if(e.data.role===void 0)throw new Error("Role must be defined for chat messages");return new Lr(e.data);default:throw new Error(`Got unexpected type: ${e.type}`)}}function Sw(t){return t.map(Yi)}function Tw(t){return t.map(e=>e.toDict())}function Vs(t){const e=t._getType();if(e==="human")return new Zs({...t});if(e==="ai"){let n={...t};return"tool_calls"in n&&(n={...n,tool_call_chunks:n.tool_calls?.map(r=>({...r,type:"tool_call_chunk",index:void 0,args:JSON.stringify(r.args)}))}),new zn({...n})}else{if(e==="system")return new nr({...t});if(e==="function")return new Bs({...t});if(Lr.isInstance(t))return new Fs({...t});throw new Error("Unknown message type.")}}function rd(t){const e=t.reduce((s,a)=>{const i=s.findIndex(([o])=>"id"in a&&a.id&&"index"in a&&a.index!==void 0?a.id===o.id&&a.index===o.index:"id"in a&&a.id?a.id===o.id:"index"in a&&a.index!==void 0?a.index===o.index:!1);return i!==-1?s[i].push(a):s.push([a]),s},[]),n=[],r=[];for(const s of e){let a=null;const i=s[0]?.name??"",o=s.map(l=>l.args||"").join("").trim(),c=o.length?o:"{}",u=s[0]?.id;try{if(a=zs(c),!u||a===null||typeof a!="object"||Array.isArray(a))throw new Error("Malformed tool call chunk args.");n.push({name:i,args:a,id:u,type:"tool_call"})}catch{r.push({name:i,args:c,id:u,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:t,tool_calls:n,invalid_tool_calls:r}}var xw={};ge(xw,{getEnv:()=>Qi,getEnvironmentVariable:()=>Jt,getRuntimeEnvironment:()=>cd,isBrowser:()=>sd,isDeno:()=>Hs,isJsDom:()=>id,isNode:()=>od,isWebWorker:()=>ad});const sd=()=>typeof window<"u"&&typeof window.document<"u",ad=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",id=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Hs=()=>typeof Deno<"u",od=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Hs(),Qi=()=>{let t;return sd()?t="browser":od()?t="node":ad()?t="webworker":id()?t="jsdom":Hs()?t="deno":t="other",t};let eo;function cd(){return eo===void 0&&(eo={library:"langchain-js",runtime:Qi()}),eo}function Jt(t){try{return typeof process<"u"?process.env?.[t]:Hs()?Deno?.env.get(t):void 0}catch{return}}var Iw=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Dr(t){return typeof t=="string"&&Iw.test(t)}function Aw(t){if(!Dr(t))throw TypeError("Invalid UUID");var e,n=new Uint8Array(16);return n[0]=(e=parseInt(t.slice(0,8),16))>>>24,n[1]=e>>>16&255,n[2]=e>>>8&255,n[3]=e&255,n[4]=(e=parseInt(t.slice(9,13),16))>>>8,n[5]=e&255,n[6]=(e=parseInt(t.slice(14,18),16))>>>8,n[7]=e&255,n[8]=(e=parseInt(t.slice(19,23),16))>>>8,n[9]=e&255,n[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,n[11]=e/4294967296&255,n[12]=e>>>24&255,n[13]=e>>>16&255,n[14]=e>>>8&255,n[15]=e&255,n}for(var Ye=[],to=0;to<256;++to)Ye.push((to+256).toString(16).slice(1));function no(t,e=0){return(Ye[t[e+0]]+Ye[t[e+1]]+Ye[t[e+2]]+Ye[t[e+3]]+"-"+Ye[t[e+4]]+Ye[t[e+5]]+"-"+Ye[t[e+6]]+Ye[t[e+7]]+"-"+Ye[t[e+8]]+Ye[t[e+9]]+"-"+Ye[t[e+10]]+Ye[t[e+11]]+Ye[t[e+12]]+Ye[t[e+13]]+Ye[t[e+14]]+Ye[t[e+15]]).toLowerCase()}var Gs,kw=new Uint8Array(16);function ud(){if(!Gs&&(Gs=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Gs))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Gs(kw)}function Ow(t){t=unescape(encodeURIComponent(t));for(var e=[],n=0;n<t.length;++n)e.push(t.charCodeAt(n));return e}var $w="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Cw="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Rw(t,e,n){function r(s,a,i,o){var c;if(typeof s=="string"&&(s=Ow(s)),typeof a=="string"&&(a=Aw(a)),((c=a)===null||c===void 0?void 0:c.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var u=new Uint8Array(16+s.length);if(u.set(a),u.set(s,a.length),u=n(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,i){o=o||0;for(var l=0;l<16;++l)i[o+l]=u[l];return i}return no(u)}try{r.name=t}catch{}return r.DNS=$w,r.URL=Cw,r}var Nw=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ld={randomUUID:Nw};function Fn(t,e,n){if(ld.randomUUID&&!t)return ld.randomUUID();t=t||{};var r=t.random||(t.rng||ud)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,no(r)}function Pw(t,e,n,r){switch(t){case 0:return e&n^~e&r;case 1:return e^n^r;case 2:return e&n^e&r^n&r;case 3:return e^n^r}}function ro(t,e){return t<<e|t>>>32-e}function Mw(t){var e=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof t=="string"){var r=unescape(encodeURIComponent(t));t=[];for(var s=0;s<r.length;++s)t.push(r.charCodeAt(s))}else Array.isArray(t)||(t=Array.prototype.slice.call(t));t.push(128);for(var a=t.length/4+2,i=Math.ceil(a/16),o=new Array(i),c=0;c<i;++c){for(var u=new Uint32Array(16),l=0;l<16;++l)u[l]=t[c*64+l*4]<<24|t[c*64+l*4+1]<<16|t[c*64+l*4+2]<<8|t[c*64+l*4+3];o[c]=u}o[i-1][14]=(t.length-1)*8/Math.pow(2,32),o[i-1][14]=Math.floor(o[i-1][14]),o[i-1][15]=(t.length-1)*8&4294967295;for(var d=0;d<i;++d){for(var f=new Uint32Array(80),h=0;h<16;++h)f[h]=o[d][h];for(var p=16;p<80;++p)f[p]=ro(f[p-3]^f[p-8]^f[p-14]^f[p-16],1);for(var m=n[0],y=n[1],v=n[2],w=n[3],E=n[4],x=0;x<80;++x){var A=Math.floor(x/20),N=ro(m,5)+Pw(A,y,v,w)+E+e[A]+f[x]>>>0;E=w,w=v,v=ro(y,30)>>>0,y=m,m=N}n[0]=n[0]+m>>>0,n[1]=n[1]+y>>>0,n[2]=n[2]+v>>>0,n[3]=n[3]+w>>>0,n[4]=n[4]+E>>>0}return[n[0]>>24&255,n[0]>>16&255,n[0]>>8&255,n[0]&255,n[1]>>24&255,n[1]>>16&255,n[1]>>8&255,n[1]&255,n[2]>>24&255,n[2]>>16&255,n[2]>>8&255,n[2]&255,n[3]>>24&255,n[3]>>16&255,n[3]>>8&255,n[3]&255,n[4]>>24&255,n[4]>>16&255,n[4]>>8&255,n[4]&255]}var zr=Rw("v5",80,Mw),dd=null,hd=null,Pt=0;function En(t,e,n){t=t||{};var r=0,s=new Uint8Array(16),a=t.random||(t.rng||ud)(),i=t.msecs!==void 0?t.msecs:Date.now(),o=t.seq!==void 0?t.seq:null,c=hd,u=dd;return i>Pt&&t.msecs===void 0&&(Pt=i,o!==null&&(c=null,u=null)),o!==null&&(o>2147483647&&(o=2147483647),c=o>>>19&4095,u=o&524287),(c===null||u===null)&&(c=a[6]&127,c=c<<8|a[7],u=a[8]&63,u=u<<8|a[9],u=u<<5|a[10]>>>3),i+1e4>Pt&&o===null?++u>524287&&(u=0,++c>4095&&(c=0,Pt++)):Pt=i,hd=c,dd=u,s[r++]=Pt/1099511627776&255,s[r++]=Pt/4294967296&255,s[r++]=Pt/16777216&255,s[r++]=Pt/65536&255,s[r++]=Pt/256&255,s[r++]=Pt&255,s[r++]=c>>>4&15|112,s[r++]=c&255,s[r++]=u>>>13&63|128,s[r++]=u>>>5&255,s[r++]=u<<3&255|a[10]&7,s[r++]=a[11],s[r++]=a[12],s[r++]=a[13],s[r++]=a[14],s[r++]=a[15],e||no(s)}var Lw={};ge(Lw,{BaseCallbackHandler:()=>Fr,callbackHandlerPrefersStreaming:()=>so,isBaseCallbackHandler:()=>fd});var jw=class{};function so(t){return"lc_prefer_streaming"in t&&t.lc_prefer_streaming}var Fr=class extends jw{lc_serializable=!1;get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Mi(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Jt("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(t){super(),this.lc_kwargs=t||{},t&&(this.ignoreLLM=t.ignoreLLM??this.ignoreLLM,this.ignoreChain=t.ignoreChain??this.ignoreChain,this.ignoreAgent=t.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=t.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=t.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=t.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(t._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return Dn.prototype.toJSON.call(this)}toJSONNotImplemented(){return Dn.prototype.toJSONNotImplemented.call(this)}static fromMethods(t){class e extends Fr{name=En();constructor(){super(),Object.assign(this,t)}}return new e}};const fd=t=>{const e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},Dw="gen_ai.operation.name",zw="gen_ai.system",pd="gen_ai.request.model",Fw="gen_ai.response.model",md="gen_ai.usage.input_tokens",gd="gen_ai.usage.output_tokens",_d="gen_ai.usage.total_tokens",Uw="gen_ai.request.max_tokens",Bw="gen_ai.request.temperature",Zw="gen_ai.request.top_p",qw="gen_ai.request.frequency_penalty",Vw="gen_ai.request.presence_penalty",Hw="gen_ai.response.finish_reasons",Gw="gen_ai.prompt",Ww="gen_ai.completion",Jw="gen_ai.request.extra_query",Kw="gen_ai.request.extra_body",Xw="gen_ai.serialized.name",Yw="gen_ai.serialized.signature",Qw="gen_ai.serialized.doc",eb="gen_ai.response.id",tb="gen_ai.response.service_tier",nb="gen_ai.response.system_fingerprint",rb="gen_ai.usage.input_token_details",sb="gen_ai.usage.output_token_details",ab="langsmith.trace.session_id",ib="langsmith.trace.session_name",ob="langsmith.span.kind",cb="langsmith.trace.name",ub="langsmith.metadata",yd="langsmith.span.tags",lb="langsmith.request.streaming",db="langsmith.request.headers",hb=(...t)=>fetch(...t),wd=Symbol.for("ls:fetch_implementation"),fb=()=>{const t=globalThis[wd];return t?typeof t=="function"&&"Headers"in t&&"Request"in t&&"Response"in t:!1},pb=t=>async(...e)=>{if(t||ot("DEBUG")==="true"){const[r,s]=e;console.log(`\u2192 ${s?.method||"GET"} ${r}`)}const n=await(globalThis[wd]??hb)(...e);return(t||ot("DEBUG")==="true")&&console.log(`\u2190 ${n.status} ${n.statusText} ${n.url}`),n},bd=()=>ot("PROJECT")??Xt("LANGCHAIN_SESSION")??"default",vd={};function Ed(t){vd[t]||(console.warn(t),vd[t]=!0)}const mb=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function de(t,e){if(!mb.test(t)){const n=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(n)}return t}function gb(t){const e=typeof t=="string"?Date.parse(t):t;return En({msecs:e,seq:0})}function _b(t,e){throw new Error("dump() is not supported in browser environments.")}function yb(t){throw new Error("load() is not supported in browser environments.")}function wb(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}class bb{constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchFunc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??3600,this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.fetchFunc=e.fetchFunc,this.fetchFunc&&this.ttlSeconds!==null&&this.startRefreshLoop()}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){const e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e){const n=this.cache.get(e);if(!n){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,n),this._metrics.hits+=1,n.value}set(e,n){if(!this.cache.has(e)&&this.cache.size>=this.maxSize){const s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s)}const r={value:n,createdAt:Date.now()};this.cache.delete(e),this.cache.set(e,r)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(e){for(const[n,r]of this.cache.entries())r.value;_b()}load(e){const n=yb();if(!n)return 0;let r=0;const s=Date.now();for(const[a,i]of Object.entries(n)){if(this.cache.size>=this.maxSize)break;const o={value:i,createdAt:s};this.cache.set(a,o),r+=1}return r}startRefreshLoop(){this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn("Unexpected error in cache refresh loop:",e)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref()}getStaleKeys(){const e=[];for(const[n,r]of this.cache.entries())wb(r,this.ttlSeconds)&&e.push(n);return e}async refreshStaleEntries(){if(!this.fetchFunc)return;const e=this.getStaleKeys();if(e.length!==0)for(const n of e)try{const r=await this.fetchFunc(n);this.set(n,r),this._metrics.refreshes+=1}catch(r){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${n}:`,r)}}}const Sd="0.4.8";let Kt;const vb=()=>typeof window<"u"&&typeof window.document<"u",Eb=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Sb=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Td=()=>typeof Deno<"u",Tb=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Td(),xd=()=>Kt||(typeof Bun<"u"?Kt="bun":vb()?Kt="browser":Tb()?Kt="node":Eb()?Kt="webworker":Sb()?Kt="jsdom":Td()?Kt="deno":Kt="other",Kt);let ao;function Id(){if(ao===void 0){const t=xd(),e=Ib();ao={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:Sd,...e}}return ao}function Ad(){const t=xb(),e={},n=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[r,s]of Object.entries(t))typeof s=="string"&&!n.includes(r)&&!r.toLowerCase().includes("key")&&!r.toLowerCase().includes("secret")&&!r.toLowerCase().includes("token")&&(r==="LANGCHAIN_REVISION_ID"?e.revision_id=s:e[r]=s);return e}function xb(){const t={};try{if(typeof process<"u"&&process.env)for(const[e,n]of Object.entries(process.env))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&n!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof n=="string"?t[e]=n.slice(0,2)+"*".repeat(n.length-4)+n.slice(-2):t[e]=n)}catch{}return t}function Xt(t){try{return typeof process<"u"?process.env?.[t]:void 0}catch{return}}function ot(t){return Xt(`LANGSMITH_${t}`)||Xt(`LANGCHAIN_${t}`)}let io;function Ib(){if(io!==void 0)return io;const t=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(const n of t){const r=Xt(n);r!==void 0&&(e[n]=r)}return io=e,e}function kd(){return Xt("OTEL_ENABLED")==="true"||ot("OTEL_ENABLED")==="true"}class Ab{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...n){!this.hasWarned&&kd()&&(console.warn(\'You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\\n```\\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\\ninitializeOTEL();\\n```\\nat the beginning of your code.\'),this.hasWarned=!0);let r;if(n.length===1&&typeof n[0]=="function"?r=n[0]:n.length===2&&typeof n[1]=="function"?r=n[1]:n.length===3&&typeof n[2]=="function"&&(r=n[2]),typeof r=="function")return r()}}class kb{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new Ab})}getTracer(e,n){return this.mockTracer}getActiveSpan(){}setSpan(e,n){return e}getSpan(e){}setSpanContext(e,n){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}}class Ob{active(){return{}}with(e,n){return n()}}const oo=Symbol.for("ls:otel_trace"),co=Symbol.for("ls:otel_context"),Od=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),$b=new kb,Cb=new Ob;class Rb{getTraceInstance(){return globalThis[oo]??$b}getContextInstance(){return globalThis[co]??Cb}initializeGlobalInstances(e){globalThis[oo]===void 0&&(globalThis[oo]=e.trace),globalThis[co]===void 0&&(globalThis[co]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[Od]=e}getDefaultOTLPTracerComponents(){return globalThis[Od]??void 0}}const uo=new Rb;function $d(){return uo.getTraceInstance()}function Nb(){return uo.getContextInstance()}function Pb(){return uo.getDefaultOTLPTracerComponents()}const Mb={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function Lb(t){return Mb[t]||t}class jb{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,n){for(const r of e)try{if(!r.run)continue;if(r.operation==="post"){const s=this.createSpanForRun(r,r.run,n.get(r.id));s&&!r.run.end_time&&this.spans.set(r.id,s)}else this.updateSpanForRun(r,r.run)}catch(s){console.error(`Error processing operation ${r.id}:`,s)}}createSpanForRun(e,n,r){const s=r&&$d().getSpan(r);if(s)try{return this.finishSpanSetup(s,n,e)}catch(a){console.error(`Failed to create span for run ${e.id}:`,a);return}}finishSpanSetup(e,n,r){return this.setSpanAttributes(e,n,r),n.error?(e.setStatus({code:2}),e.recordException(new Error(n.error))):e.setStatus({code:1}),n.end_time&&e.end(new Date(n.end_time)),e}updateSpanForRun(e,n){try{const r=this.spans.get(e.id);if(!r){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(r,n,e),n.error?(r.setStatus({code:2}),r.recordException(new Error(n.error))):r.setStatus({code:1});const s=n.end_time;s&&(r.end(new Date(s)),this.spans.delete(e.id))}catch(r){console.error(`Failed to update span for run ${e.id}:`,r)}}extractModelName(e){if(e.extra?.metadata){const n=e.extra.metadata;if(n.ls_model_name)return n.ls_model_name;if(n.invocation_params){const r=n.invocation_params;if(r.model)return r.model;if(r.model_name)return r.model_name}}}setSpanAttributes(e,n,r){if("run_type"in n&&n.run_type){e.setAttribute(ob,n.run_type);const o=Lb(n.run_type||"chain");e.setAttribute(Dw,o)}"name"in n&&n.name&&e.setAttribute(cb,n.name),"session_id"in n&&n.session_id&&e.setAttribute(ab,n.session_id),"session_name"in n&&n.session_name&&e.setAttribute(ib,n.session_name),this.setGenAiSystem(e,n);const s=this.extractModelName(n);s&&e.setAttribute(pd,s),"prompt_tokens"in n&&typeof n.prompt_tokens=="number"&&e.setAttribute(md,n.prompt_tokens),"completion_tokens"in n&&typeof n.completion_tokens=="number"&&e.setAttribute(gd,n.completion_tokens),"total_tokens"in n&&typeof n.total_tokens=="number"&&e.setAttribute(_d,n.total_tokens),this.setInvocationParameters(e,n);const a=n.extra?.metadata||{};for(const[o,c]of Object.entries(a))c!=null&&e.setAttribute(`${ub}.${o}`,String(c));const i=n.tags;if(i&&Array.isArray(i)?e.setAttribute(yd,i.join(", ")):i&&e.setAttribute(yd,String(i)),"serialized"in n&&typeof n.serialized=="object"){const o=n.serialized;o.name&&e.setAttribute(Xw,String(o.name)),o.signature&&e.setAttribute(Yw,String(o.signature)),o.doc&&e.setAttribute(Qw,String(o.doc))}this.setIOAttributes(e,r)}setGenAiSystem(e,n){let r="langchain";const s=this.extractModelName(n);if(s){const a=s.toLowerCase();a.includes("anthropic")||a.startsWith("claude")?r="anthropic":a.includes("bedrock")?r="aws.bedrock":a.includes("azure")&&a.includes("openai")?r="az.ai.openai":a.includes("azure")&&a.includes("inference")?r="az.ai.inference":a.includes("cohere")?r="cohere":a.includes("deepseek")?r="deepseek":a.includes("gemini")?r="gemini":a.includes("groq")?r="groq":a.includes("watson")||a.includes("ibm")?r="ibm.watsonx.ai":a.includes("mistral")?r="mistral_ai":a.includes("gpt")||a.includes("openai")?r="openai":a.includes("perplexity")||a.includes("sonar")?r="perplexity":a.includes("vertex")?r="vertex_ai":(a.includes("xai")||a.includes("grok"))&&(r="xai")}e.setAttribute(zw,r)}setInvocationParameters(e,n){if(!n.extra?.metadata?.invocation_params)return;const r=n.extra.metadata.invocation_params;r.max_tokens!==void 0&&e.setAttribute(Uw,r.max_tokens),r.temperature!==void 0&&e.setAttribute(Bw,r.temperature),r.top_p!==void 0&&e.setAttribute(Zw,r.top_p),r.frequency_penalty!==void 0&&e.setAttribute(qw,r.frequency_penalty),r.presence_penalty!==void 0&&e.setAttribute(Vw,r.presence_penalty)}setIOAttributes(e,n){if(n.run.inputs)try{const r=n.run.inputs;typeof r=="object"&&r!==null&&(r.model&&Array.isArray(r.messages)&&e.setAttribute(pd,r.model),r.stream!==void 0&&e.setAttribute(lb,r.stream),r.extra_headers&&e.setAttribute(db,JSON.stringify(r.extra_headers)),r.extra_query&&e.setAttribute(Jw,JSON.stringify(r.extra_query)),r.extra_body&&e.setAttribute(Kw,JSON.stringify(r.extra_body))),e.setAttribute(Gw,JSON.stringify(r))}catch(r){console.debug(`Failed to process inputs for run ${n.id}`,r)}if(n.run.outputs)try{const r=n.run.outputs,s=this.getUnifiedRunTokens(r);if(s&&(e.setAttribute(md,s[0]),e.setAttribute(gd,s[1]),e.setAttribute(_d,s[0]+s[1])),r&&typeof r=="object"){if(r.model&&e.setAttribute(Fw,String(r.model)),r.id&&e.setAttribute(eb,r.id),r.choices&&Array.isArray(r.choices)){const a=r.choices.map(i=>i.finish_reason).filter(i=>i).map(String);a.length>0&&e.setAttribute(Hw,a.join(", "))}if(r.service_tier&&e.setAttribute(tb,r.service_tier),r.system_fingerprint&&e.setAttribute(nb,r.system_fingerprint),r.usage_metadata&&typeof r.usage_metadata=="object"){const a=r.usage_metadata;a.input_token_details&&e.setAttribute(rb,JSON.stringify(a.input_token_details)),a.output_token_details&&e.setAttribute(sb,JSON.stringify(a.output_token_details))}}e.setAttribute(Ww,JSON.stringify(r))}catch(r){console.debug(`Failed to process outputs for run ${n.id}`,r)}}getUnifiedRunTokens(e){if(!e)return null;let n=this.extractUnifiedRunTokens(e.usage_metadata);if(n)return n;const r=Object.keys(e);for(const i of r){const o=e[i];if(!(!o||typeof o!="object")&&(n=this.extractUnifiedRunTokens(o.usage_metadata),n||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(n=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),n)))return n}const s=e.generations||[];if(!Array.isArray(s))return null;const a=Array.isArray(s[0])?s.flat():s;for(const i of a)if(typeof i=="object"&&i.message&&typeof i.message=="object"&&i.message.kwargs&&typeof i.message.kwargs=="object"&&(n=this.extractUnifiedRunTokens(i.message.kwargs.usage_metadata),n))return n;return null}extractUnifiedRunTokens(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}}const Db=Object.prototype.toString,zb=t=>Db.call(t)==="[object Error]",Fb=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Ub(t){if(!(t&&zb(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;const{message:n,stack:r}=t;return n==="Load failed"?r===void 0||"__sentry_captured__"in t:n.startsWith("error sending request for url")?!0:Fb.has(n)}function Bb(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Ws(t,e,{min:n=0,allowInfinity:r=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \\`${t}\\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(e))throw new TypeError(`Expected \\`${t}\\` to be a finite number.`);if(e<n)throw new TypeError(`Expected \\`${t}\\` to be \u2265 ${n}.`)}}let Zb=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function qb(t,e){const n=Math.max(1,t+1),r=e.randomize?Math.random()+1:1;let s=Math.round(r*e.minTimeout*e.factor**(n-1));return s=Math.min(s,e.maxTimeout),s}function Cd(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}async function Vb({error:t,attemptNumber:e,retriesConsumed:n,startTime:r,options:s}){const a=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(a instanceof Zb)throw a.originalError;const i=Number.isFinite(s.retries)?Math.max(0,s.retries-n):s.retries,o=s.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:a,attemptNumber:e,retriesLeft:i,retriesConsumed:n});if(await s.onFailedAttempt(c),Cd(r,o)<=0)throw a;const u=await s.shouldConsumeRetry(c),l=Cd(r,o);if(l<=0||i<=0)throw a;if(a instanceof TypeError&&!Ub(a)){if(u)throw a;return s.signal?.throwIfAborted(),!1}if(!await s.shouldRetry(c))throw a;if(!u)return s.signal?.throwIfAborted(),!1;const d=qb(n,s),f=Math.min(d,l);return f>0&&await new Promise((h,p)=>{const m=()=>{clearTimeout(y),s.signal?.removeEventListener("abort",m),p(s.signal.reason)},y=setTimeout(()=>{s.signal?.removeEventListener("abort",m),h()},f);s.unref&&y.unref?.(),s.signal?.addEventListener("abort",m,{once:!0})}),s.signal?.throwIfAborted(),!0}async function Hb(t,e={}){if(e={...e},Bb(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,Ws("factor",e.factor,{min:0,allowInfinity:!1}),Ws("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Ws("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Ws("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let n=0,r=0;const s=performance.now();for(;!Number.isFinite(e.retries)||r<=e.retries;){n++;try{e.signal?.throwIfAborted();const a=await t(n);return e.signal?.throwIfAborted(),a}catch(a){await Vb({error:a,attemptNumber:n,retriesConsumed:r,startTime:s,options:e})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Js={},lo={exports:{}},Rd;function Gb(){return Rd||(Rd=1,(function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function s(c,u,l){this.fn=c,this.context=u,this.once=l||!1}function a(c,u,l,d,f){if(typeof l!="function")throw new TypeError("The listener must be a function");var h=new s(l,d||c,f),p=n?n+u:u;return c._events[p]?c._events[p].fn?c._events[p]=[c._events[p],h]:c._events[p].push(h):(c._events[p]=h,c._eventsCount++),c}function i(c,u){--c._eventsCount===0?c._events=new r:delete c._events[u]}function o(){this._events=new r,this._eventsCount=0}o.prototype.eventNames=function(){var u=[],l,d;if(this._eventsCount===0)return u;for(d in l=this._events)e.call(l,d)&&u.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(l)):u},o.prototype.listeners=function(u){var l=n?n+u:u,d=this._events[l];if(!d)return[];if(d.fn)return[d.fn];for(var f=0,h=d.length,p=new Array(h);f<h;f++)p[f]=d[f].fn;return p},o.prototype.listenerCount=function(u){var l=n?n+u:u,d=this._events[l];return d?d.fn?1:d.length:0},o.prototype.emit=function(u,l,d,f,h,p){var m=n?n+u:u;if(!this._events[m])return!1;var y=this._events[m],v=arguments.length,w,E;if(y.fn){switch(y.once&&this.removeListener(u,y.fn,void 0,!0),v){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,l),!0;case 3:return y.fn.call(y.context,l,d),!0;case 4:return y.fn.call(y.context,l,d,f),!0;case 5:return y.fn.call(y.context,l,d,f,h),!0;case 6:return y.fn.call(y.context,l,d,f,h,p),!0}for(E=1,w=new Array(v-1);E<v;E++)w[E-1]=arguments[E];y.fn.apply(y.context,w)}else{var x=y.length,A;for(E=0;E<x;E++)switch(y[E].once&&this.removeListener(u,y[E].fn,void 0,!0),v){case 1:y[E].fn.call(y[E].context);break;case 2:y[E].fn.call(y[E].context,l);break;case 3:y[E].fn.call(y[E].context,l,d);break;case 4:y[E].fn.call(y[E].context,l,d,f);break;default:if(!w)for(A=1,w=new Array(v-1);A<v;A++)w[A-1]=arguments[A];y[E].fn.apply(y[E].context,w)}}return!0},o.prototype.on=function(u,l,d){return a(this,u,l,d,!1)},o.prototype.once=function(u,l,d){return a(this,u,l,d,!0)},o.prototype.removeListener=function(u,l,d,f){var h=n?n+u:u;if(!this._events[h])return this;if(!l)return i(this,h),this;var p=this._events[h];if(p.fn)p.fn===l&&(!f||p.once)&&(!d||p.context===d)&&i(this,h);else{for(var m=0,y=[],v=p.length;m<v;m++)(p[m].fn!==l||f&&!p[m].once||d&&p[m].context!==d)&&y.push(p[m]);y.length?this._events[h]=y.length===1?y[0]:y:i(this,h)}return this},o.prototype.removeAllListeners=function(u){var l;return u?(l=n?n+u:u,this._events[l]&&i(this,l)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=n,o.EventEmitter=o,t.exports=o})(lo)),lo.exports}var Ur={exports:{}},ho,Nd;function Wb(){return Nd||(Nd=1,ho=(t,e)=>(e=e||(()=>{}),t.then(n=>new Promise(r=>{r(e())}).then(()=>n),n=>new Promise(r=>{r(e())}).then(()=>{throw n})))),ho}var Pd;function Jb(){if(Pd)return Ur.exports;Pd=1;const t=Wb();class e extends Error{constructor(s){super(s),this.name="TimeoutError"}}const n=(r,s,a)=>new Promise((i,o)=>{if(typeof s!="number"||s<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(s===1/0){i(r);return}const c=setTimeout(()=>{if(typeof a=="function"){try{i(a())}catch(d){o(d)}return}const u=typeof a=="string"?a:`Promise timed out after ${s} milliseconds`,l=a instanceof Error?a:new e(u);typeof r.cancel=="function"&&r.cancel(),o(l)},s);t(r.then(i,o),()=>{clearTimeout(c)})});return Ur.exports=n,Ur.exports.default=n,Ur.exports.TimeoutError=e,Ur.exports}var Ks={},Xs={},Md;function Kb(){if(Md)return Xs;Md=1,Object.defineProperty(Xs,"__esModule",{value:!0});function t(e,n,r){let s=0,a=e.length;for(;a>0;){const i=a/2|0;let o=s+i;r(e[o],n)<=0?(s=++o,a-=i+1):a=i}return s}return Xs.default=t,Xs}var Ld;function Xb(){if(Ld)return Ks;Ld=1,Object.defineProperty(Ks,"__esModule",{value:!0});const t=Kb();class e{constructor(){this._queue=[]}enqueue(r,s){s=Object.assign({priority:0},s);const a={priority:s.priority,run:r};if(this.size&&this._queue[this.size-1].priority>=s.priority){this._queue.push(a);return}const i=t.default(this._queue,a,(o,c)=>c.priority-o.priority);this._queue.splice(i,0,a)}dequeue(){const r=this._queue.shift();return r?.run}filter(r){return this._queue.filter(s=>s.priority===r.priority).map(s=>s.run)}get size(){return this._queue.length}}return Ks.default=e,Ks}var jd;function Yb(){if(jd)return Js;jd=1,Object.defineProperty(Js,"__esModule",{value:!0});const t=Gb(),e=Jb(),n=Xb(),r=()=>{},s=new e.TimeoutError;class a extends t{constructor(o){var c,u,l,d;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=r,this._resolveIdle=r,o=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:n.default},o),!(typeof o.intervalCap=="number"&&o.intervalCap>=1))throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${(u=(c=o.intervalCap)===null||c===void 0?void 0:c.toString())!==null&&u!==void 0?u:""}\\` (${typeof o.intervalCap})`);if(o.interval===void 0||!(Number.isFinite(o.interval)&&o.interval>=0))throw new TypeError(`Expected \\`interval\\` to be a finite number >= 0, got \\`${(d=(l=o.interval)===null||l===void 0?void 0:l.toString())!==null&&d!==void 0?d:""}\\` (${typeof o.interval})`);this._carryoverConcurrencyCount=o.carryoverConcurrencyCount,this._isIntervalIgnored=o.intervalCap===1/0||o.interval===0,this._intervalCap=o.intervalCap,this._interval=o.interval,this._queue=new o.queueClass,this._queueClass=o.queueClass,this.concurrency=o.concurrency,this._timeout=o.timeout,this._throwOnTimeout=o.throwOnTimeout===!0,this._isPaused=o.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=r,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=r,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const o=Date.now();if(this._intervalId===void 0){const c=this._intervalEnd-o;if(c<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},c)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const o=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const c=this._queue.dequeue();return c?(this.emit("active"),c(),o&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(o){if(!(typeof o=="number"&&o>=1))throw new TypeError(`Expected \\`concurrency\\` to be a number from 1 and up, got \\`${o}\\` (${typeof o})`);this._concurrency=o,this._processQueue()}async add(o,c={}){return new Promise((u,l)=>{const d=async()=>{this._pendingCount++,this._intervalCount++;try{const f=this._timeout===void 0&&c.timeout===void 0?o():e.default(Promise.resolve(o()),c.timeout===void 0?this._timeout:c.timeout,()=>{(c.throwOnTimeout===void 0?this._throwOnTimeout:c.throwOnTimeout)&&l(s)});u(await f)}catch(f){l(f)}this._next()};this._queue.enqueue(d,c),this._tryToStartAnother(),this.emit("add")})}async addAll(o,c){return Promise.all(o.map(async u=>this.add(u,c)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(o=>{const c=this._resolveEmpty;this._resolveEmpty=()=>{c(),o()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(o=>{const c=this._resolveIdle;this._resolveIdle=()=>{c(),o()}})}get size(){return this._queue.size}sizeBy(o){return this._queue.filter(o).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(o){this._timeout=o}}return Js.default=a,Js}var Qb=Yb(),cn=Ms(Qb);const ev=[408,425,429,500,502,503,504];let Dd=class{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxQueueSizeBytes",{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}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.maxQueueSizeBytes=e.maxQueueSizeBytes,"default"in cn?this.queue=new cn.default({concurrency:this.maxConcurrency}):this.queue=new cn({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...n){return this.callWithOptions({},e,...n)}callWithOptions(e,n,...r){const s=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&s>0&&this.queueSizeBytes+s>this.maxQueueSizeBytes)return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${s} bytes.`));s>0&&(this.queueSizeBytes+=s);const a=this.onFailedResponseHook;let i=this.queue.add(()=>Hb(()=>n(...r).catch(o=>{throw o instanceof Error?o:new Error(o)}),{async onFailedAttempt({error:o}){if(typeof o!="object"||o==null)throw o;const c="message"in o&&typeof o.message=="string"?o.message:void 0;if(c?.startsWith("Cancel")||c?.startsWith("TimeoutError")||c?.startsWith("AbortError")||"name"in o&&o.name==="TimeoutError"||"code"in o&&o.code==="ECONNABORTED")throw o;const u="response"in o?o.response:void 0;if(a&&await a(u))return;const l=u?.status??("status"in o?o.status:void 0);if(l!=null&&(typeof l=="number"||typeof l=="string")&&!ev.includes(+l))throw o},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return s>0&&(i=i.finally(()=>{this.queueSizeBytes-=s})),e.signal?Promise.race([i,new Promise((o,c)=>{e.signal?.addEventListener("abort",()=>{c(new Error("AbortError"))})})]):i}};function zd(t){return typeof t?._getType=="function"}function Fd(t){const e={type:t._getType(),data:{content:t.content}};return t?.additional_kwargs&&Object.keys(t.additional_kwargs).length>0&&(e.data.additional_kwargs={...t.additional_kwargs}),e}var Ys={exports:{}},fo,Ud;function Qs(){if(Ud)return fo;Ud=1;const t="2.0.0",e=256,n=Number.MAX_SAFE_INTEGER||9007199254740991,r=16,s=e-6;return fo={MAX_LENGTH:e,MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:s,MAX_SAFE_INTEGER:n,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:t,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},fo}var po,Bd;function ea(){return Bd||(Bd=1,po=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\\bsemver\\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{}),po}var Zd;function Br(){return Zd||(Zd=1,(function(t,e){const{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:s}=Qs(),a=ea();e=t.exports={};const i=e.re=[],o=e.safeRe=[],c=e.src=[],u=e.safeSrc=[],l=e.t={};let d=0;const f="[a-zA-Z0-9-]",h=[["\\\\s",1],["\\\\d",s],[f,r]],p=y=>{for(const[v,w]of h)y=y.split(`${v}*`).join(`${v}{0,${w}}`).split(`${v}+`).join(`${v}{1,${w}}`);return y},m=(y,v,w)=>{const E=p(v),x=d++;a(y,x,v),l[y]=x,c[x]=v,u[x]=E,i[x]=new RegExp(v,w?"g":void 0),o[x]=new RegExp(E,w?"g":void 0)};m("NUMERICIDENTIFIER","0|[1-9]\\\\d*"),m("NUMERICIDENTIFIERLOOSE","\\\\d+"),m("NONNUMERICIDENTIFIER",`\\\\d*[a-zA-Z-]${f}*`),m("MAINVERSION",`(${c[l.NUMERICIDENTIFIER]})\\\\.(${c[l.NUMERICIDENTIFIER]})\\\\.(${c[l.NUMERICIDENTIFIER]})`),m("MAINVERSIONLOOSE",`(${c[l.NUMERICIDENTIFIERLOOSE]})\\\\.(${c[l.NUMERICIDENTIFIERLOOSE]})\\\\.(${c[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASEIDENTIFIER",`(?:${c[l.NONNUMERICIDENTIFIER]}|${c[l.NUMERICIDENTIFIER]})`),m("PRERELEASEIDENTIFIERLOOSE",`(?:${c[l.NONNUMERICIDENTIFIER]}|${c[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASE",`(?:-(${c[l.PRERELEASEIDENTIFIER]}(?:\\\\.${c[l.PRERELEASEIDENTIFIER]})*))`),m("PRERELEASELOOSE",`(?:-?(${c[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\\\.${c[l.PRERELEASEIDENTIFIERLOOSE]})*))`),m("BUILDIDENTIFIER",`${f}+`),m("BUILD",`(?:\\\\+(${c[l.BUILDIDENTIFIER]}(?:\\\\.${c[l.BUILDIDENTIFIER]})*))`),m("FULLPLAIN",`v?${c[l.MAINVERSION]}${c[l.PRERELEASE]}?${c[l.BUILD]}?`),m("FULL",`^${c[l.FULLPLAIN]}$`),m("LOOSEPLAIN",`[v=\\\\s]*${c[l.MAINVERSIONLOOSE]}${c[l.PRERELEASELOOSE]}?${c[l.BUILD]}?`),m("LOOSE",`^${c[l.LOOSEPLAIN]}$`),m("GTLT","((?:<|>)?=?)"),m("XRANGEIDENTIFIERLOOSE",`${c[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`),m("XRANGEIDENTIFIER",`${c[l.NUMERICIDENTIFIER]}|x|X|\\\\*`),m("XRANGEPLAIN",`[v=\\\\s]*(${c[l.XRANGEIDENTIFIER]})(?:\\\\.(${c[l.XRANGEIDENTIFIER]})(?:\\\\.(${c[l.XRANGEIDENTIFIER]})(?:${c[l.PRERELEASE]})?${c[l.BUILD]}?)?)?`),m("XRANGEPLAINLOOSE",`[v=\\\\s]*(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:${c[l.PRERELEASELOOSE]})?${c[l.BUILD]}?)?)?`),m("XRANGE",`^${c[l.GTLT]}\\\\s*${c[l.XRANGEPLAIN]}$`),m("XRANGELOOSE",`^${c[l.GTLT]}\\\\s*${c[l.XRANGEPLAINLOOSE]}$`),m("COERCEPLAIN",`(^|[^\\\\d])(\\\\d{1,${n}})(?:\\\\.(\\\\d{1,${n}}))?(?:\\\\.(\\\\d{1,${n}}))?`),m("COERCE",`${c[l.COERCEPLAIN]}(?:$|[^\\\\d])`),m("COERCEFULL",c[l.COERCEPLAIN]+`(?:${c[l.PRERELEASE]})?(?:${c[l.BUILD]})?(?:$|[^\\\\d])`),m("COERCERTL",c[l.COERCE],!0),m("COERCERTLFULL",c[l.COERCEFULL],!0),m("LONETILDE","(?:~>?)"),m("TILDETRIM",`(\\\\s*)${c[l.LONETILDE]}\\\\s+`,!0),e.tildeTrimReplace="$1~",m("TILDE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAIN]}$`),m("TILDELOOSE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAINLOOSE]}$`),m("LONECARET","(?:\\\\^)"),m("CARETTRIM",`(\\\\s*)${c[l.LONECARET]}\\\\s+`,!0),e.caretTrimReplace="$1^",m("CARET",`^${c[l.LONECARET]}${c[l.XRANGEPLAIN]}$`),m("CARETLOOSE",`^${c[l.LONECARET]}${c[l.XRANGEPLAINLOOSE]}$`),m("COMPARATORLOOSE",`^${c[l.GTLT]}\\\\s*(${c[l.LOOSEPLAIN]})$|^$`),m("COMPARATOR",`^${c[l.GTLT]}\\\\s*(${c[l.FULLPLAIN]})$|^$`),m("COMPARATORTRIM",`(\\\\s*)${c[l.GTLT]}\\\\s*(${c[l.LOOSEPLAIN]}|${c[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",m("HYPHENRANGE",`^\\\\s*(${c[l.XRANGEPLAIN]})\\\\s+-\\\\s+(${c[l.XRANGEPLAIN]})\\\\s*$`),m("HYPHENRANGELOOSE",`^\\\\s*(${c[l.XRANGEPLAINLOOSE]})\\\\s+-\\\\s+(${c[l.XRANGEPLAINLOOSE]})\\\\s*$`),m("STAR","(<|>)?=?\\\\s*\\\\*"),m("GTE0","^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$"),m("GTE0PRE","^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$")})(Ys,Ys.exports)),Ys.exports}var mo,qd;function go(){if(qd)return mo;qd=1;const t=Object.freeze({loose:!0}),e=Object.freeze({});return mo=r=>r?typeof r!="object"?t:r:e,mo}var _o,Vd;function Hd(){if(Vd)return _o;Vd=1;const t=/^[0-9]+$/,e=(r,s)=>{if(typeof r=="number"&&typeof s=="number")return r===s?0:r<s?-1:1;const a=t.test(r),i=t.test(s);return a&&i&&(r=+r,s=+s),r===s?0:a&&!i?-1:i&&!a?1:r<s?-1:1};return _o={compareIdentifiers:e,rcompareIdentifiers:(r,s)=>e(s,r)},_o}var yo,Gd;function ct(){if(Gd)return yo;Gd=1;const t=ea(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:n}=Qs(),{safeRe:r,t:s}=Br(),a=go(),{compareIdentifiers:i}=Hd();class o{constructor(u,l){if(l=a(l),u instanceof o){if(u.loose===!!l.loose&&u.includePrerelease===!!l.includePrerelease)return u;u=u.version}else if(typeof u!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof u}".`);if(u.length>e)throw new TypeError(`version is longer than ${e} characters`);t("SemVer",u,l),this.options=l,this.loose=!!l.loose,this.includePrerelease=!!l.includePrerelease;const d=u.trim().match(l.loose?r[s.LOOSE]:r[s.FULL]);if(!d)throw new TypeError(`Invalid Version: ${u}`);if(this.raw=u,this.major=+d[1],this.minor=+d[2],this.patch=+d[3],this.major>n||this.major<0)throw new TypeError("Invalid major version");if(this.minor>n||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>n||this.patch<0)throw new TypeError("Invalid patch version");d[4]?this.prerelease=d[4].split(".").map(f=>{if(/^[0-9]+$/.test(f)){const h=+f;if(h>=0&&h<n)return h}return f}):this.prerelease=[],this.build=d[5]?d[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(u){if(t("SemVer.compare",this.version,this.options,u),!(u instanceof o)){if(typeof u=="string"&&u===this.version)return 0;u=new o(u,this.options)}return u.version===this.version?0:this.compareMain(u)||this.comparePre(u)}compareMain(u){return u instanceof o||(u=new o(u,this.options)),this.major<u.major?-1:this.major>u.major?1:this.minor<u.minor?-1:this.minor>u.minor?1:this.patch<u.patch?-1:this.patch>u.patch?1:0}comparePre(u){if(u instanceof o||(u=new o(u,this.options)),this.prerelease.length&&!u.prerelease.length)return-1;if(!this.prerelease.length&&u.prerelease.length)return 1;if(!this.prerelease.length&&!u.prerelease.length)return 0;let l=0;do{const d=this.prerelease[l],f=u.prerelease[l];if(t("prerelease compare",l,d,f),d===void 0&&f===void 0)return 0;if(f===void 0)return 1;if(d===void 0)return-1;if(d===f)continue;return i(d,f)}while(++l)}compareBuild(u){u instanceof o||(u=new o(u,this.options));let l=0;do{const d=this.build[l],f=u.build[l];if(t("build compare",l,d,f),d===void 0&&f===void 0)return 0;if(f===void 0)return 1;if(d===void 0)return-1;if(d===f)continue;return i(d,f)}while(++l)}inc(u,l,d){if(u.startsWith("pre")){if(!l&&d===!1)throw new Error("invalid increment argument: identifier is empty");if(l){const f=`-${l}`.match(this.options.loose?r[s.PRERELEASELOOSE]:r[s.PRERELEASE]);if(!f||f[1]!==l)throw new Error(`invalid identifier: ${l}`)}}switch(u){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",l,d);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",l,d);break;case"prepatch":this.prerelease.length=0,this.inc("patch",l,d),this.inc("pre",l,d);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",l,d),this.inc("pre",l,d);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const f=Number(d)?1:0;if(this.prerelease.length===0)this.prerelease=[f];else{let h=this.prerelease.length;for(;--h>=0;)typeof this.prerelease[h]=="number"&&(this.prerelease[h]++,h=-2);if(h===-1){if(l===this.prerelease.join(".")&&d===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(f)}}if(l){let h=[l,f];d===!1&&(h=[l]),i(this.prerelease[0],l)===0?isNaN(this.prerelease[1])&&(this.prerelease=h):this.prerelease=h}break}default:throw new Error(`invalid increment argument: ${u}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return yo=o,yo}var wo,Wd;function rr(){if(Wd)return wo;Wd=1;const t=ct();return wo=(n,r,s=!1)=>{if(n instanceof t)return n;try{return new t(n,r)}catch(a){if(!s)return null;throw a}},wo}var bo,Jd;function tv(){if(Jd)return bo;Jd=1;const t=rr();return bo=(n,r)=>{const s=t(n,r);return s?s.version:null},bo}var vo,Kd;function nv(){if(Kd)return vo;Kd=1;const t=rr();return vo=(n,r)=>{const s=t(n.trim().replace(/^[=v]+/,""),r);return s?s.version:null},vo}var Eo,Xd;function rv(){if(Xd)return Eo;Xd=1;const t=ct();return Eo=(n,r,s,a,i)=>{typeof s=="string"&&(i=a,a=s,s=void 0);try{return new t(n instanceof t?n.version:n,s).inc(r,a,i).version}catch{return null}},Eo}var So,Yd;function sv(){if(Yd)return So;Yd=1;const t=rr();return So=(n,r)=>{const s=t(n,null,!0),a=t(r,null,!0),i=s.compare(a);if(i===0)return null;const o=i>0,c=o?s:a,u=o?a:s,l=!!c.prerelease.length;if(!!u.prerelease.length&&!l){if(!u.patch&&!u.minor)return"major";if(u.compareMain(c)===0)return u.minor&&!u.patch?"minor":"patch"}const f=l?"pre":"";return s.major!==a.major?f+"major":s.minor!==a.minor?f+"minor":s.patch!==a.patch?f+"patch":"prerelease"},So}var To,Qd;function av(){if(Qd)return To;Qd=1;const t=ct();return To=(n,r)=>new t(n,r).major,To}var xo,eh;function iv(){if(eh)return xo;eh=1;const t=ct();return xo=(n,r)=>new t(n,r).minor,xo}var Io,th;function ov(){if(th)return Io;th=1;const t=ct();return Io=(n,r)=>new t(n,r).patch,Io}var Ao,nh;function cv(){if(nh)return Ao;nh=1;const t=rr();return Ao=(n,r)=>{const s=t(n,r);return s&&s.prerelease.length?s.prerelease:null},Ao}var ko,rh;function Mt(){if(rh)return ko;rh=1;const t=ct();return ko=(n,r,s)=>new t(n,s).compare(new t(r,s)),ko}var Oo,sh;function uv(){if(sh)return Oo;sh=1;const t=Mt();return Oo=(n,r,s)=>t(r,n,s),Oo}var $o,ah;function lv(){if(ah)return $o;ah=1;const t=Mt();return $o=(n,r)=>t(n,r,!0),$o}var Co,ih;function Ro(){if(ih)return Co;ih=1;const t=ct();return Co=(n,r,s)=>{const a=new t(n,s),i=new t(r,s);return a.compare(i)||a.compareBuild(i)},Co}var No,oh;function dv(){if(oh)return No;oh=1;const t=Ro();return No=(n,r)=>n.sort((s,a)=>t(s,a,r)),No}var Po,ch;function hv(){if(ch)return Po;ch=1;const t=Ro();return Po=(n,r)=>n.sort((s,a)=>t(a,s,r)),Po}var Mo,uh;function ta(){if(uh)return Mo;uh=1;const t=Mt();return Mo=(n,r,s)=>t(n,r,s)>0,Mo}var Lo,lh;function jo(){if(lh)return Lo;lh=1;const t=Mt();return Lo=(n,r,s)=>t(n,r,s)<0,Lo}var Do,dh;function hh(){if(dh)return Do;dh=1;const t=Mt();return Do=(n,r,s)=>t(n,r,s)===0,Do}var zo,fh;function ph(){if(fh)return zo;fh=1;const t=Mt();return zo=(n,r,s)=>t(n,r,s)!==0,zo}var Fo,mh;function Uo(){if(mh)return Fo;mh=1;const t=Mt();return Fo=(n,r,s)=>t(n,r,s)>=0,Fo}var Bo,gh;function Zo(){if(gh)return Bo;gh=1;const t=Mt();return Bo=(n,r,s)=>t(n,r,s)<=0,Bo}var qo,_h;function yh(){if(_h)return qo;_h=1;const t=hh(),e=ph(),n=ta(),r=Uo(),s=jo(),a=Zo();return qo=(o,c,u,l)=>{switch(c){case"===":return typeof o=="object"&&(o=o.version),typeof u=="object"&&(u=u.version),o===u;case"!==":return typeof o=="object"&&(o=o.version),typeof u=="object"&&(u=u.version),o!==u;case"":case"=":case"==":return t(o,u,l);case"!=":return e(o,u,l);case">":return n(o,u,l);case">=":return r(o,u,l);case"<":return s(o,u,l);case"<=":return a(o,u,l);default:throw new TypeError(`Invalid operator: ${c}`)}},qo}var Vo,wh;function fv(){if(wh)return Vo;wh=1;const t=ct(),e=rr(),{safeRe:n,t:r}=Br();return Vo=(a,i)=>{if(a instanceof t)return a;if(typeof a=="number"&&(a=String(a)),typeof a!="string")return null;i=i||{};let o=null;if(!i.rtl)o=a.match(i.includePrerelease?n[r.COERCEFULL]:n[r.COERCE]);else{const h=i.includePrerelease?n[r.COERCERTLFULL]:n[r.COERCERTL];let p;for(;(p=h.exec(a))&&(!o||o.index+o[0].length!==a.length);)(!o||p.index+p[0].length!==o.index+o[0].length)&&(o=p),h.lastIndex=p.index+p[1].length+p[2].length;h.lastIndex=-1}if(o===null)return null;const c=o[2],u=o[3]||"0",l=o[4]||"0",d=i.includePrerelease&&o[5]?`-${o[5]}`:"",f=i.includePrerelease&&o[6]?`+${o[6]}`:"";return e(`${c}.${u}.${l}${d}${f}`,i)},Vo}var Ho,bh;function pv(){if(bh)return Ho;bh=1;class t{constructor(){this.max=1e3,this.map=new Map}get(n){const r=this.map.get(n);if(r!==void 0)return this.map.delete(n),this.map.set(n,r),r}delete(n){return this.map.delete(n)}set(n,r){if(!this.delete(n)&&r!==void 0){if(this.map.size>=this.max){const a=this.map.keys().next().value;this.delete(a)}this.map.set(n,r)}return this}}return Ho=t,Ho}var Go,vh;function Lt(){if(vh)return Go;vh=1;const t=/\\s+/g;class e{constructor(R,P){if(P=s(P),R instanceof e)return R.loose===!!P.loose&&R.includePrerelease===!!P.includePrerelease?R:new e(R.raw,P);if(R instanceof a)return this.raw=R.value,this.set=[[R]],this.formatted=void 0,this;if(this.options=P,this.loose=!!P.loose,this.includePrerelease=!!P.includePrerelease,this.raw=R.trim().replace(t," "),this.set=this.raw.split("||").map(H=>this.parseRange(H.trim())).filter(H=>H.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const H=this.set[0];if(this.set=this.set.filter(Y=>!m(Y[0])),this.set.length===0)this.set=[H];else if(this.set.length>1){for(const Y of this.set)if(Y.length===1&&y(Y[0])){this.set=[Y];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let R=0;R<this.set.length;R++){R>0&&(this.formatted+="||");const P=this.set[R];for(let H=0;H<P.length;H++)H>0&&(this.formatted+=" "),this.formatted+=P[H].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(R){const H=((this.options.includePrerelease&&h)|(this.options.loose&&p))+":"+R,Y=r.get(H);if(Y)return Y;const q=this.options.loose,ne=q?c[u.HYPHENRANGELOOSE]:c[u.HYPHENRANGE];R=R.replace(ne,Be(this.options.includePrerelease)),i("hyphen replace",R),R=R.replace(c[u.COMPARATORTRIM],l),i("comparator trim",R),R=R.replace(c[u.TILDETRIM],d),i("tilde trim",R),R=R.replace(c[u.CARETTRIM],f),i("caret trim",R);let me=R.split(" ").map(Ee=>w(Ee,this.options)).join(" ").split(/\\s+/).map(Ee=>X(Ee,this.options));q&&(me=me.filter(Ee=>(i("loose invalid filter",Ee,this.options),!!Ee.match(c[u.COMPARATORLOOSE])))),i("range list",me);const fe=new Map,Se=me.map(Ee=>new a(Ee,this.options));for(const Ee of Se){if(m(Ee))return[Ee];fe.set(Ee.value,Ee)}fe.size>1&&fe.has("")&&fe.delete("");const ze=[...fe.values()];return r.set(H,ze),ze}intersects(R,P){if(!(R instanceof e))throw new TypeError("a Range is required");return this.set.some(H=>v(H,P)&&R.set.some(Y=>v(Y,P)&&H.every(q=>Y.every(ne=>q.intersects(ne,P)))))}test(R){if(!R)return!1;if(typeof R=="string")try{R=new o(R,this.options)}catch{return!1}for(let P=0;P<this.set.length;P++)if(kt(this.set[P],R,this.options))return!0;return!1}}Go=e;const n=pv(),r=new n,s=go(),a=na(),i=ea(),o=ct(),{safeRe:c,t:u,comparatorTrimReplace:l,tildeTrimReplace:d,caretTrimReplace:f}=Br(),{FLAG_INCLUDE_PRERELEASE:h,FLAG_LOOSE:p}=Qs(),m=L=>L.value==="<0.0.0-0",y=L=>L.value==="",v=(L,R)=>{let P=!0;const H=L.slice();let Y=H.pop();for(;P&&H.length;)P=H.every(q=>Y.intersects(q,R)),Y=H.pop();return P},w=(L,R)=>(L=L.replace(c[u.BUILD],""),i("comp",L,R),L=N(L,R),i("caret",L),L=x(L,R),i("tildes",L),L=b(L,R),i("xrange",L),L=ue(L,R),i("stars",L),L),E=L=>!L||L.toLowerCase()==="x"||L==="*",x=(L,R)=>L.trim().split(/\\s+/).map(P=>A(P,R)).join(" "),A=(L,R)=>{const P=R.loose?c[u.TILDELOOSE]:c[u.TILDE];return L.replace(P,(H,Y,q,ne,me)=>{i("tilde",L,H,Y,q,ne,me);let fe;return E(Y)?fe="":E(q)?fe=`>=${Y}.0.0 <${+Y+1}.0.0-0`:E(ne)?fe=`>=${Y}.${q}.0 <${Y}.${+q+1}.0-0`:me?(i("replaceTilde pr",me),fe=`>=${Y}.${q}.${ne}-${me} <${Y}.${+q+1}.0-0`):fe=`>=${Y}.${q}.${ne} <${Y}.${+q+1}.0-0`,i("tilde return",fe),fe})},N=(L,R)=>L.trim().split(/\\s+/).map(P=>j(P,R)).join(" "),j=(L,R)=>{i("caret",L,R);const P=R.loose?c[u.CARETLOOSE]:c[u.CARET],H=R.includePrerelease?"-0":"";return L.replace(P,(Y,q,ne,me,fe)=>{i("caret",L,Y,q,ne,me,fe);let Se;return E(q)?Se="":E(ne)?Se=`>=${q}.0.0${H} <${+q+1}.0.0-0`:E(me)?q==="0"?Se=`>=${q}.${ne}.0${H} <${q}.${+ne+1}.0-0`:Se=`>=${q}.${ne}.0${H} <${+q+1}.0.0-0`:fe?(i("replaceCaret pr",fe),q==="0"?ne==="0"?Se=`>=${q}.${ne}.${me}-${fe} <${q}.${ne}.${+me+1}-0`:Se=`>=${q}.${ne}.${me}-${fe} <${q}.${+ne+1}.0-0`:Se=`>=${q}.${ne}.${me}-${fe} <${+q+1}.0.0-0`):(i("no pr"),q==="0"?ne==="0"?Se=`>=${q}.${ne}.${me}${H} <${q}.${ne}.${+me+1}-0`:Se=`>=${q}.${ne}.${me}${H} <${q}.${+ne+1}.0-0`:Se=`>=${q}.${ne}.${me} <${+q+1}.0.0-0`),i("caret return",Se),Se})},b=(L,R)=>(i("replaceXRanges",L,R),L.split(/\\s+/).map(P=>oe(P,R)).join(" ")),oe=(L,R)=>{L=L.trim();const P=R.loose?c[u.XRANGELOOSE]:c[u.XRANGE];return L.replace(P,(H,Y,q,ne,me,fe)=>{i("xRange",L,H,Y,q,ne,me,fe);const Se=E(q),ze=Se||E(ne),Ee=ze||E(me),_=Ee;return Y==="="&&_&&(Y=""),fe=R.includePrerelease?"-0":"",Se?Y===">"||Y==="<"?H="<0.0.0-0":H="*":Y&&_?(ze&&(ne=0),me=0,Y===">"?(Y=">=",ze?(q=+q+1,ne=0,me=0):(ne=+ne+1,me=0)):Y==="<="&&(Y="<",ze?q=+q+1:ne=+ne+1),Y==="<"&&(fe="-0"),H=`${Y+q}.${ne}.${me}${fe}`):ze?H=`>=${q}.0.0${fe} <${+q+1}.0.0-0`:Ee&&(H=`>=${q}.${ne}.0${fe} <${q}.${+ne+1}.0-0`),i("xRange return",H),H})},ue=(L,R)=>(i("replaceStars",L,R),L.trim().replace(c[u.STAR],"")),X=(L,R)=>(i("replaceGTE0",L,R),L.trim().replace(c[R.includePrerelease?u.GTE0PRE:u.GTE0],"")),Be=L=>(R,P,H,Y,q,ne,me,fe,Se,ze,Ee,_)=>(E(H)?P="":E(Y)?P=`>=${H}.0.0${L?"-0":""}`:E(q)?P=`>=${H}.${Y}.0${L?"-0":""}`:ne?P=`>=${P}`:P=`>=${P}${L?"-0":""}`,E(Se)?fe="":E(ze)?fe=`<${+Se+1}.0.0-0`:E(Ee)?fe=`<${Se}.${+ze+1}.0-0`:_?fe=`<=${Se}.${ze}.${Ee}-${_}`:L?fe=`<${Se}.${ze}.${+Ee+1}-0`:fe=`<=${fe}`,`${P} ${fe}`.trim()),kt=(L,R,P)=>{for(let H=0;H<L.length;H++)if(!L[H].test(R))return!1;if(R.prerelease.length&&!P.includePrerelease){for(let H=0;H<L.length;H++)if(i(L[H].semver),L[H].semver!==a.ANY&&L[H].semver.prerelease.length>0){const Y=L[H].semver;if(Y.major===R.major&&Y.minor===R.minor&&Y.patch===R.patch)return!0}return!1}return!0};return Go}var Wo,Eh;function na(){if(Eh)return Wo;Eh=1;const t=Symbol("SemVer ANY");class e{static get ANY(){return t}constructor(l,d){if(d=n(d),l instanceof e){if(l.loose===!!d.loose)return l;l=l.value}l=l.trim().split(/\\s+/).join(" "),i("comparator",l,d),this.options=d,this.loose=!!d.loose,this.parse(l),this.semver===t?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(l){const d=this.options.loose?r[s.COMPARATORLOOSE]:r[s.COMPARATOR],f=l.match(d);if(!f)throw new TypeError(`Invalid comparator: ${l}`);this.operator=f[1]!==void 0?f[1]:"",this.operator==="="&&(this.operator=""),f[2]?this.semver=new o(f[2],this.options.loose):this.semver=t}toString(){return this.value}test(l){if(i("Comparator.test",l,this.options.loose),this.semver===t||l===t)return!0;if(typeof l=="string")try{l=new o(l,this.options)}catch{return!1}return a(l,this.operator,this.semver,this.options)}intersects(l,d){if(!(l instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(l.value,d).test(this.value):l.operator===""?l.value===""?!0:new c(this.value,d).test(l.semver):(d=n(d),d.includePrerelease&&(this.value==="<0.0.0-0"||l.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||l.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&l.operator.startsWith(">")||this.operator.startsWith("<")&&l.operator.startsWith("<")||this.semver.version===l.semver.version&&this.operator.includes("=")&&l.operator.includes("=")||a(this.semver,"<",l.semver,d)&&this.operator.startsWith(">")&&l.operator.startsWith("<")||a(this.semver,">",l.semver,d)&&this.operator.startsWith("<")&&l.operator.startsWith(">")))}}Wo=e;const n=go(),{safeRe:r,t:s}=Br(),a=yh(),i=ea(),o=ct(),c=Lt();return Wo}var Jo,Sh;function ra(){if(Sh)return Jo;Sh=1;const t=Lt();return Jo=(n,r,s)=>{try{r=new t(r,s)}catch{return!1}return r.test(n)},Jo}var Ko,Th;function mv(){if(Th)return Ko;Th=1;const t=Lt();return Ko=(n,r)=>new t(n,r).set.map(s=>s.map(a=>a.value).join(" ").trim().split(" ")),Ko}var Xo,xh;function gv(){if(xh)return Xo;xh=1;const t=ct(),e=Lt();return Xo=(r,s,a)=>{let i=null,o=null,c=null;try{c=new e(s,a)}catch{return null}return r.forEach(u=>{c.test(u)&&(!i||o.compare(u)===-1)&&(i=u,o=new t(i,a))}),i},Xo}var Yo,Ih;function _v(){if(Ih)return Yo;Ih=1;const t=ct(),e=Lt();return Yo=(r,s,a)=>{let i=null,o=null,c=null;try{c=new e(s,a)}catch{return null}return r.forEach(u=>{c.test(u)&&(!i||o.compare(u)===1)&&(i=u,o=new t(i,a))}),i},Yo}var Qo,Ah;function yv(){if(Ah)return Qo;Ah=1;const t=ct(),e=Lt(),n=ta();return Qo=(s,a)=>{s=new e(s,a);let i=new t("0.0.0");if(s.test(i)||(i=new t("0.0.0-0"),s.test(i)))return i;i=null;for(let o=0;o<s.set.length;++o){const c=s.set[o];let u=null;c.forEach(l=>{const d=new t(l.semver.version);switch(l.operator){case">":d.prerelease.length===0?d.patch++:d.prerelease.push(0),d.raw=d.format();case"":case">=":(!u||n(d,u))&&(u=d);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${l.operator}`)}}),u&&(!i||n(i,u))&&(i=u)}return i&&s.test(i)?i:null},Qo}var ec,kh;function wv(){if(kh)return ec;kh=1;const t=Lt();return ec=(n,r)=>{try{return new t(n,r).range||"*"}catch{return null}},ec}var tc,Oh;function nc(){if(Oh)return tc;Oh=1;const t=ct(),e=na(),{ANY:n}=e,r=Lt(),s=ra(),a=ta(),i=jo(),o=Zo(),c=Uo();return tc=(l,d,f,h)=>{l=new t(l,h),d=new r(d,h);let p,m,y,v,w;switch(f){case">":p=a,m=o,y=i,v=">",w=">=";break;case"<":p=i,m=c,y=a,v="<",w="<=";break;default:throw new TypeError(\'Must provide a hilo val of "<" or ">"\')}if(s(l,d,h))return!1;for(let E=0;E<d.set.length;++E){const x=d.set[E];let A=null,N=null;if(x.forEach(j=>{j.semver===n&&(j=new e(">=0.0.0")),A=A||j,N=N||j,p(j.semver,A.semver,h)?A=j:y(j.semver,N.semver,h)&&(N=j)}),A.operator===v||A.operator===w||(!N.operator||N.operator===v)&&m(l,N.semver))return!1;if(N.operator===w&&y(l,N.semver))return!1}return!0},tc}var rc,$h;function bv(){if($h)return rc;$h=1;const t=nc();return rc=(n,r,s)=>t(n,r,">",s),rc}var sc,Ch;function vv(){if(Ch)return sc;Ch=1;const t=nc();return sc=(n,r,s)=>t(n,r,"<",s),sc}var ac,Rh;function Ev(){if(Rh)return ac;Rh=1;const t=Lt();return ac=(n,r,s)=>(n=new t(n,s),r=new t(r,s),n.intersects(r,s)),ac}var ic,Nh;function Sv(){if(Nh)return ic;Nh=1;const t=ra(),e=Mt();return ic=(n,r,s)=>{const a=[];let i=null,o=null;const c=n.sort((f,h)=>e(f,h,s));for(const f of c)t(f,r,s)?(o=f,i||(i=f)):(o&&a.push([i,o]),o=null,i=null);i&&a.push([i,null]);const u=[];for(const[f,h]of a)f===h?u.push(f):!h&&f===c[0]?u.push("*"):h?f===c[0]?u.push(`<=${h}`):u.push(`${f} - ${h}`):u.push(`>=${f}`);const l=u.join(" || "),d=typeof r.raw=="string"?r.raw:String(r);return l.length<d.length?l:r},ic}var oc,Ph;function Tv(){if(Ph)return oc;Ph=1;const t=Lt(),e=na(),{ANY:n}=e,r=ra(),s=Mt(),a=(d,f,h={})=>{if(d===f)return!0;d=new t(d,h),f=new t(f,h);let p=!1;e:for(const m of d.set){for(const y of f.set){const v=c(m,y,h);if(p=p||v!==null,v)continue e}if(p)return!1}return!0},i=[new e(">=0.0.0-0")],o=[new e(">=0.0.0")],c=(d,f,h)=>{if(d===f)return!0;if(d.length===1&&d[0].semver===n){if(f.length===1&&f[0].semver===n)return!0;h.includePrerelease?d=i:d=o}if(f.length===1&&f[0].semver===n){if(h.includePrerelease)return!0;f=o}const p=new Set;let m,y;for(const b of d)b.operator===">"||b.operator===">="?m=u(m,b,h):b.operator==="<"||b.operator==="<="?y=l(y,b,h):p.add(b.semver);if(p.size>1)return null;let v;if(m&&y){if(v=s(m.semver,y.semver,h),v>0)return null;if(v===0&&(m.operator!==">="||y.operator!=="<="))return null}for(const b of p){if(m&&!r(b,String(m),h)||y&&!r(b,String(y),h))return null;for(const oe of f)if(!r(b,String(oe),h))return!1;return!0}let w,E,x,A,N=y&&!h.includePrerelease&&y.semver.prerelease.length?y.semver:!1,j=m&&!h.includePrerelease&&m.semver.prerelease.length?m.semver:!1;N&&N.prerelease.length===1&&y.operator==="<"&&N.prerelease[0]===0&&(N=!1);for(const b of f){if(A=A||b.operator===">"||b.operator===">=",x=x||b.operator==="<"||b.operator==="<=",m){if(j&&b.semver.prerelease&&b.semver.prerelease.length&&b.semver.major===j.major&&b.semver.minor===j.minor&&b.semver.patch===j.patch&&(j=!1),b.operator===">"||b.operator===">="){if(w=u(m,b,h),w===b&&w!==m)return!1}else if(m.operator===">="&&!r(m.semver,String(b),h))return!1}if(y){if(N&&b.semver.prerelease&&b.semver.prerelease.length&&b.semver.major===N.major&&b.semver.minor===N.minor&&b.semver.patch===N.patch&&(N=!1),b.operator==="<"||b.operator==="<="){if(E=l(y,b,h),E===b&&E!==y)return!1}else if(y.operator==="<="&&!r(y.semver,String(b),h))return!1}if(!b.operator&&(y||m)&&v!==0)return!1}return!(m&&x&&!y&&v!==0||y&&A&&!m&&v!==0||j||N)},u=(d,f,h)=>{if(!d)return f;const p=s(d.semver,f.semver,h);return p>0?d:p<0||f.operator===">"&&d.operator===">="?f:d},l=(d,f,h)=>{if(!d)return f;const p=s(d.semver,f.semver,h);return p<0?d:p>0||f.operator==="<"&&d.operator==="<="?f:d};return oc=a,oc}var cc,Mh;function xv(){if(Mh)return cc;Mh=1;const t=Br(),e=Qs(),n=ct(),r=Hd(),s=rr(),a=tv(),i=nv(),o=rv(),c=sv(),u=av(),l=iv(),d=ov(),f=cv(),h=Mt(),p=uv(),m=lv(),y=Ro(),v=dv(),w=hv(),E=ta(),x=jo(),A=hh(),N=ph(),j=Uo(),b=Zo(),oe=yh(),ue=fv(),X=na(),Be=Lt(),kt=ra(),L=mv(),R=gv(),P=_v(),H=yv(),Y=wv(),q=nc(),ne=bv(),me=vv(),fe=Ev(),Se=Sv(),ze=Tv();return cc={parse:s,valid:a,clean:i,inc:o,diff:c,major:u,minor:l,patch:d,prerelease:f,compare:h,rcompare:p,compareLoose:m,compareBuild:y,sort:v,rsort:w,gt:E,lt:x,eq:A,neq:N,gte:j,lte:b,cmp:oe,coerce:ue,Comparator:X,Range:Be,satisfies:kt,toComparators:L,maxSatisfying:R,minSatisfying:P,minVersion:H,validRange:Y,outside:q,gtr:ne,ltr:me,intersects:fe,simplifyRange:Se,subset:ze,SemVer:n,re:t.re,src:t.src,tokens:t.t,SEMVER_SPEC_VERSION:e.SEMVER_SPEC_VERSION,RELEASE_TYPES:e.RELEASE_TYPES,compareIdentifiers:r.compareIdentifiers,rcompareIdentifiers:r.rcompareIdentifiers},cc}xv();function Sn(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(`Invalid identifier format: ${t}`);const[e,n]=t.split(":"),r=n||"latest";if(e.includes("/")){const[s,a]=e.split("/",2);if(!s||!a)throw new Error(`Invalid identifier format: ${t}`);return[s,a,r]}else{if(!e)throw new Error(`Invalid identifier format: ${t}`);return["-",e,r]}}class Iv extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}class Av extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}}function Lh(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithNotFoundError"}async function W(t,e,n){let r;if(t.ok){n&&(r=await t.text());return}if(t.status===403)try{(await t.json())?.error==="org_scoped_key_requires_workspace"&&(r="This API key is org-scoped and requires workspace specification. Please provide \'workspaceId\' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{const o=new Error(`${t.status} ${t.statusText}`);throw o.status=t?.status,o}if(r===void 0)try{r=await t.text()}catch{r=""}const s=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${r}`;if(t.status===404)throw new Av(s);if(t.status===409)throw new Iv(s);const a=new Error(s);throw a.status=t.status,a}const jh="ERR_CONFLICTING_ENDPOINTS";class kv extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:jh}),this.name="ConflictingEndpointsError"}}function Ov(t){return typeof t=="object"&&t!==null&&t.code===jh}var Dh="[...]",$v={result:"[Circular]"},sa=[],sr=[];const Cv=new TextEncoder;function Rv(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function aa(t){return Cv.encode(t)}function zh(t){if(t&&typeof t=="object"&&t!==null){if(t instanceof Map)return Object.fromEntries(t);if(t instanceof Set)return Array.from(t);if(t instanceof Date)return t.toISOString();if(t instanceof RegExp)return t.toString();if(t instanceof Error)return{name:t.name,message:t.message}}else if(typeof t=="bigint")return t.toString();return t}function Nv(t){return function(e,n){return zh(n)}}function yt(t,e,n,r,s){try{const a=JSON.stringify(t,Nv(n),r);return aa(a)}catch(a){if(!a.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`\nContext: ${e}`:""}`),aa("[Unserializable]");ot("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`\nContext: ${e}`:""}`),typeof s>"u"&&(s=Rv()),lc(t,"",0,[],void 0,0,s);let i;try{sr.length===0?i=JSON.stringify(t,n,r):i=JSON.stringify(t,Pv(n),r)}catch{return aa("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;sa.length!==0;){const o=sa.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return aa(i)}}function uc(t,e,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:t}),sa.push([r,n,e,s])):sr.push([e,n,t]):(r[n]=t,sa.push([r,n,e]))}function lc(t,e,n,r,s,a,i){a+=1;var o;if(typeof t=="object"&&t!==null){for(o=0;o<r.length;o++)if(r[o]===t){uc($v,t,e,s);return}if(typeof i.depthLimit<"u"&&a>i.depthLimit){uc(Dh,t,e,s);return}if(typeof i.edgesLimit<"u"&&n+1>i.edgesLimit){uc(Dh,t,e,s);return}if(r.push(t),Array.isArray(t))for(o=0;o<t.length;o++)lc(t[o],o,o,r,t,a,i);else{t=zh(t);var c=Object.keys(t);for(o=0;o<c.length;o++){var u=c[o];lc(t[u],u,o,r,t,a,i)}}r.pop()}}function Pv(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(sr.length>0)for(var r=0;r<sr.length;r++){var s=sr[r];if(s[1]===e&&s[0]===n){n=s[2],sr.splice(r,1);break}}return t.call(this,e,n)}}function Fh(t,e,n){if(n)return t;const r=Id(),s=e??Ad(),a=t.extra??{},i=a.metadata;return t.extra={...a,runtime:{...r,...a?.runtime},metadata:{...s,...s.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??s.revision_id}:{},...i}},t}const Mv=t=>{const e=t?.toString()??ot("TRACING_SAMPLING_RATE");if(e===void 0)return;const n=parseFloat(e);if(n<0||n>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${n}`);return n},Lv=t=>{const n=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return n==="localhost"||n==="127.0.0.1"||n==="::1"};async function jv(t){const e=[];for await(const n of t)e.push(n);return e}function ia(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^\'(.*)\'$/,"$1")}const Dv=async t=>{if(t?.status===429){const e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(n=>setTimeout(n,e)),!0}return!1};function Uh(t){return typeof t=="number"?Number(t.toFixed(4)):t}const zv=24*1024*1024,Bh=1024*1024*1024,Fv=1e4,Uv=100,Zh="https://api.smith.langchain.com";class Bv{constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??Bh}peek(){return this.items[0]}push(e){let n;const r=new Promise(a=>{n=a}),s=yt(e.item,`Serializing run with id: ${e.item.id}`).length;return this.sizeBytes+s>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${s} bytes.`),n(),r):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:n,itemPromise:r,size:s}),this.sizeBytes+=s,r)}pop({upToSizeBytes:e,upToSize:n}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const r=[];let s=0;for(;s+(this.peek()?.size??0)<e&&this.items.length>0&&r.length<n;){const a=this.items.shift();a&&(r.push(a),s+=a.size,this.sizeBytes-=a.size)}if(r.length===0&&this.items.length>0){const a=this.items.shift();r.push(a),s+=a.size,this.sizeBytes-=a.size}return[r.map(a=>({action:a.action,item:a.payload,otelContext:a.otelContext,apiKey:a.apiKey,apiUrl:a.apiUrl,size:a.size})),()=>r.forEach(a=>a.itemPromiseResolve())]}}class Zr{get _fetch(){return this.fetchImplementation||pb(this.debug)}constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitTracedRuntimeInfo",{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:void 0}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:Xt("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:ot("DISABLE_RUN_COMPRESSION")==="true"}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:Xt("LANGSMITH_DEBUG")==="true"});const n=Zr.getDefaultClientConfig();if(this.tracingSampleRate=Mv(e.tracingSamplingRate),this.apiUrl=ia(e.apiUrl??n.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=ia(e.apiKey??n.apiKey),this.webUrl=ia(e.webUrl??n.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=ia(e.workspaceId??ot("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new Dd({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation;const r=e.maxIngestMemoryBytes??Bh;this.batchIngestCaller=new Dd({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:r,...e.callerOptions??{},onFailedResponseHook:Dv,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??n.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??n.hideOutputs,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new Bv(r),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,kd()&&(this.langSmithToOTELTranslator=new jb),this.cachedLSEnvVarsForMetadata=Ad(),e.cache===!0?this._cache=new bb:e.cache&&typeof e.cache=="object"?this._cache=e.cache:this._cache=void 0}static getDefaultClientConfig(){const e=ot("API_KEY"),n=ot("ENDPOINT")??Zh,r=ot("HIDE_INPUTS")==="true",s=ot("HIDE_OUTPUTS")==="true";return{apiUrl:n,apiKey:e,webUrl:void 0,hideInputs:r,hideOutputs:s}}getHostUrl(){return this.webUrl?this.webUrl:Lv(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){const e={"User-Agent":`langsmith-js/${Sd}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){const n={...e};return n.inputs!==void 0&&(n.inputs=await this.processInputs(n.inputs)),n.outputs!==void 0&&(n.outputs=await this.processOutputs(n.outputs)),n}async _getResponse(e,n){const r=n?.toString()??"",s=`${this.apiUrl}${e}?${r}`;return await this.caller.call(async()=>{const i=await this._fetch(s,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(i,`fetch ${e}`),i})}async _get(e,n){return(await this._getResponse(e,n)).json()}async*_getPaginated(e,n=new URLSearchParams,r){let s=Number(n.get("offset"))||0;const a=Number(n.get("limit"))||100;for(;;){n.set("offset",String(s)),n.set("limit",String(a));const i=`${this.apiUrl}${e}?${n}`,o=await this.caller.call(async()=>{const u=await this._fetch(i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(u,`fetch ${e}`),u}),c=r?r(await o.json()):await o.json();if(c.length===0||(yield c,c.length<a))break;s+=c.length}}async*_getCursorPaginatedList(e,n=null,r="POST",s="runs"){const a=n?{...n}:{};for(;;){const i=JSON.stringify(a),c=await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}${e}`,{method:r,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await W(l,`fetch ${e}`),l})).json();if(!c||!c[s])break;yield c[s];const u=c.cursors;if(!u||!u.next)break;a.cursor=u.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,n=!1){if(this.tracingSampleRate===void 0)return e;if(n){const r=[];for(const s of e)this.filteredPostUuids.has(s.trace_id)?s.id===s.trace_id&&this.filteredPostUuids.delete(s.trace_id):r.push(s);return r}else{const r=[];for(const s of e){const a=s.trace_id??s.id;this.filteredPostUuids.has(a)||(s.id===a?this._shouldSample()?r.push(s):this.filteredPostUuids.add(a):r.push(s))}return r}}async _getBatchSizeLimitBytes(){const e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??zv}async _getBatchSizeLimit(){const e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??Uv}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:n}){const r=[];for(;this.autoBatchQueue.items.length>0;){const[s,a]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:n});if(!s.length){a();break}const i=s.reduce((u,l)=>{const d=l.apiUrl??this.apiUrl,f=l.apiKey??this.apiKey,p=l.apiKey===this.apiKey&&l.apiUrl===this.apiUrl?"default":`${d}|${f}`;return u[p]||(u[p]=[]),u[p].push(l),u},{}),o=[];for(const[u,l]of Object.entries(i)){const d=this._processBatch(l,{apiUrl:u==="default"?void 0:u.split("|")[0],apiKey:u==="default"?void 0:u.split("|")[1]});o.push(d)}const c=Promise.all(o).finally(a);r.push(c)}return Promise.all(r)}async _processBatch(e,n){if(!e.length)return;const r=e.reduce((s,a)=>s+(a.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{const s={runCreates:e.filter(o=>o.action==="create").map(o=>o.item),runUpdates:e.filter(o=>o.action==="update").map(o=>o.item)},a=await this._ensureServerInfo();if(!this._multipartDisabled&&(a?.batch_ingest_config?.use_multipart_endpoint??!0)){const o=!this._runCompressionDisabled&&a?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(s,{...n,useGzip:o,sizeBytes:r})}catch(c){if(Lh(c))this._multipartDisabled=!0,await this.batchIngestRuns(s,{...n,sizeBytes:r});else throw c}}else await this.batchIngestRuns(s,{...n,sizeBytes:r})}}catch(s){console.error("Error exporting batch:",s)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){const n=new Map,r=[];for(const s of e)s.item.id&&s.otelContext&&(n.set(s.item.id,s.otelContext),s.action==="create"?r.push({operation:"post",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}):r.push({operation:"patch",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}));this.langSmithToOTELTranslator.exportBatch(r,n)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=Fh(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);const n=this.autoBatchQueue.push(e);if(this.manualFlushMode)return n;const r=await this._getBatchSizeLimitBytes(),s=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>r||this.autoBatchQueue.items.length>s)&&this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:s}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:s})},this.autoBatchAggregationDelayMs)),n}async _getServerInfo(){const n=await(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(Fv),...this.fetchOptions});return await W(r,"get server info"),r})).json();return this.debug&&console.log(`\n=== LangSmith Server Configuration ===\n`+JSON.stringify(n,null,2)+`\n`),n}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){const e=await this._getBatchSizeLimitBytes(),n=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:n})}_cloneCurrentOTELContext(){const e=$d(),n=Nb();if(this.langSmithToOTELTranslator!==void 0){const r=e.getActiveSpan();if(r)return e.setSpan(n.active(),r)}}async createRun(e,n){if(!this._filterForSampling([e]).length)return;const r={...this.headers,"Content-Type":"application/json"},s=e.project_name;delete e.project_name;const a=await this.prepareRunCreateOrUpdateInputs({session_name:s,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&a.trace_id!==void 0&&a.dotted_order!==void 0){const c=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:a,otelContext:c,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}const i=Fh(a,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);n?.apiKey!==void 0&&(r["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(r["x-tenant-id"]=n.workspaceId);const o=yt(i,`Creating run with id: ${i.id}`);await this.caller.call(async()=>{const c=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await W(c,"create run",!0),c})}async batchIngestRuns({runCreates:e,runUpdates:n},r){if(e===void 0&&n===void 0)return;let s=await Promise.all(e?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]),a=await Promise.all(n?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]);if(s.length>0&&a.length>0){const c=s.reduce((l,d)=>(d.id&&(l[d.id]=d),l),{}),u=[];for(const l of a)l.id!==void 0&&c[l.id]?c[l.id]={...c[l.id],...l}:u.push(l);s=Object.values(c),a=u}const i={post:s,patch:a};if(!i.post.length&&!i.patch.length)return;const o={post:[],patch:[]};for(const c of["post","patch"]){const u=c,l=i[u].reverse();let d=l.pop();for(;d!==void 0;)o[u].push(d),d=l.pop()}if(o.post.length>0||o.patch.length>0){const c=o.post.map(u=>u.id).concat(o.patch.map(u=>u.id)).join(",");await this._postBatchIngestRuns(yt(o,`Ingesting runs with ids: ${c}`),r)}}async _postBatchIngestRuns(e,n){const r={...this.headers,"Content-Type":"application/json",Accept:"application/json"};n?.apiKey!==void 0&&(r["x-api-key"]=n.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{const s=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await W(s,"batch create run",!0),s})}async multipartIngestRuns({runCreates:e,runUpdates:n},r){if(e===void 0&&n===void 0)return;const s={};let a=[];for(const d of e??[]){const f=await this.prepareRunCreateOrUpdateInputs(d);f.id!==void 0&&f.attachments!==void 0&&(s[f.id]=f.attachments),delete f.attachments,a.push(f)}let i=[];for(const d of n??[])i.push(await this.prepareRunCreateOrUpdateInputs(d));if(a.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error(\'Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run\');if(i.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error(\'Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run\');if(a.length>0&&i.length>0){const d=a.reduce((h,p)=>(p.id&&(h[p.id]=p),h),{}),f=[];for(const h of i)h.id!==void 0&&d[h.id]?d[h.id]={...d[h.id],...h}:f.push(h);a=Object.values(d),i=f}if(a.length===0&&i.length===0)return;const u=[],l=[];for(const[d,f]of[["post",a],["patch",i]])for(const h of f){const{inputs:p,outputs:m,events:y,extra:v,error:w,serialized:E,attachments:x,...A}=h,N={inputs:p,outputs:m,events:y,extra:v,error:w,serialized:E},j=yt(A,`Serializing for multipart ingestion of run with id: ${A.id}`);l.push({name:`${d}.${A.id}`,payload:new Blob([j],{type:`application/json; length=${j.length}`})});for(const[b,oe]of Object.entries(N)){if(oe===void 0)continue;const ue=yt(oe,`Serializing ${b} for multipart ingestion of run with id: ${A.id}`);l.push({name:`${d}.${A.id}.${b}`,payload:new Blob([ue],{type:`application/json; length=${ue.length}`})})}if(A.id!==void 0){const b=s[A.id];if(b){delete s[A.id];for(const[oe,ue]of Object.entries(b)){let X,Be;if(Array.isArray(ue)?[X,Be]=ue:(X=ue.mimeType,Be=ue.data),oe.includes(".")){console.warn(`Skipping attachment \'${oe}\' for run ${A.id}: Invalid attachment name. Attachment names must not contain periods (\'.\'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${A.id}.${oe}`,payload:new Blob([Be],{type:`${X}; length=${Be.byteLength}`})})}}}u.push(`trace=${A.trace_id},id=${A.id}`)}await this._sendMultipartRequest(l,u.join("; "),r)}async _createNodeFetchBody(e,n){const r=[];for(const i of e)r.push(new Blob([`--${n}\\r\n`])),r.push(new Blob([`Content-Disposition: form-data; name="${i.name}"\\r\n`,`Content-Type: ${i.payload.type}\\r\n\\r\n`])),r.push(i.payload),r.push(new Blob([`\\r\n`]));return r.push(new Blob([`--${n}--\\r\n`])),await new Blob(r).arrayBuffer()}async _createMultipartStream(e,n){const r=new TextEncoder;return new ReadableStream({async start(a){const i=async o=>{typeof o=="string"?a.enqueue(r.encode(o)):a.enqueue(o)};for(const o of e){await i(`--${n}\\r\n`),await i(`Content-Disposition: form-data; name="${o.name}"\\r\n`),await i(`Content-Type: ${o.payload.type}\\r\n\\r\n`);const u=o.payload.stream().getReader();try{let l;for(;!(l=await u.read()).done;)a.enqueue(l.value)}finally{u.releaseLock()}await i(`\\r\n`)}await i(`--${n}--\\r\n`),a.close()}})}async _sendMultipartRequest(e,n,r){const s="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),a=fb(),i=()=>this._createNodeFetchBody(e,s),o=()=>this._createMultipartStream(e,s),c=async u=>this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{const l=await u(),d={...this.headers,"Content-Type":`multipart/form-data; boundary=${s}`};r?.apiKey!==void 0&&(d["x-api-key"]=r.apiKey);let f=l;r?.useGzip&&typeof l=="object"&&"pipeThrough"in l&&(f=l.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");const h=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:f,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(h,"Failed to send multipart request",!0),h});try{let u,l=!1;!a&&!this.multipartStreamingDisabled&&xd()!=="bun"?(l=!0,u=await c(o)):u=await c(i),(!this.multipartStreamingDisabled||l)&&u.status===422&&(r?.apiUrl??this.apiUrl)!==Zh&&(console.warn(`Streaming multipart upload to ${r?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${n}".`),this.multipartStreamingDisabled=!0,u=await c(i))}catch(u){if(Lh(u))throw u;console.warn(`${u.message.trim()}\n\nContext: ${n}`)}}async updateRun(e,n,r){de(e),n.inputs&&(n.inputs=await this.processInputs(n.inputs)),n.outputs&&(n.outputs=await this.processOutputs(n.outputs));const s={...n,id:e};if(!this._filterForSampling([s],!0).length)return;if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){const o=this._cloneCurrentOTELContext();if(n.end_time!==void 0&&s.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:s,otelContext:o,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:s,otelContext:o,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}const a={...this.headers,"Content-Type":"application/json"};r?.apiKey!==void 0&&(a["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(a["x-tenant-id"]=r.workspaceId);const i=yt(n,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{const o=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await W(o,"update run",!0),o})}async readRun(e,{loadChildRuns:n}={loadChildRuns:!1}){de(e);let r=await this._get(`/runs/${e}`);return n&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:n,projectOpts:r}){if(n!==void 0){let s;n.session_id?s=n.session_id:r?.projectName?s=(await this.readProject({projectName:r?.projectName})).id:r?.projectId?s=r?.projectId:s=(await this.readProject({projectName:ot("PROJECT")||"default"})).id;const a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${s}/r/${n.id}?poll=true`}else if(e!==void 0){const s=await this.readRun(e);if(!s.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${s.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){const n=await jv(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),r={},s={};n.sort((a,i)=>(a?.dotted_order??"").localeCompare(i?.dotted_order??""));for(const a of n){if(a.parent_run_id===null||a.parent_run_id===void 0)throw new Error(`Child run ${a.id} has no parent`);a.dotted_order?.startsWith(e.dotted_order??"")&&a.id!==e.id&&(a.parent_run_id in r||(r[a.parent_run_id]=[]),r[a.parent_run_id].push(a),s[a.id]=a)}e.child_runs=r[e.id]||[];for(const a in r)a!==e.id&&(s[a].child_runs=r[a]);return e}async*listRuns(e){const{projectId:n,projectName:r,parentRunId:s,traceId:a,referenceExampleId:i,startTime:o,executionOrder:c,isRoot:u,runType:l,error:d,id:f,query:h,filter:p,traceFilter:m,treeFilter:y,limit:v,select:w,order:E}=e;let x=[];if(n&&(x=Array.isArray(n)?n:[n]),r){const b=Array.isArray(r)?r:[r],oe=await Promise.all(b.map(ue=>this.readProject({projectName:ue}).then(X=>X.id)));x.push(...oe)}const A=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],N={session:x.length?x:null,run_type:l,reference_example:i,query:h,filter:p,trace_filter:m,tree_filter:y,execution_order:c,parent_run:s,start_time:o?o.toISOString():null,error:d,id:f,limit:v,trace:a,select:w||A,is_root:u,order:E};N.select.includes("child_run_ids")&&Ed("Deprecated: \'child_run_ids\' in the listRuns select parameter is deprecated and will be removed in a future version.");let j=0;for await(const b of this._getCursorPaginatedList("/runs/query",N))if(v){if(j>=v)break;if(b.length+j>v){yield*b.slice(0,v-j);break}j+=b.length,yield*b}else yield*b}async*listGroupRuns(e){const{projectId:n,projectName:r,groupBy:s,filter:a,startTime:i,endTime:o,limit:c,offset:u}=e,d={session_id:n||(await this.readProject({projectName:r})).id,group_by:s,filter:a,start_time:i?i.toISOString():null,end_time:o?o.toISOString():null,limit:Number(c)||100};let f=Number(u)||0;const h="/runs/group",p=`${this.apiUrl}${h}`;for(;;){const m={...d,offset:f},y=Object.fromEntries(Object.entries(m).filter(([N,j])=>j!==void 0)),v=JSON.stringify(y),E=await(await this.caller.call(async()=>{const N=await this._fetch(p,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:v});return await W(N,`Failed to fetch ${h}`),N})).json(),{groups:x,total:A}=E;if(x.length===0)break;for(const N of x)yield N;if(f+=x.length,f>=A)break}}async getRunStats({id:e,trace:n,parentRun:r,runType:s,projectNames:a,projectIds:i,referenceExampleIds:o,startTime:c,endTime:u,error:l,query:d,filter:f,traceFilter:h,treeFilter:p,isRoot:m,dataSourceType:y}){let v=i||[];a&&(v=[...i||[],...await Promise.all(a.map(j=>this.readProject({projectName:j}).then(b=>b.id)))]);const E=Object.fromEntries(Object.entries({id:e,trace:n,parent_run:r,run_type:s,session:v,reference_example:o,start_time:c,end_time:u,error:l,query:d,filter:f,trace_filter:h,tree_filter:p,is_root:m,data_source_type:y}).filter(([j,b])=>b!==void 0)),x=JSON.stringify(E);return await(await this.caller.call(async()=>{const j=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:x});return await W(j,"get run stats"),j})).json()}async shareRun(e,{shareId:n}={}){const r={run_id:e,share_token:n||Fn()};de(e);const s=JSON.stringify(r),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await W(o,"share run"),o})).json();if(i===null||!("share_token"in i))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(e){de(e),await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(n,"unshare run",!0),n})}async readRunSharedLink(e){de(e);const r=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(s,"read run shared link"),s})).json();if(!(r===null||!("share_token"in r)))return`${this.getHostUrl()}/public/${r.share_token}/r`}async listSharedRuns(e,{runIds:n}={}){const r=new URLSearchParams({share_token:e});if(n!==void 0)for(const i of n)r.append("id",i);return de(e),await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(i,"list shared runs"),i})).json()}async readDatasetSharedSchema(e,n){if(!e&&!n)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:n})).id),de(e);const s=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(a,"read dataset shared schema"),a})).json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async shareDataset(e,n){if(!e&&!n)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:n})).id);const r={dataset_id:e};de(e);const s=JSON.stringify(r),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await W(o,"share dataset"),o})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){de(e),await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(n,"unshare dataset",!0),n})}async readSharedDataset(e){return de(e),await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(s,"read shared dataset"),s})).json()}async listSharedExamples(e,n){const r={};n?.exampleIds&&(r.id=n.exampleIds);const s=new URLSearchParams;Object.entries(r).forEach(([o,c])=>{Array.isArray(c)?c.forEach(u=>s.append(o,u)):s.append(o,c)});const a=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/public/${e}/examples?${s.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(o,"list shared examples"),o}),i=await a.json();if(!a.ok)throw"detail"in i?new Error(`Failed to list shared examples.\nStatus: ${a.status}\nMessage: ${Array.isArray(i.detail)?i.detail.join(`\n`):"Unspecified error"}`):new Error(`Failed to list shared examples: ${a.status} ${a.statusText}`);return i.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:n=null,metadata:r=null,upsert:s=!1,projectExtra:a=null,referenceDatasetId:i=null}){const o=s?"?upsert=true":"",c=`${this.apiUrl}/sessions${o}`,u=a||{};r&&(u.metadata=r);const l={name:e,extra:u,description:n};i!==null&&(l.reference_dataset_id=i);const d=JSON.stringify(l);return await(await this.caller.call(async()=>{const p=await this._fetch(c,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});return await W(p,"create project"),p})).json()}async updateProject(e,{name:n=null,description:r=null,metadata:s=null,projectExtra:a=null,endTime:i=null}){const o=`${this.apiUrl}/sessions/${e}`;let c=a;s&&(c={...c||{},metadata:s});const u=JSON.stringify({name:n,extra:c,description:r,end_time:i?new Date(i).toISOString():null});return await(await this.caller.call(async()=>{const f=await this._fetch(o,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await W(f,"update project"),f})).json()}async hasProject({projectId:e,projectName:n}){let r="/sessions";const s=new URLSearchParams;if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)de(e),r+=`/${e}`;else if(n!==void 0)s.append("name",n);else throw new Error("Must provide projectName or projectId");const a=await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${r}?${s}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(i,"has project"),i});try{const i=await a.json();return a.ok?Array.isArray(i)?i.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:n,includeStats:r}){let s="/sessions";const a=new URLSearchParams;if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)de(e),s+=`/${e}`;else if(n!==void 0)a.append("name",n);else throw new Error("Must provide projectName or projectId");r!==void 0&&a.append("include_stats",r.toString());const i=await this._get(s,a);let o;if(Array.isArray(i)){if(i.length===0)throw new Error(`Project[id=${e}, name=${n}] not found`);o=i[0]}else o=i;return o}async getProjectUrl({projectId:e,projectName:n}){if(e===void 0&&n===void 0)throw new Error("Must provide either projectName or projectId");const r=await this.readProject({projectId:e,projectName:n}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:n}){if(e===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");const r=await this.readDataset({datasetId:e,datasetName:n}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/datasets/${r.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;const e=new URLSearchParams({limit:"1"});for await(const n of this._getPaginated("/sessions",e))return this._tenantId=n[0].tenant_id,n[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:n,nameContains:r,referenceDatasetId:s,referenceDatasetName:a,includeStats:i,datasetVersion:o,referenceFree:c,metadata:u}={}){const l=new URLSearchParams;if(e!==void 0)for(const d of e)l.append("id",d);if(n!==void 0&&l.append("name",n),r!==void 0&&l.append("name_contains",r),s!==void 0)l.append("reference_dataset",s);else if(a!==void 0){const d=await this.readDataset({datasetName:a});l.append("reference_dataset",d.id)}i!==void 0&&l.append("include_stats",i.toString()),o!==void 0&&l.append("dataset_version",o),c!==void 0&&l.append("reference_free",c.toString()),u!==void 0&&l.append("metadata",JSON.stringify(u));for await(const d of this._getPaginated("/sessions",l))yield*d}async deleteProject({projectId:e,projectName:n}){let r;if(e===void 0&&n===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?r=(await this.readProject({projectName:n})).id:r=e,de(r),await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(s,`delete session ${r} (${n})`,!0),s})}async uploadCsv({csvFile:e,fileName:n,inputKeys:r,outputKeys:s,description:a,dataType:i,name:o}){const c=`${this.apiUrl}/datasets/upload`,u=new FormData,l=new Blob([e],{type:"text/csv"});return u.append("file",l,n),r.forEach(h=>{u.append("input_keys",h)}),s.forEach(h=>{u.append("output_keys",h)}),a&&u.append("description",a),i&&u.append("data_type",i),o&&u.append("name",o),await(await this.caller.call(async()=>{const h=await this._fetch(c,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await W(h,"upload CSV"),h})).json()}async createDataset(e,{description:n,dataType:r,inputsSchema:s,outputsSchema:a,metadata:i}={}){const o={name:e,description:n,extra:i?{metadata:i}:void 0};r&&(o.data_type=r),s&&(o.inputs_schema_definition=s),a&&(o.outputs_schema_definition=a);const c=JSON.stringify(o);return await(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await W(d,"create dataset"),d})).json()}async readDataset({datasetId:e,datasetName:n}){let r="/datasets";const s=new URLSearchParams({limit:"1"});if(e&&n)throw new Error("Must provide either datasetName or datasetId, not both");if(e)de(e),r+=`/${e}`;else if(n)s.append("name",n);else throw new Error("Must provide datasetName or datasetId");const a=await this._get(r,s);let i;if(Array.isArray(a)){if(a.length===0)throw new Error(`Dataset[id=${e}, name=${n}] not found`);i=a[0]}else i=a;return i}async hasDataset({datasetId:e,datasetName:n}){try{return await this.readDataset({datasetId:e,datasetName:n}),!0}catch(r){if(r instanceof Error&&r.message.toLocaleLowerCase().includes("not found"))return!1;throw r}}async diffDatasetVersions({datasetId:e,datasetName:n,fromVersion:r,toVersion:s}){let a=e;if(a===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");if(a!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");a===void 0&&(a=(await this.readDataset({datasetName:n})).id);const i=new URLSearchParams({from_version:typeof r=="string"?r:r.toISOString(),to_version:typeof s=="string"?s:s.toISOString()});return await this._get(`/datasets/${a}/versions/diff`,i)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:n}){const r="/datasets";if(e===void 0)if(n!==void 0)e=(await this.readDataset({datasetName:n})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${r}/${e}/openai_ft`)).text()).trim().split(`\n`).map(o=>JSON.parse(o))}async*listDatasets({limit:e=100,offset:n=0,datasetIds:r,datasetName:s,datasetNameContains:a,metadata:i}={}){const o="/datasets",c=new URLSearchParams({limit:e.toString(),offset:n.toString()});if(r!==void 0)for(const u of r)c.append("id",u);s!==void 0&&c.append("name",s),a!==void 0&&c.append("name_contains",a),i!==void 0&&c.append("metadata",JSON.stringify(i));for await(const u of this._getPaginated(o,c))yield*u}async updateDataset(e){const{datasetId:n,datasetName:r,...s}=e;if(!n&&!r)throw new Error("Must provide either datasetName or datasetId");const a=n??(await this.readDataset({datasetName:r})).id;de(a);const i=JSON.stringify(s);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${a}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await W(c,"update dataset"),c})).json()}async updateDatasetTag(e){const{datasetId:n,datasetName:r,asOf:s,tag:a}=e;if(!n&&!r)throw new Error("Must provide either datasetName or datasetId");const i=n??(await this.readDataset({datasetName:r})).id;de(i);const o=JSON.stringify({as_of:typeof s=="string"?s:s.toISOString(),tag:a});await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${i}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await W(c,"update dataset tags",!0),c})}async deleteDataset({datasetId:e,datasetName:n}){let r="/datasets",s=e;if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(n!==void 0&&(s=(await this.readDataset({datasetName:n})).id),s!==void 0)de(s),r+=`/${s}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{const a=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(a,`delete ${r}`,!0),a})}async indexDataset({datasetId:e,datasetName:n,tag:r}){let s=e;if(!s&&!n)throw new Error("Must provide either datasetName or datasetId");if(s&&n)throw new Error("Must provide either datasetName or datasetId, not both");s||(s=(await this.readDataset({datasetName:n})).id),de(s);const i=JSON.stringify({tag:r});await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${s}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await W(c,"index dataset"),c})).json()}async similarExamples(e,n,r,{filter:s}={}){const a={limit:r,inputs:e};s!==void 0&&(a.filter=s),de(n);const i=JSON.stringify(a);return(await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${n}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:i});return await W(u,"fetch similar examples"),u})).json()).examples}async createExample(e,n,r){if(qh(e)&&(n!==void 0||r!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let s=n?r?.datasetId:e.dataset_id;const a=n?r?.datasetName:e.dataset_name;if(s===void 0&&a===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&a!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:a})).id);const i=(n?r?.createdAt:e.created_at)||new Date;let o;qh(e)?o=e:o={inputs:e,outputs:n,created_at:i?.toISOString(),id:r?.exampleId,metadata:r?.metadata,split:r?.split,source_run_id:r?.sourceRunId,use_source_run_io:r?.useSourceRunIO,use_source_run_attachments:r?.useSourceRunAttachments,attachments:r?.attachments};const c=await this._uploadExamplesMultipart(s,[o]);return await this.readExample(c.example_ids?.[0]??Fn())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];const w=e;let E=w[0].dataset_id;const x=w[0].dataset_name;if(E===void 0&&x===void 0)throw new Error("Must provide either datasetName or datasetId");if(E!==void 0&&x!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");E===void 0&&(E=(await this.readDataset({datasetName:x})).id);const A=await this._uploadExamplesMultipart(E,w);return await Promise.all(A.example_ids.map(j=>this.readExample(j)))}const{inputs:n,outputs:r,metadata:s,splits:a,sourceRunIds:i,useSourceRunIOs:o,useSourceRunAttachments:c,attachments:u,exampleIds:l,datasetId:d,datasetName:f}=e;if(n===void 0)throw new Error("Must provide inputs when using legacy parameters");let h=d;const p=f;if(h===void 0&&p===void 0)throw new Error("Must provide either datasetName or datasetId");if(h!==void 0&&p!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");h===void 0&&(h=(await this.readDataset({datasetName:p})).id);const m=n.map((w,E)=>({dataset_id:h,inputs:w,outputs:r?.[E],metadata:s?.[E],split:a?.[E],id:l?.[E],attachments:u?.[E],source_run_id:i?.[E],use_source_run_io:o?.[E],use_source_run_attachments:c?.[E]})),y=await this._uploadExamplesMultipart(h,m);return await Promise.all(y.example_ids.map(w=>this.readExample(w)))}async createLLMExample(e,n,r){return this.createExample({input:e},{output:n},r)}async createChatExample(e,n,r){const s=e.map(i=>zd(i)?Fd(i):i),a=zd(n)?Fd(n):n;return this.createExample({input:s},{output:a},r)}async readExample(e){de(e);const n=`/examples/${e}`,r=await this._get(n),{attachment_urls:s,...a}=r,i=a;return s&&(i.attachments=Object.entries(s).reduce((o,[c,u])=>(o[c.slice(11)]={presigned_url:u.presigned_url,mime_type:u.mime_type},o),{})),i}async*listExamples({datasetId:e,datasetName:n,exampleIds:r,asOf:s,splits:a,inlineS3Urls:i,metadata:o,limit:c,offset:u,filter:l,includeAttachments:d}={}){let f;if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)f=e;else if(n!==void 0)f=(await this.readDataset({datasetName:n})).id;else throw new Error("Must provide a datasetName or datasetId");const h=new URLSearchParams({dataset:f}),p=s?typeof s=="string"?s:s?.toISOString():void 0;p&&h.append("as_of",p);const m=i??!0;if(h.append("inline_s3_urls",m.toString()),r!==void 0)for(const v of r)h.append("id",v);if(a!==void 0)for(const v of a)h.append("splits",v);if(o!==void 0){const v=JSON.stringify(o);h.append("metadata",v)}c!==void 0&&h.append("limit",c.toString()),u!==void 0&&h.append("offset",u.toString()),l!==void 0&&h.append("filter",l),d===!0&&["attachment_urls","outputs","metadata"].forEach(v=>h.append("select",v));let y=0;for await(const v of this._getPaginated("/examples",h)){for(const w of v){const{attachment_urls:E,...x}=w,A=x;E&&(A.attachments=Object.entries(E).reduce((N,[j,b])=>(N[j.slice(11)]={presigned_url:b.presigned_url,mime_type:b.mime_type||void 0},N),{})),yield A,y++}if(c!==void 0&&y>=c)break}}async deleteExample(e){de(e);const n=`/examples/${e}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(r,`delete ${n}`,!0),r})}async deleteExamples(e,n){if(e.forEach(r=>de(r)),n?.hardDelete){const r=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${r}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({example_ids:e,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(s,"hard delete examples",!0),s})}else{const r=new URLSearchParams;e.forEach(s=>r.append("example_ids",s)),await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/examples?${r.toString()}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(s,"delete examples",!0),s})}}async updateExample(e,n){let r;n?r=e:r=e.id,de(r);let s;n?s={id:r,...n}:s=e;let a;return s.dataset_id!==void 0?a=s.dataset_id:a=(await this.readExample(r)).dataset_id,this._updateExamplesMultipart(a,[s])}async updateExamples(e){let n;return e[0].dataset_id===void 0?n=(await this.readExample(e[0].id)).dataset_id:n=e[0].dataset_id,this._updateExamplesMultipart(n,e)}async readDatasetVersion({datasetId:e,datasetName:n,asOf:r,tag:s}){let a;if(e?a=e:a=(await this.readDataset({datasetName:n})).id,de(a),r&&s||!r&&!s)throw new Error("Exactly one of asOf and tag must be specified.");const i=new URLSearchParams;return r!==void 0&&i.append("as_of",typeof r=="string"?r:r.toISOString()),s!==void 0&&i.append("tag",s),await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${a}/version?${i.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(c,"read dataset version"),c})).json()}async listDatasetSplits({datasetId:e,datasetName:n,asOf:r}){let s;if(e===void 0&&n===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?s=(await this.readDataset({datasetName:n})).id:s=e,de(s);const a=new URLSearchParams,i=r?typeof r=="string"?r:r?.toISOString():void 0;return i&&a.append("as_of",i),await this._get(`/datasets/${s}/splits`,a)}async updateDatasetSplits({datasetId:e,datasetName:n,splitName:r,exampleIds:s,remove:a=!1}){let i;if(e===void 0&&n===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?i=(await this.readDataset({datasetName:n})).id:i=e,de(i);const o={split_name:r,examples:s.map(u=>(de(u),u)),remove:a},c=JSON.stringify(o);await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${i}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await W(u,"update dataset splits",!0),u})}async createFeedback(e,n,{score:r,value:s,correction:a,comment:i,sourceInfo:o,feedbackSourceType:c="api",sourceRunId:u,feedbackId:l,feedbackConfig:d,projectId:f,comparativeExperimentId:h}){if(!e&&!f)throw new Error("One of runId or projectId must be provided");if(e&&f)throw new Error("Only one of runId or projectId can be provided");const p={type:c??"api",metadata:o??{}};u!==void 0&&p?.metadata!==void 0&&!p.metadata.__run&&(p.metadata.__run={run_id:u}),p?.metadata!==void 0&&p.metadata.__run?.run_id!==void 0&&de(p.metadata.__run.run_id);const m={id:l??Fn(),run_id:e,key:n,score:Uh(r),value:s,correction:a,comment:i,feedback_source:p,comparative_experiment_id:h,feedbackConfig:d,session_id:f},y=JSON.stringify(m),v=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const w=await this._fetch(v,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:y});return await W(w,"create feedback",!0),w}),m}async updateFeedback(e,{score:n,value:r,correction:s,comment:a}){const i={};n!=null&&(i.score=Uh(n)),r!=null&&(i.value=r),s!=null&&(i.correction=s),a!=null&&(i.comment=a),de(e);const o=JSON.stringify(i);await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await W(c,"update feedback",!0),c})}async readFeedback(e){de(e);const n=`/feedback/${e}`;return await this._get(n)}async deleteFeedback(e){de(e);const n=`/feedback/${e}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(r,`delete ${n}`,!0),r})}async*listFeedback({runIds:e,feedbackKeys:n,feedbackSourceTypes:r}={}){const s=new URLSearchParams;if(e)for(const a of e)de(a),s.append("run",a);if(n)for(const a of n)s.append("key",a);if(r)for(const a of r)s.append("source",a);for await(const a of this._getPaginated("/feedback",s))yield*a}async createPresignedFeedbackToken(e,n,{expiration:r,feedbackConfig:s}={}){const a={run_id:e,feedback_key:n,feedback_config:s};r?typeof r=="string"?a.expires_at=r:(r?.hours||r?.minutes||r?.days)&&(a.expires_in=r):a.expires_in={hours:3};const i=JSON.stringify(a);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await W(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:e,experimentIds:n,referenceDatasetId:r,createdAt:s,description:a,metadata:i,id:o}){if(n.length===0)throw new Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:n[0]})).reference_dataset_id),!r==null)throw new Error("A reference dataset is required");const c={id:o,name:e,experiment_ids:n,reference_dataset_id:r,description:a,created_at:(s??new Date)?.toISOString(),extra:{}};i&&(c.extra.metadata=i);const u=JSON.stringify(c);return(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await W(d,"create comparative experiment"),d})).json()}async*listPresignedFeedbackTokens(e){de(e);const n=new URLSearchParams({run_id:e});for await(const r of this._getPaginated("/feedback/tokens",n))yield*r}_selectEvalResults(e){let n;return"results"in e?n=e.results:Array.isArray(e)?n=e:n=[e],n}async _logEvaluationFeedback(e,n,r){const s=this._selectEvalResults(e),a=[];for(const i of s){let o=r||{};i.evaluatorInfo&&(o={...i.evaluatorInfo,...o});let c=null;i.targetRunId?c=i.targetRunId:n&&(c=n.id),a.push(await this.createFeedback(c,i.key,{score:i.score,value:i.value,comment:i.comment,correction:i.correction,sourceInfo:o,sourceRunId:i.sourceRunId,feedbackConfig:i.feedbackConfig,feedbackSourceType:"model"}))}return[s,a]}async logEvaluationFeedback(e,n,r){const[s]=await this._logEvaluationFeedback(e,n,r);return s}async*listAnnotationQueues(e={}){const{queueIds:n,name:r,nameContains:s,limit:a}=e,i=new URLSearchParams;n&&n.forEach((c,u)=>{de(c,`queueIds[${u}]`),i.append("ids",c)}),r&&i.append("name",r),s&&i.append("name_contains",s),i.append("limit",(a!==void 0?Math.min(a,100):100).toString());let o=0;for await(const c of this._getPaginated("/annotation-queues",i))if(yield*c,o++,a!==void 0&&o>=a)break}async createAnnotationQueue(e){const{name:n,description:r,queueId:s,rubricInstructions:a}=e,i={name:n,description:r,id:s||Fn(),rubric_instructions:a},o=JSON.stringify(Object.fromEntries(Object.entries(i).filter(([u,l])=>l!==void 0)));return(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await W(u,"create annotation queue"),u})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${de(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(r,"read annotation queue"),r})).json()}async updateAnnotationQueue(e,n){const{name:r,description:s,rubricInstructions:a}=n,i=JSON.stringify({name:r,description:s,rubric_instructions:a});await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/annotation-queues/${de(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await W(o,"update annotation queue",!0),o})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${de(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(n,"delete annotation queue",!0),n})}async addRunsToAnnotationQueue(e,n){const r=JSON.stringify(n.map((s,a)=>de(s,`runIds[${a}]`).toString()));await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/annotation-queues/${de(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await W(s,"add runs to annotation queue",!0),s})}async getRunFromAnnotationQueue(e,n){const r=`/annotation-queues/${de(e,"queueId")}/run`;return(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(a,"get run from annotation queue"),a})).json()}async deleteRunFromAnnotationQueue(e,n){await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${de(e,"queueId")}/runs/${de(n,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(r,"delete run from annotation queue",!0),r})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${de(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(r,"get size from annotation queue"),r})).json()}async _currentTenantIsOwner(e){const n=await this._getSettings();return e=="-"||n.tenant_handle===e}async _ownerConflictError(e,n){const r=await this._getSettings();return new Error(`Cannot ${e} for another tenant.\n\n Current tenant: ${r.tenant_handle}\n\n Requested tenant: ${n}`)}async _getLatestCommitHash(e){const r=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(s,"get latest commit hash"),s})).json();if(r.commits.length!==0)return r.commits[0].commit_hash}async _likeOrUnlikePrompt(e,n){const[r,s,a]=Sn(e),i=JSON.stringify({like:n});return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/likes/${r}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await W(c,`${n?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(e){const[n,r,s]=Sn(e);if(await this._currentTenantIsOwner(n)){const a=await this._getSettings();return s!=="latest"?`${this.getHostUrl()}/prompts/${r}/${s.substring(0,8)}?organizationId=${a.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${a.id}`}else return s!=="latest"?`${this.getHostUrl()}/hub/${n}/${r}/${s.substring(0,8)}`:`${this.getHostUrl()}/hub/${n}/${r}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){for await(const n of this._getPaginated(`/commits/${e}/`,new URLSearchParams,r=>r.commits))yield*n}async*listPrompts(e){const n=new URLSearchParams;n.append("sort_field",e?.sortField??"updated_at"),n.append("sort_direction","desc"),n.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&n.append("is_public",e.isPublic.toString()),e?.query&&n.append("query",e.query);for await(const r of this._getPaginated("/repos",n,s=>s.repos))yield*r}async getPrompt(e){const[n,r,s]=Sn(e),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return o?.status===404?null:(await W(o,"get prompt"),o)}))?.json();return i?.repo?i.repo:null}async createPrompt(e,n){const r=await this._getSettings();if(n?.isPublic&&!r.tenant_handle)throw new Error(`Cannot create a public prompt without first\n\n creating a LangChain Hub handle.\n You can add a handle by creating a public prompt at:\n\n https://smith.langchain.com/prompts`);const[s,a,i]=Sn(e);if(!await this._currentTenantIsOwner(s))throw await this._ownerConflictError("create a prompt",s);const o={repo_handle:a,...n?.description&&{description:n.description},...n?.readme&&{readme:n.readme},...n?.tags&&{tags:n.tags},is_public:!!n?.isPublic},c=JSON.stringify(o),u=await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await W(d,"create prompt"),d}),{repo:l}=await u.json();return l}async createCommit(e,n,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[s,a,i]=Sn(e),o=r?.parentCommitHash==="latest"||!r?.parentCommitHash?await this._getLatestCommitHash(`${s}/${a}`):r?.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(n)),parent_commit:o},u=JSON.stringify(c),d=await(await this.caller.call(async()=>{const f=await this._fetch(`${this.apiUrl}/commits/${s}/${a}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await W(f,"create commit"),f})).json();return this._getPromptUrl(`${s}/${a}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(e,n=[]){return this._updateExamplesMultipart(e,n)}async _updateExamplesMultipart(e,n=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const r=new FormData;for(const i of n){const o=i.id,c={...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split}},u=yt(c,`Serializing body for example with id: ${o}`),l=new Blob([u],{type:"application/json"});if(r.append(o,l),i.inputs){const d=yt(i.inputs,`Serializing inputs for example with id: ${o}`),f=new Blob([d],{type:"application/json"});r.append(`${o}.inputs`,f)}if(i.outputs){const d=yt(i.outputs,`Serializing outputs whle updating example with id: ${o}`),f=new Blob([d],{type:"application/json"});r.append(`${o}.outputs`,f)}if(i.attachments)for(const[d,f]of Object.entries(i.attachments)){let h,p;Array.isArray(f)?[h,p]=f:(h=f.mimeType,p=f.data);const m=new Blob([p],{type:`${h}; length=${p.byteLength}`});r.append(`${o}.attachment.${d}`,m)}if(i.attachments_operations){const d=yt(i.attachments_operations,`Serializing attachments while updating example with id: ${o}`),f=new Blob([d],{type:"application/json"});r.append(`${o}.attachments_operations`,f)}}const s=e??n[0]?.dataset_id;return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${s}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await W(i,"update examples"),i})).json()}async uploadExamplesMultipart(e,n=[]){return this._uploadExamplesMultipart(e,n)}async _uploadExamplesMultipart(e,n=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const r=new FormData;for(const a of n){const i=(a.id??Fn()).toString(),o={created_at:a.created_at,...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split},...a.source_run_id&&{source_run_id:a.source_run_id},...a.use_source_run_io&&{use_source_run_io:a.use_source_run_io},...a.use_source_run_attachments&&{use_source_run_attachments:a.use_source_run_attachments}},c=yt(o,`Serializing body for uploaded example with id: ${i}`),u=new Blob([c],{type:"application/json"});if(r.append(i,u),a.inputs){const l=yt(a.inputs,`Serializing inputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});r.append(`${i}.inputs`,d)}if(a.outputs){const l=yt(a.outputs,`Serializing outputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});r.append(`${i}.outputs`,d)}if(a.attachments)for(const[l,d]of Object.entries(a.attachments)){let f,h;Array.isArray(d)?[f,h]=d:(f=d.mimeType,h=d.data);const p=new Blob([h],{type:`${f}; length=${h.byteLength}`});r.append(`${i}.attachment.${l}`,p)}}return(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await W(a,"upload examples"),a})).json()}async updatePrompt(e,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[r,s]=Sn(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);const a={};if(n?.description!==void 0&&(a.description=n.description),n?.readme!==void 0&&(a.readme=n.readme),n?.tags!==void 0&&(a.tags=n.tags),n?.isPublic!==void 0&&(a.is_public=n.isPublic),n?.isArchived!==void 0&&(a.is_archived=n.isArchived),Object.keys(a).length===0)throw new Error("No valid update options provided");const i=JSON.stringify(a);return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/repos/${r}/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await W(c,"update prompt"),c})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[n,r,s]=Sn(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("delete a prompt",n);return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(i,"delete prompt"),i})).json()}_getPromptCacheKey(e,n){return`${e}${n?":with_model":""}`}async _fetchPromptFromApi(e,n){const[r,s,a]=Sn(e),o=await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/commits/${r}/${s}/${a}${n?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await W(c,"pull prompt commit"),c})).json();return{owner:r,repo:s,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async pullPromptCommit(e,n){if(!n?.skipCache&&this._cache){const r=this._getPromptCacheKey(e,n?.includeModel),s=this._cache.get(r);if(s)return s;const a=await this._fetchPromptFromApi(e,n);return this._cache.set(r,a),a}return this._fetchPromptFromApi(e,n)}async _pullPrompt(e,n){const r=await this.pullPromptCommit(e,{includeModel:n?.includeModel,skipCache:n?.skipCache});return JSON.stringify(r.manifest)}async pushPrompt(e,n){return await this.promptExists(e)?n&&Object.keys(n).some(s=>s!=="object")&&await this.updatePrompt(e,{description:n?.description,readme:n?.readme,tags:n?.tags,isPublic:n?.isPublic}):await this.createPrompt(e,{description:n?.description,readme:n?.readme,tags:n?.tags,isPublic:n?.isPublic}),n?.object?await this.createCommit(e,n?.object,{parentCommitHash:n?.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,n={}){const{sourceApiUrl:r=this.apiUrl,datasetName:s}=n,[a,i]=this.parseTokenOrUrl(e,r),o=new Zr({apiUrl:a,apiKey:"placeholder"}),c=await o.readSharedDataset(i),u=s||c.name;try{if(await this.hasDataset({datasetId:u})){console.log(`Dataset ${u} already exists in your tenant. Skipping.`);return}}catch{}const l=await o.listSharedExamples(i),d=await this.createDataset(u,{description:c.description,dataType:c.data_type||"kv",inputsSchema:c.inputs_schema_definition??void 0,outputsSchema:c.outputs_schema_definition??void 0});try{await this.createExamples({inputs:l.map(f=>f.inputs),outputs:l.flatMap(f=>f.outputs?[f.outputs]:[]),datasetId:d.id})}catch(f){throw console.error(`An error occurred while creating dataset ${u}. You should delete it manually.`),f}}parseTokenOrUrl(e,n,r=2,s="dataset"){try{return de(e),[n,e]}catch{}try{const i=new URL(e).pathname.split("/").filter(o=>o!=="");if(i.length>=r){const o=i[i.length-r];return[n,o]}else throw new Error(`Invalid public ${s} URL: ${e}`)}catch{throw new Error(`Invalid public ${s} URL or token: ${e}`)}}get cache(){return this._cache}cleanup(){this._cache&&this._cache.stop()}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();await new Promise(e=>setTimeout(e,1)),await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await Pb()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function qh(t){return"dataset_id"in t||"dataset_name"in t}const Zv=t=>!!["TRACING_V2","TRACING"].find(n=>ot(n)==="true"),Tn=Symbol.for("lc:context_variables"),dc=Symbol.for("langsmith:replica_trace_roots");function Vh(t,e){if(Tn in t)return t[Tn][e]}function qv(t,e,n){const r=Tn in t?t[Tn]:{};r[e]=n,t[Tn]=r}const qr="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function Hh(t){const n=Object.keys(t).sort().map(r=>`${r}:${t[r]??""}`).join("|");return zr(n,qr)}function Vv(t){return t.replace(/[-:.]/g,"")}function Gh(t,e=1){const n=e.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(t).toISOString().slice(0,-1)}${n}Z`}function Wh(t,e,n=1){const r=Gh(t,n);return{dottedOrder:Vv(r)+e,microsecondPrecisionDatestring:r}}const Hv=new Set(["projectName","updates","reroot"]);function Gv(t){const e={};for(const n of Object.keys(t))Hv.has(n)&&(e[n]=t[n]);return e}class oa{constructor(e,n,r,s){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=n,this.project_name=r,this.replicas=s}static fromHeader(e){const n=e.split(",");let r={},s=[],a,i;for(const o of n){const[c,u]=o.split("="),l=decodeURIComponent(u);c==="langsmith-metadata"?r=JSON.parse(l):c==="langsmith-tags"?s=l.split(","):c==="langsmith-project"?a=l:c==="langsmith-replicas"&&(i=JSON.parse(l).map(f=>Array.isArray(f)?f:Gv(f)))}return new oa(r,s,a,i)}toHeader(){const e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}}class ft{constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Wv(e)){Object.assign(this,{...e});return}const n=ft.getDefaultConfig(),{metadata:r,...s}=e,a=s.client??ft.getSharedClient(),i={...r,...s?.extra?.metadata};if(s.extra={...s.extra,metadata:i},"id"in s&&s.id==null&&delete s.id,Object.assign(this,{...n,...s,client:a}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=Gh(this.start_time,this.execution_order)),this.id||(this.id=gb(this._serialized_start_time??this.start_time)),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=Yv(this.replicas),!this.dotted_order){const{dottedOrder:o}=Wh(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+o:this.dotted_order=o}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){const e=Date.now();return{run_type:"chain",project_name:bd(),child_runs:[],api_url:Xt("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Xt("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return ft.sharedClient||(ft.sharedClient=new Zr),ft.sharedClient}createChild(e){const n=this.child_execution_order+1,r=this.replicas?.map(l=>{const{reroot:d,...f}=l;return f}),s=e.replicas??r,a=new ft({...e,parent_run:this,project_name:this.project_name,replicas:s,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:n,child_execution_order:n});Tn in this&&(a[Tn]=this[Tn]);const i=Symbol.for("lc:child_config"),o=e.extra?.[i]??this.extra[i];if(Kv(o)){const l={...o},d=Jv(l.callbacks)?l.callbacks.copy?.():void 0;d&&(Object.assign(d,{_parentRunId:a.id}),d.handlers?.find(Jh)?.updateFromRunTree?.(a),l.callbacks=d),a.extra[i]=l}const c=new Set;let u=this;for(;u!=null&&!c.has(u.id);)c.add(u.id),u.child_execution_order=Math.max(u.child_execution_order,n),u=u.parent_run;return this.child_runs.push(a),a}async end(e,n,r=Date.now(),s){this.outputs=this.outputs??e,this.error=this.error??n,this.end_time=this.end_time??r,s&&Object.keys(s).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...s}}:{metadata:s})}_convertToCreate(e,n,r=!0){const s=e.extra??{};if(s?.runtime?.library===void 0&&(s.runtime||(s.runtime={}),n))for(const[o,c]of Object.entries(n))s.runtime[o]||(s.runtime[o]=c);let a,i;return r?(i=e.parent_run?.id??e.parent_run_id,a=[]):(a=e.child_runs.map(o=>this._convertToCreate(o,n,r)),i=void 0),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:s,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:a,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_sliceParentId(e,n){if(n.dotted_order){const r=n.dotted_order.split(".");let s=null;for(let a=0;a<r.length;a++)if(r[a].slice(-36)===e){s=a;break}if(s!==null){const a=r.slice(s+1);n.dotted_order=a.join("."),a.length>0?n.trace_id=a[0].slice(-36):n.trace_id=n.id}}n.parent_run_id===e&&(n.parent_run_id=void 0)}_setReplicaTraceRoot(e,n){const r=Vh(this,dc)??{};r[e]=n,qv(this,dc,r);for(const s of this.child_runs)s._setReplicaTraceRoot(e,n)}_remapForProject(e){const{projectName:n,runtimeEnv:r,excludeChildRuns:s=!0,reroot:a=!1,distributedParentId:i,apiUrl:o,apiKey:c,workspaceId:u}=e,l=this._convertToCreate(this,r,s);if(n===this.project_name)return{...l,session_name:n};if(a){if(i)this._sliceParentId(i,l);else if(l.parent_run_id=void 0,l.dotted_order){const w=l.dotted_order.split(".");w.length>0&&(l.dotted_order=w[w.length-1],l.trace_id=l.id)}const v=Hh({projectName:n,apiUrl:o,apiKey:c,workspaceId:u});this._setReplicaTraceRoot(v,l.id)}let d;if(!a){const v=Vh(this,dc)??{},w=Hh({projectName:n,apiUrl:o,apiKey:c,workspaceId:u});if(d=v[w],d&&(l.trace_id=d,l.dotted_order)){const E=l.dotted_order.split(".");let x=null;for(let A=0;A<E.length;A++)if(E[A].slice(-36)===d){x=A;break}if(x!==null){const A=E.slice(x);l.dotted_order=A.join(".")}}}const f=l.id,h=zr(`${f}:${n}`,qr);let p;l.trace_id?p=zr(`${l.trace_id}:${n}`,qr):p=h;let m;l.parent_run_id&&(m=zr(`${l.parent_run_id}:${n}`,qr));let y;return l.dotted_order&&(y=l.dotted_order.split(".").map(E=>{const x=E.slice(-36),A=zr(`${x}:${n}`,qr);return E.slice(0,-36)+A}).join(".")),{...l,id:h,trace_id:p,parent_run_id:m,dotted_order:y,session_name:n}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{const n=Id();if(this.replicas&&this.replicas.length>0)for(const{projectName:r,apiKey:s,apiUrl:a,workspaceId:i,reroot:o}of this.replicas){const c=this._remapForProject({projectName:r??this.project_name,runtimeEnv:n,excludeChildRuns:!0,reroot:o,distributedParentId:this.distributedParentId,apiUrl:a,apiKey:s,workspaceId:i});await this.client.createRun(c,{apiKey:s,apiUrl:a,workspaceId:i})}else{const r=this._convertToCreate(this,n,e);await this.client.createRun(r)}if(!e){Ed("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const r of this.child_runs)await r.postRun(!1)}this.child_runs=[]}catch(n){console.error(`Error in postRun for run ${this.id}:`,n)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(const{projectName:n,apiKey:r,apiUrl:s,workspaceId:a,updates:i,reroot:o}of this.replicas){const c=this._remapForProject({projectName:n??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:o,distributedParentId:this.distributedParentId,apiUrl:s,apiKey:r,workspaceId:a}),u={id:c.id,name:c.name,run_type:c.run_type,start_time:c.start_time,outputs:c.outputs,error:c.error,parent_run_id:c.parent_run_id,session_name:c.session_name,reference_example_id:c.reference_example_id,end_time:c.end_time,dotted_order:c.dotted_order,trace_id:c.trace_id,events:c.events,tags:c.tags,extra:c.extra,attachments:this.attachments,...i};e?.excludeInputs||(u.inputs=c.inputs),await this.client.updateRun(c.id,u,{apiKey:r,apiUrl:s,workspaceId:a})}else try{const n={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e?.excludeInputs||(n.inputs=this.inputs),await this.client.updateRun(this.id,n)}catch(n){console.error(`Error in patchRun for run ${this.id}`,n)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,n){const r=e?.callbacks;let s,a,i,o=Zv();if(r){const u=r?.getParentRunId?.()??"",l=r?.handlers?.find(d=>d?.name=="langchain_tracer");s=l?.getRun?.(u),a=l?.projectName,i=l?.client,o=o||!!l}return s?new ft({name:s.name,id:s.id,trace_id:s.trace_id,dotted_order:s.dotted_order,client:i,tracingEnabled:o,project_name:a,tags:[...new Set((s?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...s?.extra?.metadata,...e?.metadata}}}).createChild(n):new ft({...n,client:i,tracingEnabled:o,project_name:a})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,n){const r="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,s=r["langsmith-trace"];if(!s||typeof s!="string")return;const a=s.trim(),i=a.split(".").map(l=>{const[d,f]=l.split("Z");return{strTime:d,time:Date.parse(d+"Z"),uuid:f}}),o=i[0].uuid,c={...n,name:n?.name??"parent",run_type:n?.run_type??"chain",start_time:n?.start_time??Date.now(),id:i.at(-1)?.uuid,trace_id:o,dotted_order:a};if(r.baggage&&typeof r.baggage=="string"){const l=oa.fromHeader(r.baggage);c.metadata=l.metadata,c.tags=l.tags,c.project_name=l.project_name,c.replicas=l.replicas}const u=new ft(c);return u.distributedParentId=u.id,u}toHeaders(e){const n={"langsmith-trace":this.dotted_order,baggage:new oa(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(const[r,s]of Object.entries(n))e.set(r,s);return n}}Object.defineProperty(ft,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function Wv(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}function Jh(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}function Kh(t){return Array.isArray(t)&&t.some(e=>Jh(e))}function Jv(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}function Kv(t){const e=t?.callbacks;return t!=null&&typeof e=="object"&&(Kh(e?.handlers)||Kh(e))}function Xv(){const t=Xt("LANGSMITH_RUNS_ENDPOINTS");if(!t)return[];try{const e=JSON.parse(t);if(Array.isArray(e)){const n=[];for(const r of e){if(typeof r!="object"||r===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof r}`);continue}if(typeof r.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_url}`);continue}if(typeof r.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_key}`);continue}n.push({apiUrl:r.api_url.replace(/\\/$/,""),apiKey:r.api_key})}return n}else if(typeof e=="object"&&e!==null){Qv(e);const n=[];for(const[r,s]of Object.entries(e)){const a=r.replace(/\\/$/,"");if(typeof s=="string")n.push({apiUrl:a,apiKey:s});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${r}: expected string, got ${typeof s}`);continue}}return n}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof e}`),[]}catch(e){if(Ov(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function Yv(t){return t?t.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):Xv()}function Qv(t){if(Object.keys(t).length>0&&ot("ENDPOINT"))throw new kv}var e0={};ge(e0,{BaseTracer:()=>ir,isBaseTracer:()=>ar});const t0=t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t};function hc(t,e){if(t)return new ft({...t,start_time:t._serialized_start_time??t.start_time,parent_run:hc(e),child_runs:t.child_runs.map(n=>hc(n)).filter(n=>n!==void 0),extra:{...t.extra,runtime:cd()},tracingEnabled:!1})}function fc(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}function ar(t){return typeof t._addRunToRunMap=="function"}var ir=class extends Fr{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(t){super(...arguments)}copy(){return this}getRunById(t){if(t!==void 0)return this.usesRunTreeMap?t0(this.runTreeMap.get(t)):this.runMap.get(t)}stringifyError(t){return t instanceof Error?t.message+(t?.stack?`\n\n${t.stack}`:""):typeof t=="string"?t:`${t}`}_addChildRun(t,e){t.child_runs.push(e)}_addRunToRunMap(t){const{dottedOrder:e,microsecondPrecisionDatestring:n}=Wh(new Date(t.start_time).getTime(),t.id,t.execution_order),r={...t},s=this.getRunById(r.parent_run_id);if(r.parent_run_id!==void 0?s?(this._addChildRun(s,r),s.child_execution_order=Math.max(s.child_execution_order,r.child_execution_order),r.trace_id=s.trace_id,s.dotted_order!==void 0&&(r.dotted_order=[s.dotted_order,e].join("."),r._serialized_start_time=n)):r.parent_run_id=void 0:(r.trace_id=r.id,r.dotted_order=e,r._serialized_start_time=n),this.usesRunTreeMap){const a=hc(r,s);a!==void 0&&this.runTreeMap.set(r.id,a)}else this.runMap.set(r.id,r);return r}async _endTrace(t){const e=t.parent_run_id!==void 0&&this.getRunById(t.parent_run_id);e?e.child_execution_order=Math.max(e.child_execution_order,t.child_execution_order):await this.persistRun(t),await this.onRunUpdate?.(t),this.usesRunTreeMap?this.runTreeMap.delete(t.id):this.runMap.delete(t.id)}_getExecutionOrder(t){const e=t!==void 0&&this.getRunById(t);return e?e.child_execution_order+1:1}_createRunForLLMStart(t,e,n,r,s,a,i,o){const c=this._getExecutionOrder(r),u=Date.now(),l=i?{...s,metadata:i}:s,d={id:n,name:o??t.id[t.id.length-1],parent_run_id:r,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:e},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:l??{},tags:a||[]};return this._addRunToRunMap(d)}async handleLLMStart(t,e,n,r,s,a,i,o){const c=this.getRunById(n)??this._createRunForLLMStart(t,e,n,r,s,a,i,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(t,e,n,r,s,a,i,o){const c=this._getExecutionOrder(r),u=Date.now(),l=i?{...s,metadata:i}:s,d={id:n,name:o??t.id[t.id.length-1],parent_run_id:r,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:e},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:l??{},tags:a||[]};return this._addRunToRunMap(d)}async handleChatModelStart(t,e,n,r,s,a,i,o){const c=this.getRunById(n)??this._createRunForChatModelStart(t,e,n,r,s,a,i,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(t,e,n,r,s){const a=this.getRunById(e);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.outputs=t,a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...s},await this.onLLMEnd?.(a),await this._endTrace(a),a}async handleLLMError(t,e,n,r,s){const a=this.getRunById(e);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(t),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...s},await this.onLLMError?.(a),await this._endTrace(a),a}_createRunForChainStart(t,e,n,r,s,a,i,o,c){const u=this._getExecutionOrder(r),l=Date.now(),d={id:n,name:o??t.id[t.id.length-1],parent_run_id:r,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:e,execution_order:u,child_execution_order:u,run_type:i??"chain",child_runs:[],extra:a?{...c,metadata:a}:{...c},tags:s||[]};return this._addRunToRunMap(d)}async handleChainStart(t,e,n,r,s,a,i,o){const c=this.getRunById(n)??this._createRunForChainStart(t,e,n,r,s,a,i,o);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(t,e,n,r,s){const a=this.getRunById(e);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.outputs=fc(t,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),s?.inputs!==void 0&&(a.inputs=fc(s.inputs,"input")),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(t,e,n,r,s){const a=this.getRunById(e);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(t),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),s?.inputs!==void 0&&(a.inputs=fc(s.inputs,"input")),await this.onChainError?.(a),await this._endTrace(a),a}_createRunForToolStart(t,e,n,r,s,a,i){const o=this._getExecutionOrder(r),c=Date.now(),u={id:n,name:i??t.id[t.id.length-1],parent_run_id:r,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:e},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:a?{metadata:a}:{},tags:s||[]};return this._addRunToRunMap(u)}async handleToolStart(t,e,n,r,s,a,i){const o=this.getRunById(n)??this._createRunForToolStart(t,e,n,r,s,a,i);return await this.onRunCreate?.(o),await this.onToolStart?.(o),o}async handleToolEnd(t,e){const n=this.getRunById(e);if(!n||n?.run_type!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.outputs={output:t},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await this.onToolEnd?.(n),await this._endTrace(n),n}async handleToolError(t,e){const n=this.getRunById(e);if(!n||n?.run_type!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.error=this.stringifyError(t),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await this.onToolError?.(n),await this._endTrace(n),n}async handleAgentAction(t,e){const n=this.getRunById(e);if(!n||n?.run_type!=="chain")return;const r=n;r.actions=r.actions||[],r.actions.push(t),r.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentAction?.(n)}async handleAgentEnd(t,e){const n=this.getRunById(e);!n||n?.run_type!=="chain"||(n.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentEnd?.(n))}_createRunForRetrieverStart(t,e,n,r,s,a,i){const o=this._getExecutionOrder(r),c=Date.now(),u={id:n,name:i??t.id[t.id.length-1],parent_run_id:r,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:e},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:a?{metadata:a}:{},tags:s||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(t,e,n,r,s,a,i){const o=this.getRunById(n)??this._createRunForRetrieverStart(t,e,n,r,s,a,i);return await this.onRunCreate?.(o),await this.onRetrieverStart?.(o),o}async handleRetrieverEnd(t,e){const n=this.getRunById(e);if(!n||n?.run_type!=="retriever")throw new Error("No retriever run to end");return n.end_time=Date.now(),n.outputs={documents:t},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await this.onRetrieverEnd?.(n),await this._endTrace(n),n}async handleRetrieverError(t,e){const n=this.getRunById(e);if(!n||n?.run_type!=="retriever")throw new Error("No retriever run to end");return n.end_time=Date.now(),n.error=this.stringifyError(t),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await this.onRetrieverError?.(n),await this._endTrace(n),n}async handleText(t,e){const n=this.getRunById(e);!n||n?.run_type!=="chain"||(n.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:t}}),await this.onText?.(n))}async handleLLMNewToken(t,e,n,r,s,a){const i=this.getRunById(n);if(!i||i?.run_type!=="llm")throw new Error(\'Invalid "runId" provided to "handleLLMNewToken" callback.\');return i.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:t,idx:e,chunk:a?.chunk}}),await this.onLLMNewToken?.(i,t,{chunk:a?.chunk}),i}},ca={exports:{}};ca.exports;var Xh;function n0(){return Xh||(Xh=1,(function(t){const n=(a=0)=>i=>`\\x1B[${38+a};5;${i}m`,r=(a=0)=>(i,o,c)=>`\\x1B[${38+a};2;${i};${o};${c}m`;function s(){const a=new Map,i={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};i.color.gray=i.color.blackBright,i.bgColor.bgGray=i.bgColor.bgBlackBright,i.color.grey=i.color.blackBright,i.bgColor.bgGrey=i.bgColor.bgBlackBright;for(const[o,c]of Object.entries(i)){for(const[u,l]of Object.entries(c))i[u]={open:`\\x1B[${l[0]}m`,close:`\\x1B[${l[1]}m`},c[u]=i[u],a.set(l[0],l[1]);Object.defineProperty(i,o,{value:c,enumerable:!1})}return Object.defineProperty(i,"codes",{value:a,enumerable:!1}),i.color.close="\\x1B[39m",i.bgColor.close="\\x1B[49m",i.color.ansi256=n(),i.color.ansi16m=r(),i.bgColor.ansi256=n(10),i.bgColor.ansi16m=r(10),Object.defineProperties(i,{rgbToAnsi256:{value:(o,c,u)=>o===c&&c===u?o<8?16:o>248?231:Math.round((o-8)/247*24)+232:16+36*Math.round(o/255*5)+6*Math.round(c/255*5)+Math.round(u/255*5),enumerable:!1},hexToRgb:{value:o=>{const c=/(?<colorString>[a-f\\d]{6}|[a-f\\d]{3})/i.exec(o.toString(16));if(!c)return[0,0,0];let{colorString:u}=c.groups;u.length===3&&(u=u.split("").map(d=>d+d).join(""));const l=Number.parseInt(u,16);return[l>>16&255,l>>8&255,l&255]},enumerable:!1},hexToAnsi256:{value:o=>i.rgbToAnsi256(...i.hexToRgb(o)),enumerable:!1}}),i}Object.defineProperty(t,"exports",{enumerable:!0,get:s})})(ca)),ca.exports}var r0=n0(),Yh=Ms(r0),s0={};ge(s0,{ConsoleCallbackHandler:()=>pc});function ut(t,e){return`${t.open}${e}${t.close}`}function Ot(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}function Qh(t){return typeof t=="string"?t.trim():t==null?t:Ot(t,t.toString())}function xn(t){if(!t.end_time)return"";const e=t.end_time-t.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}const{color:pt}=Yh;var pc=class extends ir{name="console_callback_handler";persistRun(t){return Promise.resolve()}getParents(t){const e=[];let n=t;for(;n.parent_run_id;){const r=this.runMap.get(n.parent_run_id);if(r)e.push(r),n=r;else break}return e}getBreadcrumbs(t){const n=[...this.getParents(t).reverse(),t].map((r,s,a)=>{const i=`${r.execution_order}:${r.run_type}:${r.name}`;return s===a.length-1?ut(Yh.bold,i):i}).join(" > ");return ut(pt.grey,n)}onChainStart(t){const e=this.getBreadcrumbs(t);console.log(`${ut(pt.green,"[chain/start]")} [${e}] Entering Chain run with input: ${Ot(t.inputs,"[inputs]")}`)}onChainEnd(t){const e=this.getBreadcrumbs(t);console.log(`${ut(pt.cyan,"[chain/end]")} [${e}] [${xn(t)}] Exiting Chain run with output: ${Ot(t.outputs,"[outputs]")}`)}onChainError(t){const e=this.getBreadcrumbs(t);console.log(`${ut(pt.red,"[chain/error]")} [${e}] [${xn(t)}] Chain run errored with error: ${Ot(t.error,"[error]")}`)}onLLMStart(t){const e=this.getBreadcrumbs(t),n="prompts"in t.inputs?{prompts:t.inputs.prompts.map(r=>r.trim())}:t.inputs;console.log(`${ut(pt.green,"[llm/start]")} [${e}] Entering LLM run with input: ${Ot(n,"[inputs]")}`)}onLLMEnd(t){const e=this.getBreadcrumbs(t);console.log(`${ut(pt.cyan,"[llm/end]")} [${e}] [${xn(t)}] Exiting LLM run with output: ${Ot(t.outputs,"[response]")}`)}onLLMError(t){const e=this.getBreadcrumbs(t);console.log(`${ut(pt.red,"[llm/error]")} [${e}] [${xn(t)}] LLM run errored with error: ${Ot(t.error,"[error]")}`)}onToolStart(t){const e=this.getBreadcrumbs(t);console.log(`${ut(pt.green,"[tool/start]")} [${e}] Entering Tool run with input: "${Qh(t.inputs.input)}"`)}onToolEnd(t){const e=this.getBreadcrumbs(t);console.log(`${ut(pt.cyan,"[tool/end]")} [${e}] [${xn(t)}] Exiting Tool run with output: "${Qh(t.outputs?.output)}"`)}onToolError(t){const e=this.getBreadcrumbs(t);console.log(`${ut(pt.red,"[tool/error]")} [${e}] [${xn(t)}] Tool run errored with error: ${Ot(t.error,"[error]")}`)}onRetrieverStart(t){const e=this.getBreadcrumbs(t);console.log(`${ut(pt.green,"[retriever/start]")} [${e}] Entering Retriever run with input: ${Ot(t.inputs,"[inputs]")}`)}onRetrieverEnd(t){const e=this.getBreadcrumbs(t);console.log(`${ut(pt.cyan,"[retriever/end]")} [${e}] [${xn(t)}] Exiting Retriever run with output: ${Ot(t.outputs,"[outputs]")}`)}onRetrieverError(t){const e=this.getBreadcrumbs(t);console.log(`${ut(pt.red,"[retriever/error]")} [${e}] [${xn(t)}] Retriever run errored with error: ${Ot(t.error,"[error]")}`)}onAgentAction(t){const e=t,n=this.getBreadcrumbs(t);console.log(`${ut(pt.blue,"[agent/action]")} [${n}] Agent selected action: ${Ot(e.actions[e.actions.length-1],"[action]")}`)}};let mc;const ef=()=>{if(mc===void 0){const t=Jt("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};mc=new Zr(t)}return mc};let a0=class{getStore(){}run(e,n){return n()}};const gc=Symbol.for("ls:tracing_async_local_storage"),i0=new a0;let o0=class{getInstance(){return globalThis[gc]??i0}initializeGlobalInstance(e){globalThis[gc]===void 0&&(globalThis[gc]=e)}};const c0=new o0;function u0(t=!1){const e=c0.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function _c(t){return typeof t=="function"&&"langsmith:traceable"in t}var l0={};ge(l0,{LangChainTracer:()=>ua});function d0(t){let e;for(const n of t)for(const r of n)on.isInstance(r.message)&&r.message.usage_metadata!==void 0&&(e=Gi(e,r.message.usage_metadata));return e}var ua=class ny extends ir{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;constructor(e={}){super(e);const{exampleId:n,projectName:r,client:s,replicas:a}=e;this.projectName=r??bd(),this.replicas=a,this.exampleId=n,this.client=s??ef();const i=ny.getTraceableRunTree();i&&this.updateFromRunTree(i)}async persistRun(e){}async onRunCreate(e){e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){const n=this.getRunTreeWithTracingConfig(e.id);e.extra?.lc_defers_inputs?await n?.postRun():await n?.patchRun()}onLLMEnd(e){const n=e.outputs;if(n?.generations){const r=d0(n.generations);if(r!==void 0){e.extra=e.extra??{};const s=e.extra.metadata??{};s.usage_metadata=r,e.extra.metadata=s}}}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let n=e;const r=new Set;for(;n.parent_run&&!(r.has(n.id)||(r.add(n.id),!n.parent_run));)n=n.parent_run;r.clear();const s=[n];for(;s.length>0;){const a=s.shift();!a||r.has(a.id)||(r.add(a.id),this.runTreeMap.set(a.id,a),a.child_runs&&s.push(...a.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(e){const n=this.runTreeMap.get(e);if(n)return new ft({...n,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return u0(!0)}catch{return}}};let Un;function h0(){const t="default"in cn?cn.default:cn;return new t({autoStart:!0,concurrency:1})}function f0(){return typeof Un>"u"&&(Un=h0()),Un}async function Fe(t,e){if(e===!0){const n=Nr();n!==void 0?await n.run(void 0,async()=>t()):await t()}else Un=f0(),Un.add(async()=>{const n=Nr();n!==void 0?await n.run(void 0,async()=>t()):await t()})}async function p0(){const t=ef();await Promise.allSettled([typeof Un<"u"?Un.onIdle():Promise.resolve(),t.awaitPendingTraceBatches()])}var m0={};ge(m0,{awaitAllCallbacks:()=>p0,consumeCallback:()=>Fe});const g0=t=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(n=>Jt(n)==="true");function tf(t){const e=Nr();return e===void 0?void 0:e.getStore()?.[Rr]?.[t]}const _0=Symbol("lc:configure_hooks"),y0=()=>tf(_0)||[];var w0={};ge(w0,{BaseCallbackManager:()=>nf,BaseRunManager:()=>Hr,CallbackManager:()=>lt,CallbackManagerForChainRun:()=>sf,CallbackManagerForLLMRun:()=>yc,CallbackManagerForRetrieverRun:()=>rf,CallbackManagerForToolRun:()=>af,ensureHandler:()=>Gr,parseCallbackConfigArg:()=>Vr});function Vr(t){return t?Array.isArray(t)||"name"in t?{callbacks:t}:t:{}}var nf=class{setHandler(t){return this.setHandlers([t])}},Hr=class{constructor(t,e,n,r,s,a,i,o){this.runId=t,this.handlers=e,this.inheritableHandlers=n,this.tags=r,this.inheritableTags=s,this.metadata=a,this.inheritableMetadata=i,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(e=>Fe(async()=>{try{await e.handleText?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleText: ${n}`),e.raiseError)throw n}},e.awaitHandlers)))}async handleCustomEvent(t,e,n,r,s){await Promise.all(this.handlers.map(a=>Fe(async()=>{try{await a.handleCustomEvent?.(t,e,this.runId,this.tags,this.metadata)}catch(i){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${i}`),a.raiseError)throw i}},a.awaitHandlers)))}},rf=class extends Hr{getChild(t){const e=new lt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleRetrieverEnd(t){await Promise.all(this.handlers.map(e=>Fe(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetriever`),e.raiseError)throw n}},e.awaitHandlers)))}async handleRetrieverError(t){await Promise.all(this.handlers.map(e=>Fe(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverError?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetrieverError: ${n}`),e.raiseError)throw t}},e.awaitHandlers)))}},yc=class extends Hr{async handleLLMNewToken(t,e,n,r,s,a){await Promise.all(this.handlers.map(i=>Fe(async()=>{if(!i.ignoreLLM)try{await i.handleLLMNewToken?.(t,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,a)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMNewToken: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleLLMError(t,e,n,r,s){await Promise.all(this.handlers.map(a=>Fe(async()=>{if(!a.ignoreLLM)try{await a.handleLLMError?.(t,this.runId,this._parentRunId,this.tags,s)}catch(i){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMError: ${i}`),a.raiseError)throw i}},a.awaitHandlers)))}async handleLLMEnd(t,e,n,r,s){await Promise.all(this.handlers.map(a=>Fe(async()=>{if(!a.ignoreLLM)try{await a.handleLLMEnd?.(t,this.runId,this._parentRunId,this.tags,s)}catch(i){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMEnd: ${i}`),a.raiseError)throw i}},a.awaitHandlers)))}},sf=class extends Hr{getChild(t){const e=new lt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleChainError(t,e,n,r,s){await Promise.all(this.handlers.map(a=>Fe(async()=>{if(!a.ignoreChain)try{await a.handleChainError?.(t,this.runId,this._parentRunId,this.tags,s)}catch(i){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainError: ${i}`),a.raiseError)throw i}},a.awaitHandlers)))}async handleChainEnd(t,e,n,r,s){await Promise.all(this.handlers.map(a=>Fe(async()=>{if(!a.ignoreChain)try{await a.handleChainEnd?.(t,this.runId,this._parentRunId,this.tags,s)}catch(i){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainEnd: ${i}`),a.raiseError)throw i}},a.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(e=>Fe(async()=>{if(!e.ignoreAgent)try{await e.handleAgentAction?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentAction: ${n}`),e.raiseError)throw n}},e.awaitHandlers)))}async handleAgentEnd(t){await Promise.all(this.handlers.map(e=>Fe(async()=>{if(!e.ignoreAgent)try{await e.handleAgentEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentEnd: ${n}`),e.raiseError)throw n}},e.awaitHandlers)))}},af=class extends Hr{getChild(t){const e=new lt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleToolError(t){await Promise.all(this.handlers.map(e=>Fe(async()=>{if(!e.ignoreAgent)try{await e.handleToolError?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolError: ${n}`),e.raiseError)throw n}},e.awaitHandlers)))}async handleToolEnd(t){await Promise.all(this.handlers.map(e=>Fe(async()=>{if(!e.ignoreAgent)try{await e.handleToolEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolEnd: ${n}`),e.raiseError)throw n}},e.awaitHandlers)))}},lt=class Os extends nf{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(e,n){super(),this.handlers=n?.handlers??this.handlers,this.inheritableHandlers=n?.inheritableHandlers??this.inheritableHandlers,this.tags=n?.tags??this.tags,this.inheritableTags=n?.inheritableTags??this.inheritableTags,this.metadata=n?.metadata??this.metadata,this.inheritableMetadata=n?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,n,r=void 0,s=void 0,a=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(n.map(async(u,l)=>{const d=l===0&&r?r:En();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return ar(f)&&f._createRunForLLMStart(e,[u],d,this._parentRunId,a,this.tags,this.metadata,c),Fe(async()=>{try{await f.handleLLMStart?.(e,[u],d,this._parentRunId,a,this.tags,this.metadata,c)}catch(h){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${h}`),f.raiseError)throw h}},f.awaitHandlers)})),new yc(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,n,r=void 0,s=void 0,a=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(n.map(async(u,l)=>{const d=l===0&&r?r:En();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return ar(f)&&f._createRunForChatModelStart(e,[u],d,this._parentRunId,a,this.tags,this.metadata,c),Fe(async()=>{try{if(f.handleChatModelStart)await f.handleChatModelStart?.(e,[u],d,this._parentRunId,a,this.tags,this.metadata,c);else if(f.handleLLMStart){const h=Xi(u);await f.handleLLMStart?.(e,[h],d,this._parentRunId,a,this.tags,this.metadata,c)}}catch(h){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${h}`),f.raiseError)throw h}},f.awaitHandlers)})),new yc(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,n,r=En(),s=void 0,a=void 0,i=void 0,o=void 0,c=void 0,u=void 0){return await Promise.all(this.handlers.map(l=>{if(!l.ignoreChain)return ar(l)&&l._createRunForChainStart(e,n,r,this._parentRunId,this.tags,this.metadata,s,o,u),Fe(async()=>{try{await l.handleChainStart?.(e,n,r,this._parentRunId,this.tags,this.metadata,s,o,u)}catch(d){if((l.raiseError?console.error:console.warn)(`Error in handler ${l.constructor.name}, handleChainStart: ${d}`),l.raiseError)throw d}},l.awaitHandlers)})),new sf(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,n,r=En(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreAgent)return ar(c)&&c._createRunForToolStart(e,n,r,this._parentRunId,this.tags,this.metadata,o),Fe(async()=>{try{await c.handleToolStart?.(e,n,r,this._parentRunId,this.tags,this.metadata,o)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleToolStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new af(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,n,r=En(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return ar(c)&&c._createRunForRetrieverStart(e,n,r,this._parentRunId,this.tags,this.metadata,o),Fe(async()=>{try{await c.handleRetrieverStart?.(e,n,r,this._parentRunId,this.tags,this.metadata,o)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new rf(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,n,r,s,a){await Promise.all(this.handlers.map(i=>Fe(async()=>{if(!i.ignoreCustomEvent)try{await i.handleCustomEvent?.(e,n,r,this.tags,this.metadata)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}addHandler(e,n=!0){this.handlers.push(e),n&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(n=>n!==e),this.inheritableHandlers=this.inheritableHandlers.filter(n=>n!==e)}setHandlers(e,n=!0){this.handlers=[],this.inheritableHandlers=[];for(const r of e)this.addHandler(r,n)}addTags(e,n=!0){this.removeTags(e),this.tags.push(...e),n&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(n=>!e.includes(n)),this.inheritableTags=this.inheritableTags.filter(n=>!e.includes(n))}addMetadata(e,n=!0){this.metadata={...this.metadata,...e},n&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(const n of Object.keys(e))delete this.metadata[n],delete this.inheritableMetadata[n]}copy(e=[],n=!0){const r=new Os(this._parentRunId);for(const s of this.handlers){const a=this.inheritableHandlers.includes(s);r.addHandler(s,a)}for(const s of this.tags){const a=this.inheritableTags.includes(s);r.addTags([s],a)}for(const s of Object.keys(this.metadata)){const a=Object.keys(this.inheritableMetadata).includes(s);r.addMetadata({[s]:this.metadata[s]},a)}for(const s of e)r.handlers.filter(a=>a.name==="console_callback_handler").some(a=>a.name===s.name)||r.addHandler(s,n);return r}static fromHandlers(e){class n extends Fr{name=En();constructor(){super(),Object.assign(this,e)}}const r=new this;return r.addHandler(new n),r}static configure(e,n,r,s,a,i,o){return this._configureSync(e,n,r,s,a,i,o)}static _configureSync(e,n,r,s,a,i,o){let c;(e||n)&&(Array.isArray(e)||!e?(c=new Os,c.setHandlers(e?.map(Gr)??[],!0)):c=e,c=c.copy(Array.isArray(n)?n.map(Gr):n?.handlers,!1));const u=Jt("LANGCHAIN_VERBOSE")==="true"||o?.verbose,l=ua.getTraceableRunTree()?.tracingEnabled??g0(),d=l||(Jt("LANGCHAIN_TRACING")??!1);if(u||d){if(c||(c=new Os),u&&!c.handlers.some(f=>f.name===pc.prototype.name)){const f=new pc;c.addHandler(f,!0)}if(d&&!c.handlers.some(f=>f.name==="langchain_tracer")&&l){const f=new ua;c.addHandler(f,!0)}if(l){const f=ua.getTraceableRunTree();f&&c._parentRunId===void 0&&(c._parentRunId=f.id,c.handlers.find(p=>p.name==="langchain_tracer")?.updateFromRunTree(f))}}for(const{contextVar:f,inheritable:h=!0,handlerClass:p,envVar:m}of y0()){const y=m&&Jt(m)==="true"&&p;let v;const w=f!==void 0?tf(f):void 0;w&&fd(w)?v=w:y&&(v=new p({})),v!==void 0&&(c||(c=new Os),c.handlers.some(E=>E.name===v.name)||c.addHandler(v,h))}return(r||s)&&c&&(c.addTags(r??[]),c.addTags(s??[],!1)),(a||i)&&c&&(c.addMetadata(a??{}),c.addMetadata(i??{},!1)),c}};function Gr(t){return"name"in t?t:Fr.fromMethods(t)}var of=class{getStore(){}run(t,e){return e()}enterWith(t){}};const b0=new of,cf=Symbol.for("lc:child_config");var v0=class{getInstance(){return Nr()??b0}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[cf]}runWithConfig(t,e,n){const r=lt._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata),s=this.getInstance(),a=s.getStore(),i=r?.getParentRunId(),o=r?.handlers?.find(u=>u?.name==="langchain_tracer");let c;return o&&i?c=o.getRunTreeWithTracingConfig(i):n||(c=new ft({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[cf]:t}),a!==void 0&&a[Rr]!==void 0&&(c===void 0&&(c={}),c[Rr]=a[Rr]),s.run(c,e)}initializeGlobalInstance(t){Nr()===void 0&&$y(t)}};const jt=new v0;var E0={};ge(E0,{AsyncLocalStorageProviderSingleton:()=>jt,MockAsyncLocalStorage:()=>of,_CONTEXT_VARIABLES_KEY:()=>Rr});const wc=25;async function wt(t){return lt._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata)}function la(...t){const e={};for(const n of t.filter(r=>!!r))for(const r of Object.keys(n))if(r==="metadata")e[r]={...e[r],...n[r]};else if(r==="tags"){const s=e[r]??[];e[r]=[...new Set(s.concat(n[r]??[]))]}else if(r==="configurable")e[r]={...e[r],...n[r]};else if(r==="timeout")e.timeout===void 0?e.timeout=n.timeout:n.timeout!==void 0&&(e.timeout=Math.min(e.timeout,n.timeout));else if(r==="signal")e.signal===void 0?e.signal=n.signal:n.signal!==void 0&&("any"in AbortSignal?e.signal=AbortSignal.any([e.signal,n.signal]):e.signal=n.signal);else if(r==="callbacks"){const s=e.callbacks,a=n.callbacks;if(Array.isArray(a))if(!s)e.callbacks=a;else if(Array.isArray(s))e.callbacks=s.concat(a);else{const i=s.copy();for(const o of a)i.addHandler(Gr(o),!0);e.callbacks=i}else if(a)if(!s)e.callbacks=a;else if(Array.isArray(s)){const i=a.copy();for(const o of s)i.addHandler(Gr(o),!0);e.callbacks=i}else e.callbacks=new lt(a._parentRunId,{handlers:s.handlers.concat(a.handlers),inheritableHandlers:s.inheritableHandlers.concat(a.inheritableHandlers),tags:Array.from(new Set(s.tags.concat(a.tags))),inheritableTags:Array.from(new Set(s.inheritableTags.concat(a.inheritableTags))),metadata:{...s.metadata,...a.metadata}})}else{const s=r;e[s]=n[s]??e[s]}return e}const S0=new Set(["string","number","boolean"]);function we(t){const e=jt.getRunnableConfig();let n={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){const{runId:r,runName:s,...a}=e;n=Object.entries(a).reduce((i,[o,c])=>(c!==void 0&&(i[o]=c),i),n)}if(t&&(n=Object.entries(t).reduce((r,[s,a])=>(a!==void 0&&(r[s]=a),r),n)),n?.configurable)for(const r of Object.keys(n.configurable))S0.has(typeof n.configurable[r])&&!n.metadata?.[r]&&(n.metadata||(n.metadata={}),n.metadata[r]=n.configurable[r]);if(n.timeout!==void 0){if(n.timeout<=0)throw new Error("Timeout must be a positive number");const r=n.timeout,s=AbortSignal.timeout(r);n.metadata||(n.metadata={}),n.metadata.timeoutMs===void 0&&(n.metadata.timeoutMs=r),n.signal!==void 0?"any"in AbortSignal&&(n.signal=AbortSignal.any([n.signal,s])):n.signal=s,delete n.timeout}return n}function Ae(t={},{callbacks:e,maxConcurrency:n,recursionLimit:r,runName:s,configurable:a,runId:i}={}){const o=we(t);return e!==void 0&&(delete o.runName,o.callbacks=e),r!==void 0&&(o.recursionLimit=r),n!==void 0&&(o.maxConcurrency=n),s!==void 0&&(o.runName=s),a!==void 0&&(o.configurable={...o.configurable,...a}),i!==void 0&&delete o.runId,o}function un(t){if(t)return{configurable:t.configurable,recursionLimit:t.recursionLimit,callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,maxConcurrency:t.maxConcurrency,timeout:t.timeout,signal:t.signal,store:t.store}}async function ln(t,e){if(e===void 0)return t;let n;return Promise.race([t.catch(r=>{if(!e?.aborted)throw r}),new Promise((r,s)=>{n=()=>{s(Wr(e))},e.addEventListener("abort",n),e.aborted&&s(Wr(e))})]).finally(()=>e.removeEventListener("abort",n))}function Wr(t){return t?.reason instanceof Error?t.reason:typeof t?.reason=="string"?new Error(t.reason):new Error("Aborted")}var T0={};ge(T0,{AsyncGeneratorWithSetup:()=>Bn,IterableReadableStream:()=>Dt,atee:()=>bc,concat:()=>In,pipeGeneratorWithSetup:()=>uf});var Dt=class Sl extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){const n=this.reader.cancel();this.reader.releaseLock(),await n}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){const n=e.getReader();return new Sl({start(r){return s();function s(){return n.read().then(({done:a,value:i})=>{if(a){r.close();return}return r.enqueue(i),s()})}},cancel(){n.releaseLock()}})}static fromAsyncGenerator(e){return new Sl({async pull(n){const{value:r,done:s}=await e.next();s&&n.close(),n.enqueue(r)},async cancel(n){await e.return(n)}})}};function bc(t,e=2){const n=Array.from({length:e},()=>[]);return n.map(async function*(s){for(;;)if(s.length===0){const a=await t.next();for(const i of n)i.push(a)}else{if(s[0].done)return;yield s.shift().value}})}function In(t,e){if(Array.isArray(t)&&Array.isArray(e))return t.concat(e);if(typeof t=="string"&&typeof e=="string")return t+e;if(typeof t=="number"&&typeof e=="number")return t+e;if("concat"in t&&typeof t.concat=="function")return t.concat(e);if(typeof t=="object"&&typeof e=="object"){const n={...t};for(const[r,s]of Object.entries(e))r in n&&!Array.isArray(n[r])?n[r]=In(n[r],s):n[r]=s;return n}else throw new Error(`Cannot concat ${typeof t} and ${typeof e}`)}var Bn=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(t){this.generator=t.generator,this.config=t.config,this.signal=t.signal??this.config?.signal,this.setup=new Promise((e,n)=>{jt.runWithConfig(un(t.config),async()=>{this.firstResult=t.generator.next(),t.startSetup?this.firstResult.then(t.startSetup).then(e,n):this.firstResult.then(r=>e(void 0),n)},!0)})}async next(...t){return this.signal?.throwIfAborted(),this.firstResultUsed?jt.runWithConfig(un(this.config),this.signal?async()=>ln(this.generator.next(...t),this.signal):async()=>this.generator.next(...t),!0):(this.firstResultUsed=!0,this.firstResult)}async return(t){return this.generator.return(t)}async throw(t){return this.generator.throw(t)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function uf(t,e,n,r,...s){const a=new Bn({generator:e,startSetup:n,signal:r}),i=await a.setup;return{output:t(a,i,...s),setup:i}}const x0=Object.prototype.hasOwnProperty;function vc(t,e){return x0.call(t,e)}function Ec(t){if(Array.isArray(t)){const n=new Array(t.length);for(let r=0;r<n.length;r++)n[r]=""+r;return n}if(Object.keys)return Object.keys(t);let e=[];for(let n in t)vc(t,n)&&e.push(n);return e}function zt(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Sc(t){let e=0;const n=t.length;let r;for(;e<n;){if(r=t.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}function or(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\\//g,"~1")}function I0(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Tc(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let n=0,r=t.length;n<r;n++)if(Tc(t[n]))return!0}else if(typeof t=="object"){const n=Ec(t),r=n.length;for(var e=0;e<r;e++)if(Tc(t[n[e]]))return!0}}return!1}function lf(t,e){const n=[t];for(const r in e){const s=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof s<"u"&&n.push(`${r}: ${s}`)}return n.join(`\n`)}var A0=class extends Error{constructor(t,e,n,r,s){super(lf(t,{name:e,index:n,operation:r,tree:s})),this.name=e,this.index=n,this.operation=r,this.tree=s,Object.setPrototypeOf(this,new.target.prototype),this.message=lf(t,{name:e,index:n,operation:r,tree:s})}},df={};ge(df,{JsonPatchError:()=>Le,_areEquals:()=>Jr,applyOperation:()=>Zn,applyPatch:()=>ur,applyReducer:()=>$0,deepClone:()=>k0,getValueByPointer:()=>da,validate:()=>hf,validator:()=>ha});const Le=A0,k0=zt;function xc(t){return Object.getOwnPropertyNames(Object.prototype).includes(t)}const cr={add:function(t,e,n){if(xc(e))throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");return t[e]=this.value,{newDocument:n}},remove:function(t,e,n){if(xc(e))throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");var r=t[e];return delete t[e],{newDocument:n,removed:r}},replace:function(t,e,n){if(xc(e))throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:function(t,e,n){let r=da(n,this.path);r&&(r=zt(r));const s=Zn(n,{op:"remove",path:this.from}).removed;return Zn(n,{op:"add",path:this.path,value:s}),{newDocument:n,removed:r}},copy:function(t,e,n){const r=da(n,this.from);return Zn(n,{op:"add",path:this.path,value:zt(r)}),{newDocument:n}},test:function(t,e,n){return{newDocument:n,test:Jr(t[e],this.value)}},_get:function(t,e,n){return this.value=t[e],{newDocument:n}}};var O0={add:function(t,e,n){return Sc(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:n,index:e}},remove:function(t,e,n){var r=t.splice(e,1);return{newDocument:n,removed:r[0]}},replace:function(t,e,n){var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:cr.move,copy:cr.copy,test:cr.test,_get:cr._get};function da(t,e){if(e=="")return t;var n={op:"_get",path:e};return Zn(t,n),n.value}function Zn(t,e,n=!1,r=!0,s=!0,a=0){if(n&&(typeof n=="function"?n(e,0,t,e.path):ha(e,0)),e.path===""){let i={newDocument:t};if(e.op==="add")return i.newDocument=e.value,i;if(e.op==="replace")return i.newDocument=e.value,i.removed=t,i;if(e.op==="move"||e.op==="copy")return i.newDocument=da(t,e.from),e.op==="move"&&(i.removed=t),i;if(e.op==="test"){if(i.test=Jr(t,e.value),i.test===!1)throw new Le("Test operation failed","TEST_OPERATION_FAILED",a,e,t);return i.newDocument=t,i}else{if(e.op==="remove")return i.removed=t,i.newDocument=null,i;if(e.op==="_get")return e.value=t,i;if(n)throw new Le("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",a,e,t);return i}}else{r||(t=zt(t));const o=(e.path||"").split("/");let c=t,u=1,l=o.length,d,f,h;for(typeof n=="function"?h=n:h=ha;;){if(f=o[u],f&&f.indexOf("~")!=-1&&(f=I0(f)),s&&(f=="__proto__"||f=="prototype"&&u>0&&o[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&d===void 0&&(c[f]===void 0?d=o.slice(0,u).join("/"):u==l-1&&(d=e.path),d!==void 0&&h(e,0,t,d)),u++,Array.isArray(c)){if(f==="-")f=c.length;else{if(n&&!Sc(f))throw new Le("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",a,e,t);Sc(f)&&(f=~~f)}if(u>=l){if(n&&e.op==="add"&&f>c.length)throw new Le("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",a,e,t);const p=O0[e.op].call(e,c,f,t);if(p.test===!1)throw new Le("Test operation failed","TEST_OPERATION_FAILED",a,e,t);return p}}else if(u>=l){const p=cr[e.op].call(e,c,f,t);if(p.test===!1)throw new Le("Test operation failed","TEST_OPERATION_FAILED",a,e,t);return p}if(c=c[f],n&&u<l&&(!c||typeof c!="object"))throw new Le("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",a,e,t)}}}function ur(t,e,n,r=!0,s=!0){if(n&&!Array.isArray(e))throw new Le("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(t=zt(t));const a=new Array(e.length);for(let i=0,o=e.length;i<o;i++)a[i]=Zn(t,e[i],n,!0,s,i),t=a[i].newDocument;return a.newDocument=t,a}function $0(t,e,n){const r=Zn(t,e);if(r.test===!1)throw new Le("Test operation failed","TEST_OPERATION_FAILED",n,e,t);return r.newDocument}function ha(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t))throw new Le("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,n);if(cr[t.op]){if(typeof t.path!="string")throw new Le("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,n);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new Le(\'Operation `path` property must start with "/"\',"OPERATION_PATH_INVALID",e,t,n);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new Le("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new Le("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&Tc(t.value))throw new Le("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,n);if(n){if(t.op=="add"){var s=t.path.split("/").length,a=r.split("/").length;if(s!==a+1&&s!==a)throw new Le("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,n)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==r)throw new Le("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,n)}else if(t.op==="move"||t.op==="copy"){var i={op:"_get",path:t.from,value:void 0},o=hf([i],n);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new Le("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,n)}}}else throw new Le("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,n)}function hf(t,e,n){try{if(!Array.isArray(t))throw new Le("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)ur(zt(e),zt(t),n||!0);else{n=n||ha;for(var r=0;r<t.length;r++)n(t[r],r,e,void 0)}}catch(s){if(s instanceof Le)return s;throw s}}function Jr(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var n=Array.isArray(t),r=Array.isArray(e),s,a,i;if(n&&r){if(a=t.length,a!=e.length)return!1;for(s=a;s--!==0;)if(!Jr(t[s],e[s]))return!1;return!0}if(n!=r)return!1;var o=Object.keys(t);if(a=o.length,a!==Object.keys(e).length)return!1;for(s=a;s--!==0;)if(!e.hasOwnProperty(o[s]))return!1;for(s=a;s--!==0;)if(i=o[s],!Jr(t[i],e[i]))return!1;return!0}return t!==t&&e!==e}function ff(t,e,n,r,s){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var a=Ec(e),i=Ec(t),o=!1,c=i.length-1;c>=0;c--){var u=i[c],l=t[u];if(vc(e,u)&&!(e[u]===void 0&&l!==void 0&&Array.isArray(e)===!1)){var d=e[u];typeof l=="object"&&l!=null&&typeof d=="object"&&d!=null&&Array.isArray(l)===Array.isArray(d)?ff(l,d,n,r+"/"+or(u),s):l!==d&&(s&&n.push({op:"test",path:r+"/"+or(u),value:zt(l)}),n.push({op:"replace",path:r+"/"+or(u),value:zt(d)}))}else Array.isArray(t)===Array.isArray(e)?(s&&n.push({op:"test",path:r+"/"+or(u),value:zt(l)}),n.push({op:"remove",path:r+"/"+or(u)}),o=!0):(s&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:e}))}if(!(!o&&a.length==i.length))for(var c=0;c<a.length;c++){var u=a[c];!vc(t,u)&&e[u]!==void 0&&n.push({op:"add",path:r+"/"+or(u),value:zt(e[u])})}}}function Ic(t,e,n=!1){var r=[];return ff(t,e,r,"",n),r}({...df});var C0={};ge(C0,{LogStreamCallbackHandler:()=>kc,RunLog:()=>Ac,RunLogPatch:()=>dn,isLogStreamHandler:()=>pf});var dn=class{ops;constructor(t){this.ops=t.ops??[]}concat(t){const e=this.ops.concat(t.ops),n=ur({},e);return new Ac({ops:e,state:n[n.length-1].newDocument})}},Ac=class Tl extends dn{state;constructor(e){super(e),this.state=e.state}concat(e){const n=this.ops.concat(e.ops),r=ur(this.state,e.ops);return new Tl({ops:n,state:r[r.length-1].newDocument})}static fromRunLogPatch(e){const n=ur({},e.ops);return new Tl({ops:e.ops,state:n[n.length-1].newDocument})}};const pf=t=>t.name==="log_stream_tracer";async function mf(t,e){if(e==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:n}=t;if(["retriever","llm","prompt"].includes(t.run_type))return n;if(!(Object.keys(n).length===1&&n?.input===""))return n.input}async function gf(t,e){const{outputs:n}=t;return e==="original"||["retriever","llm","prompt"].includes(t.run_type)?n:n!==void 0&&Object.keys(n).length===1&&n?.output!==void 0?n.output:n}function R0(t){return t!==void 0&&t.message!==void 0}var kc=class extends ir{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat="original";rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name="log_stream_tracer";lc_prefer_streaming=!0;constructor(t){super({_awaitHandler:!0,...t}),this.autoClose=t?.autoClose??!0,this.includeNames=t?.includeNames,this.includeTypes=t?.includeTypes,this.includeTags=t?.includeTags,this.excludeNames=t?.excludeNames,this.excludeTypes=t?.excludeTypes,this.excludeTags=t?.excludeTags,this._schemaFormat=t?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Dt.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(t){}_includeRun(t){if(t.id===this.rootId)return!1;const e=t.tags??[];let n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n=n||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(t.run_type)),this.includeTags!==void 0&&(n=n||e.find(r=>this.includeTags?.includes(r))!==void 0),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(t.run_type)),this.excludeTags!==void 0&&(n=n&&e.every(r=>!this.excludeTags?.includes(r))),n}async*tapOutputIterable(t,e){for await(const n of e){if(t!==this.rootId){const r=this.keyMapByRunId[t];r&&await this.writer.write(new dn({ops:[{op:"add",path:`/logs/${r}/streamed_output/-`,value:n}]}))}yield n}}async onRunCreate(t){if(this.rootId===void 0&&(this.rootId=t.id,await this.writer.write(new dn({ops:[{op:"replace",path:"",value:{id:t.id,name:t.name,type:t.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(t))return;this.counterMapByRunName[t.name]===void 0&&(this.counterMapByRunName[t.name]=0),this.counterMapByRunName[t.name]+=1;const e=this.counterMapByRunName[t.name];this.keyMapByRunId[t.id]=e===1?t.name:`${t.name}:${e}`;const n={id:t.id,name:t.name,type:t.run_type,tags:t.tags??[],metadata:t.extra?.metadata??{},start_time:new Date(t.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(n.inputs=await mf(t,this._schemaFormat)),await this.writer.write(new dn({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[t.id]}`,value:n}]}))}async onRunUpdate(t){try{const e=this.keyMapByRunId[t.id];if(e===void 0)return;const n=[];this._schemaFormat==="streaming_events"&&n.push({op:"replace",path:`/logs/${e}/inputs`,value:await mf(t,this._schemaFormat)}),n.push({op:"add",path:`/logs/${e}/final_output`,value:await gf(t,this._schemaFormat)}),t.end_time!==void 0&&n.push({op:"add",path:`/logs/${e}/end_time`,value:new Date(t.end_time).toISOString()});const r=new dn({ops:n});await this.writer.write(r)}finally{if(t.id===this.rootId){const e=new dn({ops:[{op:"replace",path:"/final_output",value:await gf(t,this._schemaFormat)}]});await this.writer.write(e),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(t,e,n){const r=this.keyMapByRunId[t.id];if(r===void 0)return;const s=t.inputs.messages!==void 0;let a;s?R0(n?.chunk)?a=n?.chunk:a=new zn({id:`run-${t.id}`,content:e}):a=e;const i=new dn({ops:[{op:"add",path:`/logs/${r}/streamed_output_str/-`,value:e},{op:"add",path:`/logs/${r}/streamed_output/-`,value:a}]});await this.writer.write(i)}},N0={};ge(N0,{ChatGenerationChunk:()=>Oc,GenerationChunk:()=>lr,RUN_KEY:()=>Kr});const Kr="__run";var lr=class ry{text;generationInfo;constructor(e){this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new ry({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}},Oc=class sy extends lr{message;constructor(e){super(e),this.message=e.message}concat(e){return new sy({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo},message:this.message.concat(e.message)})}};function fa({name:t,serialized:e}){return t!==void 0?t:e?.name!==void 0?e.name:e?.id!==void 0&&Array.isArray(e?.id)?e.id[e.id.length-1]:"Unnamed"}const P0=t=>t.name==="event_stream_tracer";var M0=class extends ir{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;readableStreamClosed=!1;name="event_stream_tracer";lc_prefer_streaming=!0;constructor(t){super({_awaitHandler:!0,...t}),this.autoClose=t?.autoClose??!0,this.includeNames=t?.includeNames,this.includeTypes=t?.includeTypes,this.includeTags=t?.includeTags,this.excludeNames=t?.excludeNames,this.excludeTypes=t?.excludeTypes,this.excludeTags=t?.excludeTags,this.transformStream=new TransformStream({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Dt.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(t){}_includeRun(t){const e=t.tags??[];let n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n=n||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(t.runType)),this.includeTags!==void 0&&(n=n||e.find(r=>this.includeTags?.includes(r))!==void 0),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(t.runType)),this.excludeTags!==void 0&&(n=n&&e.every(r=>!this.excludeTags?.includes(r))),n}async*tapOutputIterable(t,e){const n=await e.next();if(n.done)return;const r=this.runInfoMap.get(t);if(r===void 0){yield n.value;return}function s(i,o){return i==="llm"&&typeof o=="string"?new lr({text:o}):o}let a=this.tappedPromises.get(t);if(a===void 0){let i;a=new Promise(o=>{i=o}),this.tappedPromises.set(t,a);try{const o={event:`on_${r.runType}_stream`,run_id:t,name:r.name,tags:r.tags,metadata:r.metadata,data:{}};await this.send({...o,data:{chunk:s(r.runType,n.value)}},r),yield n.value;for await(const c of e)r.runType!=="tool"&&r.runType!=="retriever"&&await this.send({...o,data:{chunk:s(r.runType,c)}},r),yield c}finally{i?.()}}else{yield n.value;for await(const i of e)yield i}}async send(t,e){this.readableStreamClosed||this._includeRun(e)&&await this.writer.write(t)}async sendEndEvent(t,e){const n=this.tappedPromises.get(t.run_id);n!==void 0?n.then(()=>{this.send(t,e)}):await this.send(t,e)}async onLLMStart(t){const e=fa(t),n=t.inputs.messages!==void 0?"chat_model":"llm",r={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:n,inputs:t.inputs};this.runInfoMap.set(t.id,r);const s=`on_${n}_start`;await this.send({event:s,data:{input:t.inputs},name:e,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},r)}async onLLMNewToken(t,e,n){const r=this.runInfoMap.get(t.id);let s,a;if(r===void 0)throw new Error(`onLLMNewToken: Run ID ${t.id} not found in run map.`);if(this.runInfoMap.size!==1){if(r.runType==="chat_model")a="on_chat_model_stream",n?.chunk===void 0?s=new zn({content:e,id:`run-${t.id}`}):s=n.chunk.message;else if(r.runType==="llm")a="on_llm_stream",n?.chunk===void 0?s=new lr({text:e}):s=n.chunk;else throw new Error(`Unexpected run type ${r.runType}`);await this.send({event:a,data:{chunk:s},run_id:t.id,name:r.name,tags:r.tags,metadata:r.metadata},r)}}async onLLMEnd(t){const e=this.runInfoMap.get(t.id);this.runInfoMap.delete(t.id);let n;if(e===void 0)throw new Error(`onLLMEnd: Run ID ${t.id} not found in run map.`);const r=t.outputs?.generations;let s;if(e.runType==="chat_model"){for(const a of r??[]){if(s!==void 0)break;s=a[0]?.message}n="on_chat_model_end"}else if(e.runType==="llm")s={generations:r?.map(a=>a.map(i=>({text:i.text,generationInfo:i.generationInfo}))),llmOutput:t.outputs?.llmOutput??{}},n="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${e.runType}`);await this.sendEndEvent({event:n,data:{output:s,input:e.inputs},run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata},e)}async onChainStart(t){const e=fa(t),n=t.run_type??"chain",r={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:t.run_type};let s={};t.inputs.input===""&&Object.keys(t.inputs).length===1?(s={},r.inputs={}):t.inputs.input!==void 0?(s.input=t.inputs.input,r.inputs=t.inputs.input):(s.input=t.inputs,r.inputs=t.inputs),this.runInfoMap.set(t.id,r),await this.send({event:`on_${n}_start`,data:s,name:e,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},r)}async onChainEnd(t){const e=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),e===void 0)throw new Error(`onChainEnd: Run ID ${t.id} not found in run map.`);const n=`on_${t.run_type}_end`,r=t.inputs??e.inputs??{},a={output:t.outputs?.output??t.outputs,input:r};r.input&&Object.keys(r).length===1&&(a.input=r.input,e.inputs=r.input),await this.sendEndEvent({event:n,data:a,run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata??{}},e)}async onToolStart(t){const e=fa(t),n={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:"tool",inputs:t.inputs??{}};this.runInfoMap.set(t.id,n),await this.send({event:"on_tool_start",data:{input:t.inputs??{}},name:e,run_id:t.id,tags:t.tags??[],metadata:t.extra?.metadata??{}},n)}async onToolEnd(t){const e=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),e===void 0)throw new Error(`onToolEnd: Run ID ${t.id} not found in run map.`);if(e.inputs===void 0)throw new Error(`onToolEnd: Run ID ${t.id} is a tool call, and is expected to have traced inputs.`);const n=t.outputs?.output===void 0?t.outputs:t.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:n,input:e.inputs},run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata},e)}async onToolError(t){const e=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),e===void 0)throw new Error(`onToolEnd: Run ID ${t.id} not found in run map.`);if(e.inputs===void 0)throw new Error(`onToolEnd: Run ID ${t.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:"on_tool_error",data:{input:e.inputs,error:t.error},run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata},e)}async onRetrieverStart(t){const e=fa(t),r={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:"retriever",inputs:{query:t.inputs.query}};this.runInfoMap.set(t.id,r),await this.send({event:"on_retriever_start",data:{input:{query:t.inputs.query}},name:e,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},r)}async onRetrieverEnd(t){const e=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),e===void 0)throw new Error(`onRetrieverEnd: Run ID ${t.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:t.outputs?.documents??t.outputs,input:e.inputs},run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata},e)}async handleCustomEvent(t,e,n){const r=this.runInfoMap.get(n);if(r===void 0)throw new Error(`handleCustomEvent: Run ID ${n} not found in run map.`);await this.send({event:"on_custom_event",run_id:n,name:t,tags:r.tags,metadata:r.metadata,data:e},r)}async finish(){const t=[...this.tappedPromises.values()];Promise.all(t).finally(()=>{this.writer.close()})}};const L0=Object.prototype.toString,j0=t=>L0.call(t)==="[object Error]",D0=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function z0(t){if(!(t&&j0(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;const{message:n,stack:r}=t;return n==="Load failed"?r===void 0||"__sentry_captured__"in t:n.startsWith("error sending request for url")?!0:D0.has(n)}function F0(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function pa(t,e,{min:n=0,allowInfinity:r=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \\`${t}\\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(e))throw new TypeError(`Expected \\`${t}\\` to be a finite number.`);if(e<n)throw new TypeError(`Expected \\`${t}\\` to be \u2265 ${n}.`)}}var U0=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}};function B0(t,e){const n=Math.max(1,t+1),r=e.randomize?Math.random()+1:1;let s=Math.round(r*e.minTimeout*e.factor**(n-1));return s=Math.min(s,e.maxTimeout),s}function _f(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}async function Z0({error:t,attemptNumber:e,retriesConsumed:n,startTime:r,options:s}){const a=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(a instanceof U0)throw a.originalError;const i=Number.isFinite(s.retries)?Math.max(0,s.retries-n):s.retries,o=s.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:a,attemptNumber:e,retriesLeft:i,retriesConsumed:n});if(await s.onFailedAttempt(c),_f(r,o)<=0)throw a;const u=await s.shouldConsumeRetry(c),l=_f(r,o);if(l<=0||i<=0)throw a;if(a instanceof TypeError&&!z0(a)){if(u)throw a;return s.signal?.throwIfAborted(),!1}if(!await s.shouldRetry(c))throw a;if(!u)return s.signal?.throwIfAborted(),!1;const d=B0(n,s),f=Math.min(d,l);return f>0&&await new Promise((h,p)=>{const m=()=>{clearTimeout(y),s.signal?.removeEventListener("abort",m),p(s.signal.reason)},y=setTimeout(()=>{s.signal?.removeEventListener("abort",m),h()},f);s.unref&&y.unref?.(),s.signal?.addEventListener("abort",m,{once:!0})}),s.signal?.throwIfAborted(),!0}async function $c(t,e={}){if(e={...e},F0(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,pa("factor",e.factor,{min:0,allowInfinity:!1}),pa("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),pa("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),pa("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let n=0,r=0;const s=performance.now();for(;!Number.isFinite(e.retries)||r<=e.retries;){n++;try{e.signal?.throwIfAborted();const a=await t(n);return e.signal?.throwIfAborted(),a}catch(a){await Z0({error:a,attemptNumber:n,retriesConsumed:r,startTime:s,options:e})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}var q0={};ge(q0,{AsyncCaller:()=>Xr});const V0=[400,401,402,403,404,405,406,407,409],H0=t=>{if(typeof t!="object"||t===null)return;if("message"in t&&typeof t.message=="string"&&(t.message.startsWith("Cancel")||t.message.startsWith("AbortError"))||"name"in t&&typeof t.name=="string"&&t.name==="AbortError"||"code"in t&&typeof t.code=="string"&&t.code==="ECONNABORTED")throw t;const e="response"in t&&typeof t.response=="object"&&t.response!==null&&"status"in t.response&&typeof t.response.status=="number"?t.response.status:void 0,n="status"in t&&typeof t.status=="number"?t.status:void 0,r=e??n;if(r&&V0.includes(+r))throw t;if(("error"in t&&typeof t.error=="object"&&t.error!==null&&"code"in t.error&&typeof t.error.code=="string"?t.error.code:void 0)==="insufficient_quota"){const a=new Error("message"in t&&typeof t.message=="string"?t.message:"Insufficient quota");throw a.name="InsufficientQuotaError",a}};var Xr=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(t){this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,this.onFailedAttempt=t.onFailedAttempt??H0;const e="default"in cn?cn.default:cn;this.queue=new e({concurrency:this.maxConcurrency})}async call(t,...e){return this.queue.add(()=>$c(()=>t(...e).catch(n=>{throw n instanceof Error?n:new Error(n)}),{onFailedAttempt:({error:n})=>this.onFailedAttempt?.(n),retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(t,e,...n){if(t.signal){let r;return Promise.race([this.call(e,...n),new Promise((s,a)=>{r=()=>{a(Wr(t.signal))},t.signal?.addEventListener("abort",r)})]).finally(()=>{t.signal&&r&&t.signal.removeEventListener("abort",r)})}return this.call(e,...n)}fetch(...t){return this.call(()=>fetch(...t).then(e=>e.ok?e:Promise.reject(e)))}},yf=class extends ir{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:t,onStart:e,onEnd:n,onError:r}){super({_awaitHandler:!0}),this.config=t,this.argOnStart=e,this.argOnEnd=n,this.argOnError=r}persistRun(t){return Promise.resolve()}async onRunCreate(t){this.rootId||(this.rootId=t.id,this.argOnStart&&await this.argOnStart(t,this.config))}async onRunUpdate(t){t.id===this.rootId&&(t.error?this.argOnError&&await this.argOnError(t,this.config):this.argOnEnd&&await this.argOnEnd(t,this.config))}};function Cc(t){return t?t.lc_runnable:!1}var G0=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(t){this.includeNames=t.includeNames,this.includeTypes=t.includeTypes,this.includeTags=t.includeTags,this.excludeNames=t.excludeNames,this.excludeTypes=t.excludeTypes,this.excludeTags=t.excludeTags}includeEvent(t,e){let n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0;const r=t.tags??[];return this.includeNames!==void 0&&(n=n||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(e)),this.includeTags!==void 0&&(n=n||r.some(s=>this.includeTags?.includes(s))),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(e)),this.excludeTags!==void 0&&(n=n&&r.every(s=>!this.excludeTags?.includes(s))),n}};const W0=t=>btoa(t).replace(/\\+/g,"-").replace(/\\//g,"_").replace(/=+$/,"");function I(t,e,n){function r(o,c){var u;Object.defineProperty(o,"_zod",{value:o._zod??{},enumerable:!1}),(u=o._zod).traits??(u.traits=new Set),o._zod.traits.add(t),e(o,c);for(const l in i.prototype)l in o||Object.defineProperty(o,l,{value:i.prototype[l].bind(o)});o._zod.constr=i,o._zod.def=c}const s=n?.Parent??Object;class a extends s{}Object.defineProperty(a,"name",{value:t});function i(o){var c;const u=n?.Parent?new a:this;r(u,o),(c=u._zod).deferred??(c.deferred=[]);for(const l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:o=>n?.Parent&&o instanceof n.Parent?!0:o?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}class Yr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const wf={};function An(t){return wf}function bf(t){const e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,s])=>e.indexOf(+r)===-1).map(([r,s])=>s)}function J0(t,e){return typeof e=="bigint"?e.toString():e}function Rc(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function Nc(t){return t==null}function Pc(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function K0(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,a=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return a%i/10**s}function ke(t,e,n){Object.defineProperty(t,e,{get(){{const r=n();return t[e]=r,r}},set(r){Object.defineProperty(t,e,{value:r})},configurable:!0})}function Mc(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Qr(t){return JSON.stringify(t)}const vf=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function ma(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const X0=Rc(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function ga(t){if(ma(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!(ma(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}const Y0=new Set(["string","number","symbol"]);function es(t){return t.replace(/[.*+?^${}()|[\\]\\\\]/g,"\\\\$&")}function st(t,e,n){const r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function Q(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function Q0(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const eE={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function tE(t,e){const n={},r=t._zod.def;for(const s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(n[s]=r.shape[s])}return st(t,{...t._zod.def,shape:n,checks:[]})}function nE(t,e){const n={...t._zod.def.shape},r=t._zod.def;for(const s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete n[s]}return st(t,{...t._zod.def,shape:n,checks:[]})}function Ef(t,e){if(!ga(e))throw new Error("Invalid input to extend: expected a plain object");const n={...t._zod.def,get shape(){const r={...t._zod.def.shape,...e};return Mc(this,"shape",r),r},checks:[]};return st(t,n)}function rE(t,e){return st(t,{...t._zod.def,get shape(){const n={...t._zod.def.shape,...e._zod.def.shape};return Mc(this,"shape",n),n},catchall:e._zod.def.catchall,checks:[]})}function Sf(t,e,n){const r=e._zod.def.shape,s={...r};if(n)for(const a in n){if(!(a in r))throw new Error(`Unrecognized key: "${a}"`);n[a]&&(s[a]=t?new t({type:"optional",innerType:r[a]}):r[a])}else for(const a in r)s[a]=t?new t({type:"optional",innerType:r[a]}):r[a];return st(e,{...e._zod.def,shape:s,checks:[]})}function sE(t,e,n){const r=e._zod.def.shape,s={...r};if(n)for(const a in n){if(!(a in s))throw new Error(`Unrecognized key: "${a}"`);n[a]&&(s[a]=new t({type:"nonoptional",innerType:r[a]}))}else for(const a in r)s[a]=new t({type:"nonoptional",innerType:r[a]});return st(e,{...e._zod.def,shape:s,checks:[]})}function ts(t,e=0){for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function qn(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function _a(t){return typeof t=="string"?t:t?.message}function kn(t,e,n){const r={...t,path:t.path??[]};if(!t.message){const s=_a(t.inst?._zod.def?.error?.(t))??_a(e?.error?.(t))??_a(n.customError?.(t))??_a(n.localeError?.(t))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function Lc(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function ns(...t){const[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}const Tf=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,J0,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},xf=I("$ZodError",Tf),ya=I("$ZodError",Tf,{Parent:Error});function aE(t,e=n=>n.message){const n={},r=[];for(const s of t.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:n}}function iE(t,e){const n=e||function(a){return a.message},r={_errors:[]},s=a=>{for(const i of a.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(o=>s({issues:o}));else if(i.code==="invalid_key")s({issues:i.issues});else if(i.code==="invalid_element")s({issues:i.issues});else if(i.path.length===0)r._errors.push(n(i));else{let o=r,c=0;for(;c<i.path.length;){const u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(n(i))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(t),r}function oE(t){const e=[];for(const n of t)typeof n=="number"?e.push(`[${n}]`):typeof n=="symbol"?e.push(`[${JSON.stringify(String(n))}]`):/[^\\w$]/.test(n)?e.push(`[${JSON.stringify(n)}]`):(e.length&&e.push("."),e.push(n));return e.join("")}function cE(t){const e=[],n=[...t.issues].sort((r,s)=>r.path.length-s.path.length);for(const r of n)e.push(`\u2716 ${r.message}`),r.path?.length&&e.push(` \u2192 at ${oE(r.path)}`);return e.join(`\n`)}const If=t=>(e,n,r,s)=>{const a=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:n,issues:[]},a);if(i instanceof Promise)throw new Yr;if(i.issues.length){const o=new(s?.Err??t)(i.issues.map(c=>kn(c,a,An())));throw vf(o,s?.callee),o}return i.value},jc=If(ya),Af=t=>async(e,n,r,s)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let i=e._zod.run({value:n,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const o=new(s?.Err??t)(i.issues.map(c=>kn(c,a,An())));throw vf(o,s?.callee),o}return i.value},kf=Af(ya),Of=t=>(e,n,r)=>{const s=r?{...r,async:!1}:{async:!1},a=e._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new Yr;return a.issues.length?{success:!1,error:new(t??xf)(a.issues.map(i=>kn(i,s,An())))}:{success:!0,data:a.value}},uE=Of(ya),$f=t=>async(e,n,r)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let a=e._zod.run({value:n,issues:[]},s);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new t(a.issues.map(i=>kn(i,s,An())))}:{success:!0,data:a.value}},lE=$f(ya),dE=/^[cC][^\\s-]{8,}$/,hE=/^[0-9a-z]+$/,fE=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,pE=/^[0-9a-vA-V]{20}$/,mE=/^[A-Za-z0-9]{27}$/,gE=/^[a-zA-Z0-9_-]{21}$/,_E=/^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/,yE=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Cf=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,wE=/^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_\'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/,bE="^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$";function vE(){return new RegExp(bE,"u")}const EE=/^(?:(?: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])$/,SE=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,TE=/^((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])\\/([0-9]|[1-2][0-9]|3[0-2])$/,xE=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,IE=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Rf=/^[A-Za-z0-9_-]*$/,AE=/^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/,kE=/^\\+(?:[0-9]){6,14}[0-9]$/,Nf="(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))",OE=new RegExp(`^${Nf}$`);function Pf(t){const e="(?:[01]\\\\d|2[0-3]):[0-5]\\\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\\\d`:`${e}:[0-5]\\\\d\\\\.\\\\d{${t.precision}}`:`${e}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`}function $E(t){return new RegExp(`^${Pf(t)}$`)}function CE(t){const e=Pf({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\\\d{2}:\\\\d{2})");const r=`${e}(?:${n.join("|")})`;return new RegExp(`^${Nf}T(?:${r})$`)}const RE=t=>{const e=t?`[\\\\s\\\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\\\s\\\\S]*";return new RegExp(`^${e}$`)},NE=/^\\d+$/,PE=/^-?\\d+(?:\\.\\d+)?/i,ME=/^[^A-Z]*$/,LE=/^[^a-z]*$/,mt=I("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Mf={number:"number",bigint:"bigint",object:"date"},Lf=I("$ZodCheckLessThan",(t,e)=>{mt.init(t,e);const n=Mf[typeof e.value];t._zod.onattach.push(r=>{const s=r._zod.bag,a=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<a&&(e.inclusive?s.maximum=e.value:s.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),jf=I("$ZodCheckGreaterThan",(t,e)=>{mt.init(t,e);const n=Mf[typeof e.value];t._zod.onattach.push(r=>{const s=r._zod.bag,a=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>a&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),jE=I("$ZodCheckMultipleOf",(t,e)=>{mt.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):K0(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),DE=I("$ZodCheckNumberFormat",(t,e)=>{mt.init(t,e),e.format=e.format||"float64";const n=e.format?.includes("int"),r=n?"int":"number",[s,a]=eE[e.format];t._zod.onattach.push(i=>{const o=i._zod.bag;o.format=e.format,o.minimum=s,o.maximum=a,n&&(o.pattern=NE)}),t._zod.check=i=>{const o=i.value;if(n){if(!Number.isInteger(o)){i.issues.push({expected:r,format:e.format,code:"invalid_type",input:o,inst:t});return}if(!Number.isSafeInteger(o)){o>0?i.issues.push({input:o,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort}):i.issues.push({input:o,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort});return}}o<s&&i.issues.push({origin:"number",input:o,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),o>a&&i.issues.push({origin:"number",input:o,code:"too_big",maximum:a,inst:t})}}),zE=I("$ZodCheckMaxLength",(t,e)=>{var n;mt.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Nc(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{const s=r.value;if(s.length<=e.maximum)return;const i=Lc(s);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),FE=I("$ZodCheckMinLength",(t,e)=>{var n;mt.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Nc(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{const s=r.value;if(s.length>=e.minimum)return;const i=Lc(s);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),UE=I("$ZodCheckLengthEquals",(t,e)=>{var n;mt.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Nc(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=r=>{const s=r.value,a=s.length;if(a===e.length)return;const i=Lc(s),o=a>e.length;r.issues.push({origin:i,...o?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),wa=I("$ZodCheckStringFormat",(t,e)=>{var n,r;mt.init(t,e),t._zod.onattach.push(s=>{const a=s._zod.bag;a.format=e.format,e.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),BE=I("$ZodCheckRegex",(t,e)=>{wa.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),ZE=I("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=ME),wa.init(t,e)}),qE=I("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=LE),wa.init(t,e)}),VE=I("$ZodCheckIncludes",(t,e)=>{mt.init(t,e);const n=es(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(s=>{const a=s._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(r)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),HE=I("$ZodCheckStartsWith",(t,e)=>{mt.init(t,e);const n=new RegExp(`^${es(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),GE=I("$ZodCheckEndsWith",(t,e)=>{mt.init(t,e);const n=new RegExp(`.*${es(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),WE=I("$ZodCheckOverwrite",(t,e)=>{mt.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class JE{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const r=e.split(`\n`).filter(i=>i),s=Math.min(...r.map(i=>i.length-i.trimStart().length)),a=r.map(i=>i.slice(s)).map(i=>" ".repeat(this.indent*2)+i);for(const i of a)this.content.push(i)}compile(){const e=Function,n=this?.args,s=[...(this?.content??[""]).map(a=>` ${a}`)];return new e(...n,s.join(`\n`))}}const KE={major:4,minor:0,patch:0},Re=I("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=KE;const r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(const s of r)for(const a of s._zod.onattach)a(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const s=(a,i,o)=>{let c=ts(a),u;for(const l of i){if(l._zod.def.when){if(!l._zod.def.when(a))continue}else if(c)continue;const d=a.issues.length,f=l._zod.check(a);if(f instanceof Promise&&o?.async===!1)throw new Yr;if(u||f instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await f,a.issues.length!==d&&(c||(c=ts(a,d)))});else{if(a.issues.length===d)continue;c||(c=ts(a,d))}}return u?u.then(()=>a):a};t._zod.run=(a,i)=>{const o=t._zod.parse(a,i);if(o instanceof Promise){if(i.async===!1)throw new Yr;return o.then(c=>s(c,r,i))}return s(o,r,i)}}t["~standard"]={validate:s=>{try{const a=uE(t,s);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return lE(t,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Dc=I("$ZodString",(t,e)=>{Re.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??RE(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),$e=I("$ZodStringFormat",(t,e)=>{wa.init(t,e),Dc.init(t,e)}),XE=I("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=yE),$e.init(t,e)}),YE=I("$ZodUUID",(t,e)=>{if(e.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Cf(r))}else e.pattern??(e.pattern=Cf());$e.init(t,e)}),QE=I("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=wE),$e.init(t,e)}),eS=I("$ZodURL",(t,e)=>{$e.init(t,e),t._zod.check=n=>{try{const r=n.value,s=new URL(r),a=s.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:AE.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),!r.endsWith("/")&&a.endsWith("/")?n.value=a.slice(0,-1):n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),tS=I("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=vE()),$e.init(t,e)}),nS=I("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=gE),$e.init(t,e)}),rS=I("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=dE),$e.init(t,e)}),sS=I("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=hE),$e.init(t,e)}),aS=I("$ZodULID",(t,e)=>{e.pattern??(e.pattern=fE),$e.init(t,e)}),iS=I("$ZodXID",(t,e)=>{e.pattern??(e.pattern=pE),$e.init(t,e)}),oS=I("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=mE),$e.init(t,e)}),cS=I("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=CE(e)),$e.init(t,e)}),uS=I("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=OE),$e.init(t,e)}),lS=I("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=$E(e)),$e.init(t,e)}),dS=I("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=_E),$e.init(t,e)}),hS=I("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=EE),$e.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),fS=I("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=SE),$e.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),pS=I("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=TE),$e.init(t,e)}),mS=I("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=xE),$e.init(t,e),t._zod.check=n=>{const[r,s]=n.value.split("/");try{if(!s)throw new Error;const a=Number(s);if(`${a}`!==s)throw new Error;if(a<0||a>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function Df(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const gS=I("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=IE),$e.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{Df(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function _S(t){if(!Rf.test(t))return!1;const e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Df(n)}const yS=I("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Rf),$e.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{_S(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),wS=I("$ZodE164",(t,e)=>{e.pattern??(e.pattern=kE),$e.init(t,e)});function bS(t,e=null){try{const n=t.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const s=JSON.parse(atob(r));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}const vS=I("$ZodJWT",(t,e)=>{$e.init(t,e),t._zod.check=n=>{bS(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),zf=I("$ZodNumber",(t,e)=>{Re.init(t,e),t._zod.pattern=t._zod.bag.pattern??PE,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}const s=n.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return n;const a=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...a?{received:a}:{}}),n}}),ES=I("$ZodNumber",(t,e)=>{DE.init(t,e),zf.init(t,e)}),Ff=I("$ZodUnknown",(t,e)=>{Re.init(t,e),t._zod.parse=n=>n}),Uf=I("$ZodNever",(t,e)=>{Re.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function Bf(t,e,n){t.issues.length&&e.issues.push(...qn(n,t.issues)),e.value[n]=t.value}const SS=I("$ZodArray",(t,e)=>{Re.init(t,e),t._zod.parse=(n,r)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),n;n.value=Array(s.length);const a=[];for(let i=0;i<s.length;i++){const o=s[i],c=e.element._zod.run({value:o,issues:[]},r);c instanceof Promise?a.push(c.then(u=>Bf(u,n,i))):Bf(c,n,i)}return a.length?Promise.all(a).then(()=>n):n}});function ba(t,e,n){t.issues.length&&e.issues.push(...qn(n,t.issues)),e.value[n]=t.value}function Zf(t,e,n,r){t.issues.length?r[n]===void 0?n in r?e.value[n]=void 0:e.value[n]=t.value:e.issues.push(...qn(n,t.issues)):t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}const TS=I("$ZodObject",(t,e)=>{Re.init(t,e);const n=Rc(()=>{const d=Object.keys(e.shape);for(const h of d)if(!(e.shape[h]instanceof Re))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);const f=Q0(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(f)}});ke(t._zod,"propValues",()=>{const d=e.shape,f={};for(const h in d){const p=d[h]._zod;if(p.values){f[h]??(f[h]=new Set);for(const m of p.values)f[h].add(m)}}return f});const r=d=>{const f=new JE(["shape","payload","ctx"]),h=n.value,p=w=>{const E=Qr(w);return`shape[${E}]._zod.run({ value: input[${E}], issues: [] }, ctx)`};f.write("const input = payload.value;");const m=Object.create(null);let y=0;for(const w of h.keys)m[w]=`key_${y++}`;f.write("const newResult = {}");for(const w of h.keys)if(h.optionalKeys.has(w)){const E=m[w];f.write(`const ${E} = ${p(w)};`);const x=Qr(w);f.write(`\n if (${E}.issues.length) {\n if (input[${x}] === undefined) {\n if (${x} in input) {\n newResult[${x}] = undefined;\n }\n } else {\n payload.issues = payload.issues.concat(\n ${E}.issues.map((iss) => ({\n ...iss,\n path: iss.path ? [${x}, ...iss.path] : [${x}],\n }))\n );\n }\n } else if (${E}.value === undefined) {\n if (${x} in input) newResult[${x}] = undefined;\n } else {\n newResult[${x}] = ${E}.value;\n }\n `)}else{const E=m[w];f.write(`const ${E} = ${p(w)};`),f.write(`\n if (${E}.issues.length) payload.issues = payload.issues.concat(${E}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${Qr(w)}, ...iss.path] : [${Qr(w)}]\n })));`),f.write(`newResult[${Qr(w)}] = ${E}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");const v=f.compile();return(w,E)=>v(d,w,E)};let s;const a=ma,i=!wf.jitless,c=i&&X0.value,u=e.catchall;let l;t._zod.parse=(d,f)=>{l??(l=n.value);const h=d.value;if(!a(h))return d.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),d;const p=[];if(i&&c&&f?.async===!1&&f.jitless!==!0)s||(s=r(e.shape)),d=s(d,f);else{d.value={};const E=l.shape;for(const x of l.keys){const A=E[x],N=A._zod.run({value:h[x],issues:[]},f),j=A._zod.optin==="optional"&&A._zod.optout==="optional";N instanceof Promise?p.push(N.then(b=>j?Zf(b,d,x,h):ba(b,d,x))):j?Zf(N,d,x,h):ba(N,d,x)}}if(!u)return p.length?Promise.all(p).then(()=>d):d;const m=[],y=l.keySet,v=u._zod,w=v.def.type;for(const E of Object.keys(h)){if(y.has(E))continue;if(w==="never"){m.push(E);continue}const x=v.run({value:h[E],issues:[]},f);x instanceof Promise?p.push(x.then(A=>ba(A,d,E))):ba(x,d,E)}return m.length&&d.issues.push({code:"unrecognized_keys",keys:m,input:h,inst:t}),p.length?Promise.all(p).then(()=>d):d}});function qf(t,e,n,r){for(const s of t)if(s.issues.length===0)return e.value=s.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(s=>s.issues.map(a=>kn(a,r,An())))}),e}const Vf=I("$ZodUnion",(t,e)=>{Re.init(t,e),ke(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),ke(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),ke(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),ke(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){const n=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>Pc(r.source)).join("|")})$`)}}),t._zod.parse=(n,r)=>{let s=!1;const a=[];for(const i of e.options){const o=i._zod.run({value:n.value,issues:[]},r);if(o instanceof Promise)a.push(o),s=!0;else{if(o.issues.length===0)return o;a.push(o)}}return s?Promise.all(a).then(i=>qf(i,n,t,r)):qf(a,n,t,r)}}),xS=I("$ZodDiscriminatedUnion",(t,e)=>{Vf.init(t,e);const n=t._zod.parse;ke(t._zod,"propValues",()=>{const s={};for(const a of e.options){const i=a._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(const[o,c]of Object.entries(i)){s[o]||(s[o]=new Set);for(const u of c)s[o].add(u)}}return s});const r=Rc(()=>{const s=e.options,a=new Map;for(const i of s){const o=i._zod.propValues[e.discriminator];if(!o||o.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(const c of o){if(a.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);a.set(c,i)}}return a});t._zod.parse=(s,a)=>{const i=s.value;if(!ma(i))return s.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),s;const o=r.value.get(i?.[e.discriminator]);return o?o._zod.run(s,a):e.unionFallback?n(s,a):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),s)}}),IS=I("$ZodIntersection",(t,e)=>{Re.init(t,e),t._zod.parse=(n,r)=>{const s=n.value,a=e.left._zod.run({value:s,issues:[]},r),i=e.right._zod.run({value:s,issues:[]},r);return a instanceof Promise||i instanceof Promise?Promise.all([a,i]).then(([c,u])=>Hf(n,c,u)):Hf(n,a,i)}});function zc(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(ga(t)&&ga(e)){const n=Object.keys(e),r=Object.keys(t).filter(a=>n.indexOf(a)!==-1),s={...t,...e};for(const a of r){const i=zc(t[a],e[a]);if(!i.valid)return{valid:!1,mergeErrorPath:[a,...i.mergeErrorPath]};s[a]=i.data}return{valid:!0,data:s}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<t.length;r++){const s=t[r],a=e[r],i=zc(s,a);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Hf(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),ts(t))return t;const r=zc(e.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return t.value=r.data,t}const AS=I("$ZodRecord",(t,e)=>{Re.init(t,e),t._zod.parse=(n,r)=>{const s=n.value;if(!ga(s))return n.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),n;const a=[];if(e.keyType._zod.values){const i=e.keyType._zod.values;n.value={};for(const c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){const u=e.valueType._zod.run({value:s[c],issues:[]},r);u instanceof Promise?a.push(u.then(l=>{l.issues.length&&n.issues.push(...qn(c,l.issues)),n.value[c]=l.value})):(u.issues.length&&n.issues.push(...qn(c,u.issues)),n.value[c]=u.value)}let o;for(const c in s)i.has(c)||(o=o??[],o.push(c));o&&o.length>0&&n.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:o})}else{n.value={};for(const i of Reflect.ownKeys(s)){if(i==="__proto__")continue;const o=e.keyType._zod.run({value:i,issues:[]},r);if(o instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(o.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:o.issues.map(u=>kn(u,r,An())),input:i,path:[i],inst:t}),n.value[o.value]=o.value;continue}const c=e.valueType._zod.run({value:s[i],issues:[]},r);c instanceof Promise?a.push(c.then(u=>{u.issues.length&&n.issues.push(...qn(i,u.issues)),n.value[o.value]=u.value})):(c.issues.length&&n.issues.push(...qn(i,c.issues)),n.value[o.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),kS=I("$ZodEnum",(t,e)=>{Re.init(t,e);const n=bf(e.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(r=>Y0.has(typeof r)).map(r=>typeof r=="string"?es(r):r.toString()).join("|")})$`),t._zod.parse=(r,s)=>{const a=r.value;return t._zod.values.has(a)||r.issues.push({code:"invalid_value",values:n,input:a,inst:t}),r}}),OS=I("$ZodLiteral",(t,e)=>{Re.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?es(n):n?n.toString():String(n)).join("|")})$`),t._zod.parse=(n,r)=>{const s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),n}}),$S=I("$ZodTransform",(t,e)=>{Re.init(t,e),t._zod.parse=(n,r)=>{const s=e.transform(n.value,n);if(r.async)return(s instanceof Promise?s:Promise.resolve(s)).then(i=>(n.value=i,n));if(s instanceof Promise)throw new Yr;return n.value=s,n}}),Fc=I("$ZodOptional",(t,e)=>{Re.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ke(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ke(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Pc(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(n,r):n.value===void 0?n:e.innerType._zod.run(n,r)}),CS=I("$ZodNullable",(t,e)=>{Re.init(t,e),ke(t._zod,"optin",()=>e.innerType._zod.optin),ke(t._zod,"optout",()=>e.innerType._zod.optout),ke(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Pc(n.source)}|null)$`):void 0}),ke(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),RS=I("$ZodDefault",(t,e)=>{Re.init(t,e),t._zod.optin="optional",ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=e.defaultValue,n;const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>Gf(a,e)):Gf(s,e)}});function Gf(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const NS=I("$ZodPrefault",(t,e)=>{Re.init(t,e),t._zod.optin="optional",ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),PS=I("$ZodNonOptional",(t,e)=>{Re.init(t,e),ke(t._zod,"values",()=>{const n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>Wf(a,t)):Wf(s,t)}});function Wf(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const MS=I("$ZodCatch",(t,e)=>{Re.init(t,e),t._zod.optin="optional",ke(t._zod,"optout",()=>e.innerType._zod.optout),ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>(n.value=a.value,a.issues.length&&(n.value=e.catchValue({...n,error:{issues:a.issues.map(i=>kn(i,r,An()))},input:n.value}),n.issues=[]),n)):(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(a=>kn(a,r,An()))},input:n.value}),n.issues=[]),n)}}),LS=I("$ZodPipe",(t,e)=>{Re.init(t,e),ke(t._zod,"values",()=>e.in._zod.values),ke(t._zod,"optin",()=>e.in._zod.optin),ke(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(n,r)=>{const s=e.in._zod.run(n,r);return s instanceof Promise?s.then(a=>Jf(a,e,r)):Jf(s,e,r)}});function Jf(t,e,n){return ts(t)?t:e.out._zod.run({value:t.value,issues:t.issues},n)}const jS=I("$ZodReadonly",(t,e)=>{Re.init(t,e),ke(t._zod,"propValues",()=>e.innerType._zod.propValues),ke(t._zod,"values",()=>e.innerType._zod.values),ke(t._zod,"optin",()=>e.innerType._zod.optin),ke(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,r)=>{const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(Kf):Kf(s)}});function Kf(t){return t.value=Object.freeze(t.value),t}const DS=I("$ZodCustom",(t,e)=>{mt.init(t,e),Re.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{const r=n.value,s=e.fn(r);if(s instanceof Promise)return s.then(a=>Xf(a,n,r,t));Xf(s,n,r,t)}});function Xf(t,e,n,r){if(!t){const s={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(s.params=r._zod.def.params),e.issues.push(ns(s))}}class Yf{constructor(){this._map=new Map,this._idmap=new Map}add(e,...n){const r=n[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){const n=e._zod.parent;if(n){const r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function zS(){return new Yf}const Je=zS();function FS(t,e){return new t({type:"string",...Q(e)})}function US(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Q(e)})}function Qf(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Q(e)})}function BS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Q(e)})}function ZS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Q(e)})}function qS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Q(e)})}function VS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Q(e)})}function HS(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Q(e)})}function GS(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Q(e)})}function WS(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Q(e)})}function JS(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Q(e)})}function KS(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Q(e)})}function XS(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Q(e)})}function YS(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Q(e)})}function QS(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Q(e)})}function eT(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Q(e)})}function tT(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Q(e)})}function nT(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Q(e)})}function rT(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Q(e)})}function sT(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Q(e)})}function aT(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Q(e)})}function iT(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Q(e)})}function oT(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Q(e)})}function cT(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Q(e)})}function uT(t,e){return new t({type:"string",format:"date",check:"string_format",...Q(e)})}function lT(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...Q(e)})}function dT(t,e){return new t({type:"string",format:"duration",check:"string_format",...Q(e)})}function hT(t,e){return new t({type:"number",checks:[],...Q(e)})}function fT(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Q(e)})}function ep(t){return new t({type:"unknown"})}function tp(t,e){return new t({type:"never",...Q(e)})}function np(t,e){return new Lf({check:"less_than",...Q(e),value:t,inclusive:!1})}function Uc(t,e){return new Lf({check:"less_than",...Q(e),value:t,inclusive:!0})}function rp(t,e){return new jf({check:"greater_than",...Q(e),value:t,inclusive:!1})}function Bc(t,e){return new jf({check:"greater_than",...Q(e),value:t,inclusive:!0})}function sp(t,e){return new jE({check:"multiple_of",...Q(e),value:t})}function ap(t,e){return new zE({check:"max_length",...Q(e),maximum:t})}function va(t,e){return new FE({check:"min_length",...Q(e),minimum:t})}function ip(t,e){return new UE({check:"length_equals",...Q(e),length:t})}function pT(t,e){return new BE({check:"string_format",format:"regex",...Q(e),pattern:t})}function mT(t){return new ZE({check:"string_format",format:"lowercase",...Q(t)})}function gT(t){return new qE({check:"string_format",format:"uppercase",...Q(t)})}function _T(t,e){return new VE({check:"string_format",format:"includes",...Q(e),includes:t})}function yT(t,e){return new HE({check:"string_format",format:"starts_with",...Q(e),prefix:t})}function wT(t,e){return new GE({check:"string_format",format:"ends_with",...Q(e),suffix:t})}function rs(t){return new WE({check:"overwrite",tx:t})}function bT(t){return rs(e=>e.normalize(t))}function vT(){return rs(t=>t.trim())}function ET(){return rs(t=>t.toLowerCase())}function ST(){return rs(t=>t.toUpperCase())}function TT(t,e,n){return new t({type:"array",element:e,...Q(n)})}function xT(t,e,n){return new t({type:"custom",check:"custom",fn:e,...Q(n)})}class op{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Je,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,n={path:[],schemaPath:[]}){var r;const s=e._zod.def,a={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;const o={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(e,o);const c=e._zod.toJSONSchema?.();if(c)o.schema=c;else{const d={...n,schemaPath:[...n.schemaPath,e],path:n.path},f=e._zod.parent;if(f)o.ref=f,this.process(f,d),this.seen.get(f).isParent=!0;else{const h=o.schema;switch(s.type){case"string":{const p=h;p.type="string";const{minimum:m,maximum:y,format:v,patterns:w,contentEncoding:E}=e._zod.bag;if(typeof m=="number"&&(p.minLength=m),typeof y=="number"&&(p.maxLength=y),v&&(p.format=a[v]??v,p.format===""&&delete p.format),E&&(p.contentEncoding=E),w&&w.size>0){const x=[...w];x.length===1?p.pattern=x[0].source:x.length>1&&(o.schema.allOf=[...x.map(A=>({...this.target==="draft-7"?{type:"string"}:{},pattern:A.source}))])}break}case"number":{const p=h,{minimum:m,maximum:y,format:v,multipleOf:w,exclusiveMaximum:E,exclusiveMinimum:x}=e._zod.bag;typeof v=="string"&&v.includes("int")?p.type="integer":p.type="number",typeof x=="number"&&(p.exclusiveMinimum=x),typeof m=="number"&&(p.minimum=m,typeof x=="number"&&(x>=m?delete p.minimum:delete p.exclusiveMinimum)),typeof E=="number"&&(p.exclusiveMaximum=E),typeof y=="number"&&(p.maximum=y,typeof E=="number"&&(E<=y?delete p.maximum:delete p.exclusiveMaximum)),typeof w=="number"&&(p.multipleOf=w);break}case"boolean":{const p=h;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{h.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const p=h,{minimum:m,maximum:y}=e._zod.bag;typeof m=="number"&&(p.minItems=m),typeof y=="number"&&(p.maxItems=y),p.type="array",p.items=this.process(s.element,{...d,path:[...d.path,"items"]});break}case"object":{const p=h;p.type="object",p.properties={};const m=s.shape;for(const w in m)p.properties[w]=this.process(m[w],{...d,path:[...d.path,"properties",w]});const y=new Set(Object.keys(m)),v=new Set([...y].filter(w=>{const E=s.shape[w]._zod;return this.io==="input"?E.optin===void 0:E.optout===void 0}));v.size>0&&(p.required=Array.from(v)),s.catchall?._zod.def.type==="never"?p.additionalProperties=!1:s.catchall?s.catchall&&(p.additionalProperties=this.process(s.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{const p=h;p.anyOf=s.options.map((m,y)=>this.process(m,{...d,path:[...d.path,"anyOf",y]}));break}case"intersection":{const p=h,m=this.process(s.left,{...d,path:[...d.path,"allOf",0]}),y=this.process(s.right,{...d,path:[...d.path,"allOf",1]}),v=E=>"allOf"in E&&Object.keys(E).length===1,w=[...v(m)?m.allOf:[m],...v(y)?y.allOf:[y]];p.allOf=w;break}case"tuple":{const p=h;p.type="array";const m=s.items.map((w,E)=>this.process(w,{...d,path:[...d.path,"prefixItems",E]}));if(this.target==="draft-2020-12"?p.prefixItems=m:p.items=m,s.rest){const w=this.process(s.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?p.items=w:p.additionalItems=w}s.rest&&(p.items=this.process(s.rest,{...d,path:[...d.path,"items"]}));const{minimum:y,maximum:v}=e._zod.bag;typeof y=="number"&&(p.minItems=y),typeof v=="number"&&(p.maxItems=v);break}case"record":{const p=h;p.type="object",p.propertyNames=this.process(s.keyType,{...d,path:[...d.path,"propertyNames"]}),p.additionalProperties=this.process(s.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const p=h,m=bf(s.entries);m.every(y=>typeof y=="number")&&(p.type="number"),m.every(y=>typeof y=="string")&&(p.type="string"),p.enum=m;break}case"literal":{const p=h,m=[];for(const y of s.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");m.push(Number(y))}else m.push(y);if(m.length!==0)if(m.length===1){const y=m[0];p.type=y===null?"null":typeof y,p.const=y}else m.every(y=>typeof y=="number")&&(p.type="number"),m.every(y=>typeof y=="string")&&(p.type="string"),m.every(y=>typeof y=="boolean")&&(p.type="string"),m.every(y=>y===null)&&(p.type="null"),p.enum=m;break}case"file":{const p=h,m={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:v,mime:w}=e._zod.bag;y!==void 0&&(m.minLength=y),v!==void 0&&(m.maxLength=v),w?w.length===1?(m.contentMediaType=w[0],Object.assign(p,m)):p.anyOf=w.map(E=>({...m,contentMediaType:E})):Object.assign(p,m);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const p=this.process(s.innerType,d);h.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,d),o.ref=s.innerType;break}case"success":{const p=h;p.type="boolean";break}case"default":{this.process(s.innerType,d),o.ref=s.innerType,h.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,d),o.ref=s.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,d),o.ref=s.innerType;let p;try{p=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const p=h,m=e._zod.pattern;if(!m)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=m.source;break}case"pipe":{const p=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(p,d),o.ref=p;break}case"readonly":{this.process(s.innerType,d),o.ref=s.innerType,h.readOnly=!0;break}case"promise":{this.process(s.innerType,d),o.ref=s.innerType;break}case"optional":{this.process(s.innerType,d),o.ref=s.innerType;break}case"lazy":{const p=e._zod.innerType;this.process(p,d),o.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const u=this.metadataRegistry.get(e);return u&&Object.assign(o.schema,u),this.io==="input"&&qe(e)&&(delete o.schema.examples,delete o.schema.default),this.io==="input"&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,this.seen.get(e).schema}emit(e,n){const r={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=l=>{const d=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const m=r.external.registry.get(l[0])?.id,y=r.external.uri??(w=>w);if(m)return{ref:y(m)};const v=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=v,{defId:v,ref:`${y("__shared")}#/${d}/${v}`}}if(l[1]===s)return{ref:"#"};const h=`#/${d}/`,p=l[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:h+p}},i=l=>{if(l[1].schema.$ref)return;const d=l[1],{ref:f,defId:h}=a(l);d.def={...d.schema},h&&(d.defId=h);const p=d.schema;for(const m in p)delete p[m];p.$ref=f};if(r.cycles==="throw")for(const l of this.seen.entries()){const d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>\n\nSet the \\`cycles\\` parameter to \\`"ref"\\` to resolve cyclical schemas with defs.`)}for(const l of this.seen.entries()){const d=l[1];if(e===l[0]){i(l);continue}if(r.external){const h=r.external.registry.get(l[0])?.id;if(e!==l[0]&&h){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&r.reused==="ref"){i(l);continue}}const o=(l,d)=>{const f=this.seen.get(l),h=f.def??f.schema,p={...h};if(f.ref===null)return;const m=f.ref;if(f.ref=null,m){o(m,d);const y=this.seen.get(m).schema;y.$ref&&d.target==="draft-7"?(h.allOf=h.allOf??[],h.allOf.push(y)):(Object.assign(h,y),Object.assign(h,p))}f.isParent||this.override({zodSchema:l,jsonSchema:h,path:f.path??[]})};for(const l of[...this.seen.entries()].reverse())o(l[0],{target:this.target});const c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){const l=r.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=r.external.uri(l)}Object.assign(c,s.def);const u=r.external?.defs??{};for(const l of this.seen.entries()){const d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}r.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}function cp(t,e){if(t instanceof Yf){const r=new op(e),s={};for(const o of t._idmap.entries()){const[c,u]=o;r.process(u)}const a={},i={registry:t,uri:e?.uri,defs:s};for(const o of t._idmap.entries()){const[c,u]=o;a[c]=r.emit(u,{...e,external:i})}if(Object.keys(s).length>0){const o=r.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[o]:s}}return{schemas:a}}const n=new op(e);return n.process(t),n.emit(t,e)}function qe(t,e){const n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);const s=t._zod.def;switch(s.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return qe(s.element,n);case"object":{for(const a in s.shape)if(qe(s.shape[a],n))return!0;return!1}case"union":{for(const a of s.options)if(qe(a,n))return!0;return!1}case"intersection":return qe(s.left,n)||qe(s.right,n);case"tuple":{for(const a of s.items)if(qe(a,n))return!0;return!!(s.rest&&qe(s.rest,n))}case"record":return qe(s.keyType,n)||qe(s.valueType,n);case"map":return qe(s.keyType,n)||qe(s.valueType,n);case"set":return qe(s.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return qe(s.innerType,n);case"lazy":return qe(s.getter(),n);case"default":return qe(s.innerType,n);case"prefault":return qe(s.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return qe(s.in,n)||qe(s.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${s.type}`)}function Ne(t){if(typeof t!="object"||t===null)return!1;const e=t;if(!("_zod"in e))return!1;const n=e._zod;return typeof n=="object"&&n!==null&&"def"in n}function Ve(t){if(typeof t!="object"||t===null)return!1;const e=t;if(!("_def"in e)||"_zod"in e)return!1;const n=e._def;return typeof n=="object"&&n!=null&&"typeName"in n}function IT(t){return Ne(t)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),Ve(t)}function dr(t){return!t||typeof t!="object"||Array.isArray(t)?!1:!!(Ne(t)||Ve(t))}function up(t){return typeof t=="object"&&t!==null&&"_def"in t&&typeof t._def=="object"&&t._def!==null&&"typeName"in t._def&&t._def.typeName==="ZodLiteral"}function lp(t){return Ne(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="literal":!1}function AT(t){return!!(up(t)||lp(t))}async function dp(t,e){if(Ne(t))try{return{success:!0,data:await kf(t,e)}}catch(n){return{success:!1,error:n}}if(Ve(t))return await t.safeParseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function Ea(t,e){if(Ne(t))return await kf(t,e);if(Ve(t))return await t.parseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function kT(t,e){if(Ne(t))try{return{success:!0,data:jc(t,e)}}catch(n){return{success:!1,error:n}}if(Ve(t))return t.safeParse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function OT(t,e){if(Ne(t))return jc(t,e);if(Ve(t))return t.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Zc(t){if(Ne(t))return Je.get(t)?.description;if(Ve(t)||"description"in t&&typeof t.description=="string")return t.description}function $T(t){if(!dr(t))return!1;if(Ve(t)){const e=t._def;if(e.typeName==="ZodObject"){const n=t;return!n.shape||Object.keys(n.shape).length===0}if(e.typeName==="ZodRecord")return!0}if(Ne(t)){const e=t._zod.def;if(e.type==="object"){const n=t;return!n.shape||Object.keys(n.shape).length===0}if(e.type==="record")return!0}return typeof t=="object"&&t!==null&&!("shape"in t)}function qc(t){return dr(t)?Ve(t)?t._def.typeName==="ZodString":Ne(t)?t._zod.def.type==="string":!1:!1}function Vc(t){return typeof t=="object"&&t!==null&&"_def"in t&&typeof t._def=="object"&&t._def!==null&&"typeName"in t._def&&t._def.typeName==="ZodObject"}function Yt(t){return Ne(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="object":!1}function Sa(t){return Ne(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="array":!1}function hp(t){return Ne(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="optional":!1}function fp(t){return Ne(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="nullable":!1}function CT(t){return!!(Vc(t)||Yt(t))}function Hc(t){if(Ve(t))return t.shape;if(Ne(t))return t._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function RT(t,e){if(Ve(t))return t.extend(e);if(Ne(t))return Ef(t,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function NT(t){if(Ve(t))return t.partial();if(Ne(t))return Sf(Fc,t,void 0);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Ta(t,e=!1){if(Ve(t))return t.strict();if(Yt(t)){const n=t._zod.def.shape;if(e)for(const[a,i]of Object.entries(t._zod.def.shape)){if(Yt(i)){const c=Ta(i,e);n[a]=c}else if(Sa(i)){let c=i._zod.def.element;Yt(c)&&(c=Ta(c,e)),n[a]=st(i,{...i._zod.def,element:c})}else n[a]=i;const o=Je.get(i);o&&Je.add(n[a],o)}const r=st(t,{...t._zod.def,shape:n,catchall:tp(Uf)}),s=Je.get(t);return s&&Je.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Gc(t,e=!1){if(Vc(t))return t.passthrough();if(Yt(t)){const n=t._zod.def.shape;if(e)for(const[a,i]of Object.entries(t._zod.def.shape)){if(Yt(i)){const c=Gc(i,e);n[a]=c}else if(Sa(i)){let c=i._zod.def.element;Yt(c)&&(c=Gc(c,e)),n[a]=st(i,{...i._zod.def,element:c})}else n[a]=i;const o=Je.get(i);o&&Je.add(n[a],o)}const r=st(t,{...t._zod.def,shape:n,catchall:ep(Ff)}),s=Je.get(t);return s&&Je.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function PT(t){if(Ve(t))try{const e=t.parse(void 0);return()=>e}catch{return}if(Ne(t))try{const e=jc(t,void 0);return()=>e}catch{return}}function MT(t){return Ve(t)&&"typeName"in t._def&&t._def.typeName==="ZodEffects"}function LT(t){return Ne(t)&&t._zod.def.type==="pipe"}function Vn(t,e,n){const r=n.get(t);if(r!==void 0)return r;if(Ve(t))return MT(t)?Vn(t._def.schema,e,n):t;if(Ne(t)){let s=t;if(LT(t)&&(s=Vn(t._zod.def.in,e,n)),e){if(Yt(s)){const i={};for(const[o,c]of Object.entries(s._zod.def.shape))i[o]=Vn(c,e,n);s=st(s,{...s._zod.def,shape:i})}else if(Sa(s)){const i=Vn(s._zod.def.element,e,n);s=st(s,{...s._zod.def,element:i})}else if(hp(s)){const i=Vn(s._zod.def.innerType,e,n);s=st(s,{...s._zod.def,innerType:i})}else if(fp(s)){const i=Vn(s._zod.def.innerType,e,n);s=st(s,{...s._zod.def,innerType:i})}}const a=Je.get(t);return a&&Je.add(s,a),n.set(t,s),s}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function pp(t,e=!1){return Vn(t,e,new WeakMap)}function jT(t,e){if(Ve(t)){const n=Hc(t),r={};for(const[s,a]of Object.entries(n))e(s,a)?r[s]=a.optional():r[s]=a;return t.extend(r)}if(Ne(t)){const n=Hc(t),r={...t._zod.def.shape};for(const[i,o]of Object.entries(n))e(i,o)&&(r[i]=new Fc({type:"optional",innerType:o}));const s=st(t,{...t._zod.def,shape:r}),a=Je.get(t);return a&&Je.add(s,a),s}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function mp(t){return t instanceof Error&&(t.constructor.name==="ZodError"||t.constructor.name==="$ZodError")}function Wc(t){return t.replace(/[^a-zA-Z-_0-9]/g,"_")}const DT=["*","_","`"];function zT(t){let e="";for(const[n,r]of Object.entries(t))e+=` classDef ${n} ${r};\n`;return e}function FT(t,e,n){const{firstNode:r,lastNode:s,nodeColors:a,withStyles:i=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=n??{};let u=i?`%%{init: {\'flowchart\': {\'curve\': \'${o}\'}}}%%\ngraph TD;\n`:`graph TD;\n`;if(i){const p="default",m={[p]:"{0}({1})"};r!==void 0&&(m[r]="{0}([{1}]):::first"),s!==void 0&&(m[s]="{0}([{1}]):::last");for(const[y,v]of Object.entries(t)){const w=v.name.split(":").pop()??"";let x=DT.some(N=>w.startsWith(N)&&w.endsWith(N))?`<p>${w}</p>`:w;Object.keys(v.metadata??{}).length&&(x+=`<hr/><small><em>${Object.entries(v.metadata??{}).map(([N,j])=>`${N} = ${j}`).join(`\n`)}</em></small>`);const A=(m[y]??m[p]).replace("{0}",Wc(y)).replace("{1}",x);u+=` ${A}\n`}}const l={};for(const p of e){const m=p.source.split(":"),y=p.target.split(":"),v=m.filter((w,E)=>w===y[E]).join(":");l[v]||(l[v]=[]),l[v].push(p)}const d=new Set;function f(p){return[...p].sort((m,y)=>m.split(":").length-y.split(":").length)}function h(p,m){const y=p.length===1&&p[0].source===p[0].target;if(m&&!y){const w=m.split(":").pop();if(d.has(m))throw new Error(`Found duplicate subgraph \'${w}\' at \'${m} -- this likely means that you\'re reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(m),u+=` subgraph ${w}\n`}const v=f(Object.keys(l).filter(w=>w.startsWith(`${m}:`)&&w!==m&&w.split(":").length===m.split(":").length+1));for(const w of v)h(l[w],w);for(const w of p){const{source:E,target:x,data:A,conditional:N}=w;let j="";if(A!==void 0){let b=A;const oe=b.split(" ");oe.length>c&&(b=Array.from({length:Math.ceil(oe.length/c)},(ue,X)=>oe.slice(X*c,(X+1)*c).join(" ")).join("&nbsp;<br>&nbsp;")),j=N?` -. &nbsp;${b}&nbsp; .-> `:` -- &nbsp;${b}&nbsp; --> `}else j=N?" -.-> ":" --> ";u+=` ${Wc(E)}${j}${Wc(x)};\n`}m&&!y&&(u+=` end\n`)}h(l[""]??[],"");for(const p in l)!p.includes(":")&&p!==""&&h(l[p],p);return i&&(u+=zT(a??{})),u}async function UT(t,e){let n=e?.backgroundColor??"white";const r=e?.imageType??"png",s=W0(t);n!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(n)||(n=`!${n}`));const a=`https://mermaid.ink/img/${s}?bgColor=${n}&type=${r}`,i=await fetch(a);if(!i.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join(`\n`));return await i.blob()}const BT=Symbol("Let zodToJsonSchema decide on which parser to use"),ZT={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},qT=t=>({...ZT,...t}),VT=t=>{const e=qT(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}},gp=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")};function bt(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?gp(e,t.currentPath):e.join("/")}}function _p(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function xe(t,e,n,r,s){t[e]=n,_p(t,e,r,s)}var ve;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{const a={};for(const i of s)a[i]=i;return a},t.getValidEnumValues=s=>{const a=t.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(const o of a)i[o]=s[o];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(a){return s[a]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const a=[];for(const i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},t.find=(s,a)=>{for(const i of s)if(a(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,a=" | "){return s.map(i=>typeof i=="string"?`\'${i}\'`:i).join(a)}t.joinValues=r,t.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(ve||(ve={}));var yp;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(yp||(yp={}));const V=ve.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),On=t=>{switch(typeof t){case"undefined":return V.undefined;case"string":return V.string;case"number":return Number.isNaN(t)?V.nan:V.number;case"boolean":return V.boolean;case"function":return V.function;case"bigint":return V.bigint;case"symbol":return V.symbol;case"object":return Array.isArray(t)?V.array:t===null?V.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?V.promise:typeof Map<"u"&&t instanceof Map?V.map:typeof Set<"u"&&t instanceof Set?V.set:typeof Date<"u"&&t instanceof Date?V.date:V.object;default:return V.unknown}},$=ve.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class hn extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=e||function(a){return a.message},r={_errors:[]},s=a=>{for(const i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let o=r,c=0;for(;c<i.path.length;){const u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(n(i))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),r}static assert(e){if(!(e instanceof hn))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ve.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},r=[];for(const s of this.issues)if(s.path.length>0){const a=s.path[0];n[a]=n[a]||[],n[a].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}hn.create=t=>new hn(t);const Jc=(t,e)=>{let n;switch(t.code){case $.invalid_type:t.received===V.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case $.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ve.jsonStringifyReplacer)}`;break;case $.unrecognized_keys:n=`Unrecognized key(s) in object: ${ve.joinValues(t.keys,", ")}`;break;case $.invalid_union:n="Invalid input";break;case $.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ve.joinValues(t.options)}`;break;case $.invalid_enum_value:n=`Invalid enum value. Expected ${ve.joinValues(t.options)}, received \'${t.received}\'`;break;case $.invalid_arguments:n="Invalid function arguments";break;case $.invalid_return_type:n="Invalid function return type";break;case $.invalid_date:n="Invalid date";break;case $.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:ve.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case $.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case $.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case $.custom:n="Invalid input";break;case $.invalid_intersection_types:n="Intersection results could not be merged";break;case $.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case $.not_finite:n="Number must be finite";break;default:n=e.defaultError,ve.assertNever(t)}return{message:n}};let HT=Jc;function GT(){return HT}const WT=t=>{const{data:e,path:n,errorMaps:r,issueData:s}=t,a=[...n,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="";const c=r.filter(u=>!!u).slice().reverse();for(const u of c)o=u(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}};function F(t,e){const n=GT(),r=WT({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Jc?void 0:Jc].filter(s=>!!s)});t.common.issues.push(r)}class vt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const r=[];for(const s of n){if(s.status==="aborted")return he;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){const r=[];for(const s of n){const a=await s.key,i=await s.value;r.push({key:a,value:i})}return vt.mergeObjectSync(e,r)}static mergeObjectSync(e,n){const r={};for(const s of n){const{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return he;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[a.value]=i.value)}return{status:e.value,value:r}}}const he=Object.freeze({status:"aborted"}),ss=t=>({status:"dirty",value:t}),$t=t=>({status:"valid",value:t}),wp=t=>t.status==="aborted",bp=t=>t.status==="dirty",hr=t=>t.status==="valid",xa=t=>typeof Promise<"u"&&t instanceof Promise;var G;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(G||(G={}));class $n{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const vp=(t,e)=>{if(hr(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new hn(t.common.issues);return this._error=n,this._error}}};function _e(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,o)=>{const{message:c}=t;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??r??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??n??o.defaultError}},description:s}}let be=class{get description(){return this._def.description}_getType(e){return On(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:On(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new vt,ctx:{common:e.parent.common,data:e.data,parsedType:On(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(xa(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){const r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:On(e)},s=this._parseSync({data:e,path:r.path,parent:r});return vp(r,s)}"~validate"(e){const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:On(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:n});return hr(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>hr(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){const r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){const r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:On(e)},s=this._parse({data:e,path:r.path,parent:r}),a=await(xa(s)?s:Promise.resolve(s));return vp(r,a)}refine(e,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,a)=>{const i=e(s),o=()=>a.addIssue({code:$.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new mr({schema:this,typeName:C.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Rn.create(this,this._def)}nullable(){return gr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return fr.create(this)}promise(){return Oa.create(this,this._def)}or(e){return Aa.create([this,e],this._def)}and(e){return ka.create(this,e,this._def)}transform(e){return new mr({..._e(this._def),schema:this,typeName:C.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new tu({..._e(this._def),innerType:this,defaultValue:n,typeName:C.ZodDefault})}brand(){return new _x({typeName:C.ZodBranded,type:this,..._e(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new nu({..._e(this._def),innerType:this,catchValue:n,typeName:C.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return ru.create(this,e)}readonly(){return su.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const JT=/^c[^\\s-]{8,}$/i,KT=/^[0-9a-z]+$/,XT=/^[0-9A-HJKMNP-TV-Z]{26}$/i,YT=/^[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,QT=/^[a-z0-9_-]{21}$/i,ex=/^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/,tx=/^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/,nx=/^(?!\\.)(?!.*\\.\\.)([A-Z0-9_\'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i,rx="^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$";let Kc;const sx=/^(?:(?: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])$/,ax=/^(?:(?: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])$/,ix=/^(([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]))$/,ox=/^(([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])$/,cx=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ux=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ep="((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))",lx=new RegExp(`^${Ep}$`);function Sp(t){let e="[0-5]\\\\d";t.precision?e=`${e}\\\\.\\\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\\\.\\\\d+)?`);const n=t.precision?"+":"?";return`([01]\\\\d|2[0-3]):[0-5]\\\\d(:${e})${n}`}function dx(t){return new RegExp(`^${Sp(t)}$`)}function hx(t){let e=`${Ep}T${Sp(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\\\d{2}:?\\\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function fx(t,e){return!!((e==="v4"||!e)&&sx.test(t)||(e==="v6"||!e)&&ix.test(t))}function px(t,e){if(!ex.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function mx(t,e){return!!((e==="v4"||!e)&&ax.test(t)||(e==="v6"||!e)&&ox.test(t))}let Xc=class $s extends be{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==V.string){const a=this._getOrReturnCtx(e);return F(a,{code:$.invalid_type,expected:V.string,received:a.parsedType}),he}const r=new vt;let s;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),F(s,{code:$.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),F(s,{code:$.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="length"){const i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(s=this._getOrReturnCtx(e,s),i?F(s,{code:$.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&F(s,{code:$.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),r.dirty())}else if(a.kind==="email")nx.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"email",code:$.invalid_string,message:a.message}),r.dirty());else if(a.kind==="emoji")Kc||(Kc=new RegExp(rx,"u")),Kc.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"emoji",code:$.invalid_string,message:a.message}),r.dirty());else if(a.kind==="uuid")YT.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"uuid",code:$.invalid_string,message:a.message}),r.dirty());else if(a.kind==="nanoid")QT.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"nanoid",code:$.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid")JT.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"cuid",code:$.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid2")KT.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"cuid2",code:$.invalid_string,message:a.message}),r.dirty());else if(a.kind==="ulid")XT.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"ulid",code:$.invalid_string,message:a.message}),r.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),F(s,{validation:"url",code:$.invalid_string,message:a.message}),r.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"regex",code:$.invalid_string,message:a.message}),r.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),F(s,{code:$.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),r.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),F(s,{code:$.invalid_string,validation:{startsWith:a.value},message:a.message}),r.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),F(s,{code:$.invalid_string,validation:{endsWith:a.value},message:a.message}),r.dirty()):a.kind==="datetime"?hx(a).test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{code:$.invalid_string,validation:"datetime",message:a.message}),r.dirty()):a.kind==="date"?lx.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{code:$.invalid_string,validation:"date",message:a.message}),r.dirty()):a.kind==="time"?dx(a).test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{code:$.invalid_string,validation:"time",message:a.message}),r.dirty()):a.kind==="duration"?tx.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"duration",code:$.invalid_string,message:a.message}),r.dirty()):a.kind==="ip"?fx(e.data,a.version)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"ip",code:$.invalid_string,message:a.message}),r.dirty()):a.kind==="jwt"?px(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"jwt",code:$.invalid_string,message:a.message}),r.dirty()):a.kind==="cidr"?mx(e.data,a.version)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"cidr",code:$.invalid_string,message:a.message}),r.dirty()):a.kind==="base64"?cx.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"base64",code:$.invalid_string,message:a.message}),r.dirty()):a.kind==="base64url"?ux.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"base64url",code:$.invalid_string,message:a.message}),r.dirty()):ve.assertNever(a);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:$.invalid_string,...G.errToObj(r)})}_addCheck(e){return new $s({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...G.errToObj(e)})}url(e){return this._addCheck({kind:"url",...G.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...G.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...G.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...G.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...G.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...G.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...G.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...G.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...G.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...G.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...G.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...G.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...G.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...G.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...G.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...G.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...G.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...G.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...G.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...G.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...G.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...G.errToObj(n)})}nonempty(e){return this.min(1,G.errToObj(e))}trim(){return new $s({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new $s({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new $s({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Xc.create=t=>new Xc({checks:[],typeName:C.ZodString,coerce:t?.coerce??!1,..._e(t)});function gx(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,a=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return a%i/10**s}let Tp=class xl extends be{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==V.number){const a=this._getOrReturnCtx(e);return F(a,{code:$.invalid_type,expected:V.number,received:a.parsedType}),he}let r;const s=new vt;for(const a of this._def.checks)a.kind==="int"?ve.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),F(r,{code:$.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),F(r,{code:$.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),F(r,{code:$.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?gx(e.data,a.value)!==0&&(r=this._getOrReturnCtx(e,r),F(r,{code:$.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),F(r,{code:$.not_finite,message:a.message}),s.dirty()):ve.assertNever(a);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,G.toString(n))}gt(e,n){return this.setLimit("min",e,!1,G.toString(n))}lte(e,n){return this.setLimit("max",e,!0,G.toString(n))}lt(e,n){return this.setLimit("max",e,!1,G.toString(n))}setLimit(e,n,r,s){return new xl({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:G.toString(s)}]})}_addCheck(e){return new xl({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:G.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:G.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:G.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:G.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:G.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:G.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ve.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};Tp.create=t=>new Tp({checks:[],typeName:C.ZodNumber,coerce:t?.coerce||!1,..._e(t)});class as extends be{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==V.bigint)return this._getInvalidInput(e);let r;const s=new vt;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),F(r,{code:$.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),F(r,{code:$.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),F(r,{code:$.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):ve.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return F(n,{code:$.invalid_type,expected:V.bigint,received:n.parsedType}),he}gte(e,n){return this.setLimit("min",e,!0,G.toString(n))}gt(e,n){return this.setLimit("min",e,!1,G.toString(n))}lte(e,n){return this.setLimit("max",e,!0,G.toString(n))}lt(e,n){return this.setLimit("max",e,!1,G.toString(n))}setLimit(e,n,r,s){return new as({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:G.toString(s)}]})}_addCheck(e){return new as({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:G.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:G.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}as.create=t=>new as({checks:[],typeName:C.ZodBigInt,coerce:t?.coerce??!1,..._e(t)});class xp extends be{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==V.boolean){const r=this._getOrReturnCtx(e);return F(r,{code:$.invalid_type,expected:V.boolean,received:r.parsedType}),he}return $t(e.data)}}xp.create=t=>new xp({typeName:C.ZodBoolean,coerce:t?.coerce||!1,..._e(t)});class Ia extends be{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==V.date){const a=this._getOrReturnCtx(e);return F(a,{code:$.invalid_type,expected:V.date,received:a.parsedType}),he}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return F(a,{code:$.invalid_date}),he}const r=new vt;let s;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),F(s,{code:$.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),r.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),F(s,{code:$.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),r.dirty()):ve.assertNever(a);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Ia({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:G.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:G.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}Ia.create=t=>new Ia({checks:[],coerce:t?.coerce||!1,typeName:C.ZodDate,..._e(t)});class Ip extends be{_parse(e){if(this._getType(e)!==V.symbol){const r=this._getOrReturnCtx(e);return F(r,{code:$.invalid_type,expected:V.symbol,received:r.parsedType}),he}return $t(e.data)}}Ip.create=t=>new Ip({typeName:C.ZodSymbol,..._e(t)});class Ap extends be{_parse(e){if(this._getType(e)!==V.undefined){const r=this._getOrReturnCtx(e);return F(r,{code:$.invalid_type,expected:V.undefined,received:r.parsedType}),he}return $t(e.data)}}Ap.create=t=>new Ap({typeName:C.ZodUndefined,..._e(t)});class kp extends be{_parse(e){if(this._getType(e)!==V.null){const r=this._getOrReturnCtx(e);return F(r,{code:$.invalid_type,expected:V.null,received:r.parsedType}),he}return $t(e.data)}}kp.create=t=>new kp({typeName:C.ZodNull,..._e(t)});class Yc extends be{constructor(){super(...arguments),this._any=!0}_parse(e){return $t(e.data)}}Yc.create=t=>new Yc({typeName:C.ZodAny,..._e(t)});let Op=class extends be{constructor(){super(...arguments),this._unknown=!0}_parse(e){return $t(e.data)}};Op.create=t=>new Op({typeName:C.ZodUnknown,..._e(t)});let Cn=class extends be{_parse(e){const n=this._getOrReturnCtx(e);return F(n,{code:$.invalid_type,expected:V.never,received:n.parsedType}),he}};Cn.create=t=>new Cn({typeName:C.ZodNever,..._e(t)});class $p extends be{_parse(e){if(this._getType(e)!==V.undefined){const r=this._getOrReturnCtx(e);return F(r,{code:$.invalid_type,expected:V.void,received:r.parsedType}),he}return $t(e.data)}}$p.create=t=>new $p({typeName:C.ZodVoid,..._e(t)});let fr=class Ri extends be{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==V.array)return F(n,{code:$.invalid_type,expected:V.array,received:n.parsedType}),he;if(s.exactLength!==null){const i=n.data.length>s.exactLength.value,o=n.data.length<s.exactLength.value;(i||o)&&(F(n,{code:i?$.too_big:$.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(F(n,{code:$.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(F(n,{code:$.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,o)=>s.type._parseAsync(new $n(n,i,n.path,o)))).then(i=>vt.mergeArray(r,i));const a=[...n.data].map((i,o)=>s.type._parseSync(new $n(n,i,n.path,o)));return vt.mergeArray(r,a)}get element(){return this._def.type}min(e,n){return new Ri({...this._def,minLength:{value:e,message:G.toString(n)}})}max(e,n){return new Ri({...this._def,maxLength:{value:e,message:G.toString(n)}})}length(e,n){return new Ri({...this._def,exactLength:{value:e,message:G.toString(n)}})}nonempty(e){return this.min(1,e)}};fr.create=(t,e)=>new fr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:C.ZodArray,..._e(e)});function pr(t){if(t instanceof fn){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=Rn.create(pr(r))}return new fn({...t._def,shape:()=>e})}else return t instanceof fr?new fr({...t._def,type:pr(t.element)}):t instanceof Rn?Rn.create(pr(t.unwrap())):t instanceof gr?gr.create(pr(t.unwrap())):t instanceof Hn?Hn.create(t.items.map(e=>pr(e))):t}let fn=class Wt extends be{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=ve.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==V.object){const u=this._getOrReturnCtx(e);return F(u,{code:$.invalid_type,expected:V.object,received:u.parsedType}),he}const{status:r,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof Cn&&this._def.unknownKeys==="strip"))for(const u in s.data)i.includes(u)||o.push(u);const c=[];for(const u of i){const l=a[u],d=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new $n(s,d,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof Cn){const u=this._def.unknownKeys;if(u==="passthrough")for(const l of o)c.push({key:{status:"valid",value:l},value:{status:"valid",value:s.data[l]}});else if(u==="strict")o.length>0&&(F(s,{code:$.unrecognized_keys,keys:o}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const l of o){const d=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new $n(s,d,s.path,l)),alwaysSet:l in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const u=[];for(const l of c){const d=await l.key,f=await l.value;u.push({key:d,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>vt.mergeObjectSync(r,u)):vt.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return G.errToObj,new Wt({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{const s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:G.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new Wt({...this._def,unknownKeys:"strip"})}passthrough(){return new Wt({...this._def,unknownKeys:"passthrough"})}extend(e){return new Wt({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Wt({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:C.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new Wt({...this._def,catchall:e})}pick(e){const n={};for(const r of ve.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new Wt({...this._def,shape:()=>n})}omit(e){const n={};for(const r of ve.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new Wt({...this._def,shape:()=>n})}deepPartial(){return pr(this)}partial(e){const n={};for(const r of ve.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new Wt({...this._def,shape:()=>n})}required(e){const n={};for(const r of ve.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let a=this.shape[r];for(;a instanceof Rn;)a=a._def.innerType;n[r]=a}return new Wt({...this._def,shape:()=>n})}keyof(){return Pp(ve.objectKeys(this.shape))}};fn.create=(t,e)=>new fn({shape:()=>t,unknownKeys:"strip",catchall:Cn.create(),typeName:C.ZodObject,..._e(e)}),fn.strictCreate=(t,e)=>new fn({shape:()=>t,unknownKeys:"strict",catchall:Cn.create(),typeName:C.ZodObject,..._e(e)}),fn.lazycreate=(t,e)=>new fn({shape:t,unknownKeys:"strip",catchall:Cn.create(),typeName:C.ZodObject,..._e(e)});let Aa=class extends be{_parse(e){const{ctx:n}=this._processInputParams(e),r=this._def.options;function s(a){for(const o of a)if(o.result.status==="valid")return o.result;for(const o of a)if(o.result.status==="dirty")return n.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(o=>new hn(o.ctx.common.issues));return F(n,{code:$.invalid_union,unionErrors:i}),he}if(n.common.async)return Promise.all(r.map(async a=>{const i={...n,common:{...n.common,issues:[]},parent:null};return{result:await a._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(s);{let a;const i=[];for(const c of r){const u={...n,common:{...n.common,issues:[]},parent:null},l=c._parseSync({data:n.data,path:n.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!a&&(a={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(a)return n.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(c=>new hn(c));return F(n,{code:$.invalid_union,unionErrors:o}),he}}get options(){return this._def.options}};Aa.create=(t,e)=>new Aa({options:t,typeName:C.ZodUnion,..._e(e)});function Qc(t,e){const n=On(t),r=On(e);if(t===e)return{valid:!0,data:t};if(n===V.object&&r===V.object){const s=ve.objectKeys(e),a=ve.objectKeys(t).filter(o=>s.indexOf(o)!==-1),i={...t,...e};for(const o of a){const c=Qc(t[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(n===V.array&&r===V.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let a=0;a<t.length;a++){const i=t[a],o=e[a],c=Qc(i,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===V.date&&r===V.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}let ka=class extends be{_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=(a,i)=>{if(wp(a)||wp(i))return he;const o=Qc(a.value,i.value);return o.valid?((bp(a)||bp(i))&&n.dirty(),{status:n.value,value:o.data}):(F(r,{code:$.invalid_intersection_types}),he)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([a,i])=>s(a,i)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};ka.create=(t,e,n)=>new ka({left:t,right:e,typeName:C.ZodIntersection,..._e(n)});class Hn extends be{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==V.array)return F(r,{code:$.invalid_type,expected:V.array,received:r.parsedType}),he;if(r.data.length<this._def.items.length)return F(r,{code:$.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),he;!this._def.rest&&r.data.length>this._def.items.length&&(F(r,{code:$.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const a=[...r.data].map((i,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new $n(r,i,r.path,o)):null}).filter(i=>!!i);return r.common.async?Promise.all(a).then(i=>vt.mergeArray(n,i)):vt.mergeArray(n,a)}get items(){return this._def.items}rest(e){return new Hn({...this._def,rest:e})}}Hn.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Hn({items:t,typeName:C.ZodTuple,rest:null,..._e(e)})};class Cp extends be{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==V.map)return F(r,{code:$.invalid_type,expected:V.map,received:r.parsedType}),he;const s=this._def.keyType,a=this._def.valueType,i=[...r.data.entries()].map(([o,c],u)=>({key:s._parse(new $n(r,o,r.path,[u,"key"])),value:a._parse(new $n(r,c,r.path,[u,"value"]))}));if(r.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of i){const u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return he;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),o.set(u.value,l.value)}return{status:n.value,value:o}})}else{const o=new Map;for(const c of i){const u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return he;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),o.set(u.value,l.value)}return{status:n.value,value:o}}}}Cp.create=(t,e,n)=>new Cp({valueType:e,keyType:t,typeName:C.ZodMap,..._e(n)});class is extends be{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==V.set)return F(r,{code:$.invalid_type,expected:V.set,received:r.parsedType}),he;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(F(r,{code:$.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(F(r,{code:$.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const a=this._def.valueType;function i(c){const u=new Set;for(const l of c){if(l.status==="aborted")return he;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}const o=[...r.data.values()].map((c,u)=>a._parse(new $n(r,c,r.path,u)));return r.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,n){return new is({...this._def,minSize:{value:e,message:G.toString(n)}})}max(e,n){return new is({...this._def,maxSize:{value:e,message:G.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}is.create=(t,e)=>new is({valueType:t,minSize:null,maxSize:null,typeName:C.ZodSet,..._e(e)});class Rp extends be{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Rp.create=(t,e)=>new Rp({getter:t,typeName:C.ZodLazy,..._e(e)});let Np=class extends be{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return F(n,{received:n.data,code:$.invalid_literal,expected:this._def.value}),he}return{status:"valid",value:e.data}}get value(){return this._def.value}};Np.create=(t,e)=>new Np({value:t,typeName:C.ZodLiteral,..._e(e)});function Pp(t,e){return new eu({values:t,typeName:C.ZodEnum,..._e(e)})}let eu=class Il extends be{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),r=this._def.values;return F(n,{expected:ve.joinValues(r),received:n.parsedType,code:$.invalid_type}),he}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),r=this._def.values;return F(n,{received:n.data,code:$.invalid_enum_value,options:r}),he}return $t(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return Il.create(e,{...this._def,...n})}exclude(e,n=this._def){return Il.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};eu.create=Pp;class Mp extends be{_parse(e){const n=ve.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==V.string&&r.parsedType!==V.number){const s=ve.objectValues(n);return F(r,{expected:ve.joinValues(s),received:r.parsedType,code:$.invalid_type}),he}if(this._cache||(this._cache=new Set(ve.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=ve.objectValues(n);return F(r,{received:r.data,code:$.invalid_enum_value,options:s}),he}return $t(e.data)}get enum(){return this._def.values}}Mp.create=(t,e)=>new Mp({values:t,typeName:C.ZodNativeEnum,..._e(e)});class Oa extends be{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==V.promise&&n.common.async===!1)return F(n,{code:$.invalid_type,expected:V.promise,received:n.parsedType}),he;const r=n.parsedType===V.promise?n.data:Promise.resolve(n.data);return $t(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Oa.create=(t,e)=>new Oa({type:t,typeName:C.ZodPromise,..._e(e)});class mr extends be{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===C.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:i=>{F(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){const i=s.transform(r.data,a);if(r.common.async)return Promise.resolve(i).then(async o=>{if(n.value==="aborted")return he;const c=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return c.status==="aborted"?he:c.status==="dirty"||n.value==="dirty"?ss(c.value):c});{if(n.value==="aborted")return he;const o=this._def.schema._parseSync({data:i,path:r.path,parent:r});return o.status==="aborted"?he:o.status==="dirty"||n.value==="dirty"?ss(o.value):o}}if(s.type==="refinement"){const i=o=>{const c=s.refinement(o,a);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?he:(o.status==="dirty"&&n.dirty(),i(o.value),{status:n.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?he:(o.status==="dirty"&&n.dirty(),i(o.value).then(()=>({status:n.value,value:o.value}))))}if(s.type==="transform")if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!hr(i))return he;const o=s.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>hr(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:n.value,value:o})):he);ve.assertNever(s)}}mr.create=(t,e,n)=>new mr({schema:t,typeName:C.ZodEffects,effect:e,..._e(n)}),mr.createWithPreprocess=(t,e,n)=>new mr({schema:e,effect:{type:"preprocess",transform:t},typeName:C.ZodEffects,..._e(n)});let Rn=class extends be{_parse(e){return this._getType(e)===V.undefined?$t(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Rn.create=(t,e)=>new Rn({innerType:t,typeName:C.ZodOptional,..._e(e)});let gr=class extends be{_parse(e){return this._getType(e)===V.null?$t(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};gr.create=(t,e)=>new gr({innerType:t,typeName:C.ZodNullable,..._e(e)});let tu=class extends be{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===V.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};tu.create=(t,e)=>new tu({innerType:t,typeName:C.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._e(e)});let nu=class extends be{_parse(e){const{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return xa(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new hn(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new hn(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};nu.create=(t,e)=>new nu({innerType:t,typeName:C.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,..._e(e)});class Lp extends be{_parse(e){if(this._getType(e)!==V.nan){const r=this._getOrReturnCtx(e);return F(r,{code:$.invalid_type,expected:V.nan,received:r.parsedType}),he}return{status:"valid",value:e.data}}}Lp.create=t=>new Lp({typeName:C.ZodNaN,..._e(t)});class _x extends be{_parse(e){const{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class ru extends be{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?he:a.status==="dirty"?(n.dirty(),ss(a.value)):this._def.out._parseAsync({data:a.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?he:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new ru({in:e,out:n,typeName:C.ZodPipeline})}}let su=class extends be{_parse(e){const n=this._def.innerType._parse(e),r=s=>(hr(s)&&(s.value=Object.freeze(s.value)),s);return xa(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};su.create=(t,e)=>new su({innerType:t,typeName:C.ZodReadonly,..._e(e)});var C;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(C||(C={}));const $a=Xc.create,jp=Yc.create;Cn.create,fr.create;const Ca=fn.create;Aa.create,ka.create,Hn.create,eu.create,Oa.create,Rn.create,gr.create;function yx(t,e){const n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==C.ZodAny&&(n.items=Te(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&xe(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&xe(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(xe(n,"minItems",t.exactLength.value,t.exactLength.message,e),xe(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function wx(t,e){const n={type:"integer",format:"int64"};if(!t.checks)return n;for(const r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?xe(n,"minimum",r.value,r.message,e):xe(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),xe(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?xe(n,"maximum",r.value,r.message,e):xe(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),xe(n,"maximum",r.value,r.message,e));break;case"multipleOf":xe(n,"multipleOf",r.value,r.message,e);break}return n}function bx(){return{type:"boolean"}}function Dp(t,e){return Te(t.type._def,e)}const vx=(t,e)=>Te(t.innerType._def,e);function zp(t,e,n){const r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(s=>zp(t,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Ex(t,e)}}const Ex=(t,e)=>{const n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(const r of t.checks)switch(r.kind){case"min":xe(n,"minimum",r.value,r.message,e);break;case"max":xe(n,"maximum",r.value,r.message,e);break}return n};function Sx(t,e){return{...Te(t.innerType._def,e),default:t.defaultValue()}}function Tx(t,e){return e.effectStrategy==="input"?Te(t.schema._def,e):bt(e)}function xx(t){return{type:"string",enum:Array.from(t.values)}}const Ix=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Ax(t,e){const n=[Te(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Te(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a);let r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return n.forEach(a=>{if(Ix(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(r=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...c}=a;i=c}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}function kx(t,e){const n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}let au;const Ft={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:()=>(au===void 0&&(au=RegExp("^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$","u")),au),uuid:/^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/};function Fp(t,e){const n={type:"string"};if(t.checks)for(const r of t.checks)switch(r.kind){case"min":xe(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":xe(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Ut(n,"email",r.message,e);break;case"format:idn-email":Ut(n,"idn-email",r.message,e);break;case"pattern:zod":dt(n,Ft.email,r.message,e);break}break;case"url":Ut(n,"uri",r.message,e);break;case"uuid":Ut(n,"uuid",r.message,e);break;case"regex":dt(n,r.regex,r.message,e);break;case"cuid":dt(n,Ft.cuid,r.message,e);break;case"cuid2":dt(n,Ft.cuid2,r.message,e);break;case"startsWith":dt(n,RegExp(`^${iu(r.value,e)}`),r.message,e);break;case"endsWith":dt(n,RegExp(`${iu(r.value,e)}$`),r.message,e);break;case"datetime":Ut(n,"date-time",r.message,e);break;case"date":Ut(n,"date",r.message,e);break;case"time":Ut(n,"time",r.message,e);break;case"duration":Ut(n,"duration",r.message,e);break;case"length":xe(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),xe(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":dt(n,RegExp(iu(r.value,e)),r.message,e);break;case"ip":r.version!=="v6"&&Ut(n,"ipv4",r.message,e),r.version!=="v4"&&Ut(n,"ipv6",r.message,e);break;case"base64url":dt(n,Ft.base64url,r.message,e);break;case"jwt":dt(n,Ft.jwt,r.message,e);break;case"cidr":r.version!=="v6"&&dt(n,Ft.ipv4Cidr,r.message,e),r.version!=="v4"&&dt(n,Ft.ipv6Cidr,r.message,e);break;case"emoji":dt(n,Ft.emoji(),r.message,e);break;case"ulid":dt(n,Ft.ulid,r.message,e);break;case"base64":switch(e.base64Strategy){case"format:binary":Ut(n,"binary",r.message,e);break;case"contentEncoding:base64":xe(n,"contentEncoding","base64",r.message,e);break;case"pattern:zod":dt(n,Ft.base64,r.message,e);break}break;case"nanoid":dt(n,Ft.nanoid,r.message,e);break}return n}function iu(t,e){return e.patternStrategy==="escape"?$x(t):t}const Ox=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function $x(t){let e="";for(let n=0;n<t.length;n++)Ox.has(t[n])||(e+="\\\\"),e+=t[n];return e}function Ut(t,e,n,r){t.format||t.anyOf?.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&r.errorMessages&&{errorMessage:{format:n}}})):xe(t,"format",e,n,r)}function dt(t,e,n,r){t.pattern||t.allOf?.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Up(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):xe(t,"pattern",Up(e,r),n,r)}function Up(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;const n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source;let s="",a=!1,i=!1,o=!1;for(let c=0;c<r.length;c++){if(a){s+=r[c],a=!1;continue}if(n.i){if(i){if(r[c].match(/[a-z]/)){o?(s+=r[c],s+=`${r[c-2]}-${r[c]}`.toUpperCase(),o=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(s+=r[c],o=!0):s+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){s+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(n.m){if(r[c]==="^"){s+=`(^|(?<=[\\r\n]))`;continue}else if(r[c]==="$"){s+=`($|(?=[\\r\n]))`;continue}}if(n.s&&r[c]==="."){s+=i?`${r[c]}\\r\n`:`[${r[c]}\\r\n]`;continue}s+=r[c],r[c]==="\\\\"?a=!0:i&&r[c]==="]"?i=!1:!i&&r[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function Bp(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===C.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,s)=>({...r,[s]:Te(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??bt(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const n={type:"object",additionalProperties:Te(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===C.ZodString&&t.keyType._def.checks?.length){const{type:r,...s}=Fp(t.keyType._def,e);return{...n,propertyNames:s}}else{if(t.keyType?._def.typeName===C.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===C.ZodBranded&&t.keyType._def.type._def.typeName===C.ZodString&&t.keyType._def.type._def.checks?.length){const{type:r,...s}=Dp(t.keyType._def,e);return{...n,propertyNames:s}}}return n}function Cx(t,e){if(e.mapStrategy==="record")return Bp(t,e);const n=Te(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||bt(e),r=Te(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||bt(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function Rx(t){const e=t.values,r=Object.keys(t.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),s=Array.from(new Set(r.map(a=>typeof a)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function Nx(t){return t.target==="openAi"?void 0:{not:bt({...t,currentPath:[...t.currentPath,"not"]})}}function Px(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Ra={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Mx(t,e){if(e.target==="openApi3")return Zp(t,e);const n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in Ra&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((s,a)=>{const i=Ra[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((s,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":return a._def.value===null?[...s,"null"]:s;case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===n.length){const s=r.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:n.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,s)=>[...r,...s._def.values.filter(a=>!r.includes(a))],[])};return Zp(t,e)}const Zp=(t,e)=>{const n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,s)=>Te(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function Lx(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Ra[t.innerType._def.typeName],nullable:!0}:{type:[Ra[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const r=Te(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const n=Te(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function jx(t,e){const n={type:"number"};if(!t.checks)return n;for(const r of t.checks)switch(r.kind){case"int":n.type="integer",_p(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?xe(n,"minimum",r.value,r.message,e):xe(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),xe(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?xe(n,"maximum",r.value,r.message,e):xe(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),xe(n,"maximum",r.value,r.message,e));break;case"multipleOf":xe(n,"multipleOf",r.value,r.message,e);break}return n}function Dx(t,e){const n=e.target==="openAi",r={type:"object",properties:{}},s=[],a=t.shape();for(const o in a){let c=a[o];if(c===void 0||c._def===void 0)continue;let u=Fx(c);u&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=Te(c._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});l!==void 0&&(r.properties[o]=l,u||s.push(o))}s.length&&(r.required=s);const i=zx(t,e);return i!==void 0&&(r.additionalProperties=i),r}function zx(t,e){if(t.catchall._def.typeName!=="ZodNever")return Te(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Fx(t){try{return t.isOptional()}catch{return!0}}const Ux=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Te(t.innerType._def,e);const n=Te(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:bt(e)},n]}:bt(e)},Bx=(t,e)=>{if(e.pipeStrategy==="input")return Te(t.in._def,e);if(e.pipeStrategy==="output")return Te(t.out._def,e);const n=Te(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=Te(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}};function Zx(t,e){return Te(t.type._def,e)}function qx(t,e){const r={type:"array",uniqueItems:!0,items:Te(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&xe(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&xe(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}function Vx(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>Te(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Te(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>Te(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function Hx(t){return{not:bt(t)}}function Gx(t){return bt(t)}const Wx=(t,e)=>Te(t.innerType._def,e),Jx=(t,e,n)=>{switch(e){case C.ZodString:return Fp(t,n);case C.ZodNumber:return jx(t,n);case C.ZodObject:return Dx(t,n);case C.ZodBigInt:return wx(t,n);case C.ZodBoolean:return bx();case C.ZodDate:return zp(t,n);case C.ZodUndefined:return Hx(n);case C.ZodNull:return Px(n);case C.ZodArray:return yx(t,n);case C.ZodUnion:case C.ZodDiscriminatedUnion:return Mx(t,n);case C.ZodIntersection:return Ax(t,n);case C.ZodTuple:return Vx(t,n);case C.ZodRecord:return Bp(t,n);case C.ZodLiteral:return kx(t,n);case C.ZodEnum:return xx(t);case C.ZodNativeEnum:return Rx(t);case C.ZodNullable:return Lx(t,n);case C.ZodOptional:return Ux(t,n);case C.ZodMap:return Cx(t,n);case C.ZodSet:return qx(t,n);case C.ZodLazy:return()=>t.getter()._def;case C.ZodPromise:return Zx(t,n);case C.ZodNaN:case C.ZodNever:return Nx(n);case C.ZodEffects:return Tx(t,n);case C.ZodAny:return bt(n);case C.ZodUnknown:return Gx(n);case C.ZodDefault:return Sx(t,n);case C.ZodBranded:return Dp(t,n);case C.ZodReadonly:return Wx(t,n);case C.ZodCatch:return vx(t,n);case C.ZodPipeline:return Bx(t,n);case C.ZodFunction:case C.ZodVoid:case C.ZodSymbol:return;default:return(r=>{})()}};function Te(t,e,n=!1){const r=e.seen.get(t);if(e.override){const o=e.override?.(t,e,r,n);if(o!==BT)return o}if(r&&!n){const o=Kx(r,e);if(o!==void 0)return o}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const a=Jx(t,t.typeName,e),i=typeof a=="function"?Te(a(),e):a;if(i&&Xx(t,e,i),e.postProcess){const o=e.postProcess(i,t,e);return s.jsonSchema=i,o}return s.jsonSchema=i,i}const Kx=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:gp(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),bt(e)):e.$refStrategy==="seen"?bt(e):void 0}},Xx=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n),Yx=(t,e)=>{const n=VT(e);let r;const s=Te(t._def,n,!1)??bt(n);n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const a=r?{...s,[n.definitionPath]:r}:s;return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function Gn(t,e){const n=typeof t;if(n!==typeof e)return!1;if(Array.isArray(t)){if(!Array.isArray(e))return!1;const r=t.length;if(r!==e.length)return!1;for(let s=0;s<r;s++)if(!Gn(t[s],e[s]))return!1;return!0}if(n==="object"){if(!t||!e)return t===e;const r=Object.keys(t),s=Object.keys(e);if(r.length!==s.length)return!1;for(const i of r)if(!Gn(t[i],e[i]))return!1;return!0}return t===e}function Bt(t){return encodeURI(Qx(t))}function Qx(t){return t.replace(/~/g,"~0").replace(/\\//g,"~1")}const eI={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},tI={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},nI={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};let rI=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function Nn(t,e=Object.create(null),n=rI,r=""){if(t&&typeof t=="object"&&!Array.isArray(t)){const a=t.$id||t.id;if(a){const i=new URL(a,n.href);i.hash.length>1?e[i.href]=t:(i.hash="",r===""?n=i:Nn(t,e,n))}}else if(t!==!0&&t!==!1)return e;const s=n.href+(r?"#"+r:"");if(e[s]!==void 0)throw new Error(`Duplicate schema URI "${s}".`);if(e[s]=t,t===!0||t===!1)return e;if(t.__absolute_uri__===void 0&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:s}),t.$ref&&t.__absolute_ref__===void 0){const a=new URL(t.$ref,n.href);a.hash=a.hash,Object.defineProperty(t,"__absolute_ref__",{enumerable:!1,value:a.href})}if(t.$recursiveRef&&t.__absolute_recursive_ref__===void 0){const a=new URL(t.$recursiveRef,n.href);a.hash=a.hash,Object.defineProperty(t,"__absolute_recursive_ref__",{enumerable:!1,value:a.href})}if(t.$anchor){const a=new URL("#"+t.$anchor,n.href);e[a.href]=t}for(let a in t){if(nI[a])continue;const i=`${r}/${Bt(a)}`,o=t[a];if(Array.isArray(o)){if(eI[a]){const c=o.length;for(let u=0;u<c;u++)Nn(o[u],e,n,`${i}/${u}`)}}else if(tI[a])for(let c in o)Nn(o[c],e,n,`${i}/${Bt(c)}`);else Nn(o,e,n,i)}return e}const sI=/^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$/,aI=[0,31,28,31,30,31,30,31,31,30,31,30,31],iI=/^(\\d\\d):(\\d\\d):(\\d\\d)(\\.\\d+)?(z|[+-]\\d\\d(?::?\\d\\d)?)?$/i,oI=/^(?=.{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,cI=/^(?:[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,uI=/^(?:(?:[^\\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,lI=/^(?:(?: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,dI=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,hI=/^(?:\\/(?:[^~/]|~0|~1)*)*$/,fI=/^#(?:\\/(?:[a-z0-9_\\-.!$&\'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,pI=/^(?:0|[1-9][0-9]*)(?:#|(?:\\/(?:[^~/]|~0|~1)*)*)$/,mI=t=>{if(t[0]===\'"\')return!1;const[e,n,...r]=t.split("@");return!e||!n||r.length!==0||e.length>64||n.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&\'*+/=?^_`{|}~-]+$/i.test(e)?!1:n.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},gI=/^(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$/,_I=/^((([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,yI=t=>t.length>1&&t.length<80&&(/^P\\d+([.,]\\d+)?W$/.test(t)||/^P[\\dYMDTHS]*(\\d[.,]\\d+)?[YMDHS]$/.test(t)&&/^P([.,\\d]+Y)?([.,\\d]+M)?([.,\\d]+D)?(T([.,\\d]+H)?([.,\\d]+M)?([.,\\d]+S)?)?$/.test(t));function Qt(t){return t.test.bind(t)}const qp={date:Vp,time:Hp.bind(void 0,!1),"date-time":vI,duration:yI,uri:TI,"uri-reference":Qt(cI),"uri-template":Qt(uI),url:Qt(lI),email:mI,hostname:Qt(oI),ipv4:Qt(gI),ipv6:Qt(_I),regex:II,uuid:Qt(dI),"json-pointer":Qt(hI),"json-pointer-uri-fragment":Qt(fI),"relative-json-pointer":Qt(pI)};function wI(t){return t%4===0&&(t%100!==0||t%400===0)}function Vp(t){const e=t.match(sI);if(!e)return!1;const n=+e[1],r=+e[2],s=+e[3];return r>=1&&r<=12&&s>=1&&s<=(r==2&&wI(n)?29:aI[r])}function Hp(t,e){const n=e.match(iI);if(!n)return!1;const r=+n[1],s=+n[2],a=+n[3],i=!!n[5];return(r<=23&&s<=59&&a<=59||r==23&&s==59&&a==60)&&(!t||i)}const bI=/t|\\s/i;function vI(t){const e=t.split(bI);return e.length==2&&Vp(e[0])&&Hp(!0,e[1])}const EI=/\\/|:/,SI=/^(?:[a-z][a-z0-9+\\-.]*:)(?:\\/?\\/(?:(?:[a-z0-9\\-._~!$&\'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\\.[a-z0-9\\-._~!$&\'()*+,;=:]+)\\]|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)|(?:[a-z0-9\\-._~!$&\'()*+,;=]|%[0-9a-f]{2})*)(?::\\d*)?(?:\\/(?:[a-z0-9\\-._~!$&\'()*+,;=:@]|%[0-9a-f]{2})*)*|\\/(?:(?:[a-z0-9\\-._~!$&\'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&\'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\\-._~!$&\'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&\'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\\?(?:[a-z0-9\\-._~!$&\'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\\-._~!$&\'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function TI(t){return EI.test(t)&&SI.test(t)}const xI=/[^\\\\]\\\\Z/;function II(t){if(xI.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}function AI(t){let e=0,n=t.length,r=0,s;for(;r<n;)e++,s=t.charCodeAt(r++),s>=55296&&s<=56319&&r<n&&(s=t.charCodeAt(r),(s&64512)==56320&&r++);return e}function Ce(t,e,n="2019-09",r=Nn(e),s=!0,a=null,i="#",o="#",c=Object.create(null)){if(e===!0)return{valid:!0,errors:[]};if(e===!1)return{valid:!1,errors:[{instanceLocation:i,keyword:"false",keywordLocation:i,error:"False boolean schema."}]};const u=typeof t;let l;switch(u){case"boolean":case"number":case"string":l=u;break;case"object":t===null?l="null":Array.isArray(t)?l="array":l="object";break;default:throw new Error(`Instances of "${u}" type are not supported.`)}const{$ref:d,$recursiveRef:f,$recursiveAnchor:h,type:p,const:m,enum:y,required:v,not:w,anyOf:E,allOf:x,oneOf:A,if:N,then:j,else:b,format:oe,properties:ue,patternProperties:X,additionalProperties:Be,unevaluatedProperties:kt,minProperties:L,maxProperties:R,propertyNames:P,dependentRequired:H,dependentSchemas:Y,dependencies:q,prefixItems:ne,items:me,additionalItems:fe,unevaluatedItems:Se,contains:ze,minContains:Ee,maxContains:_,minItems:g,maxItems:k,uniqueItems:S,minimum:ye,maximum:Ie,exclusiveMinimum:Oe,exclusiveMaximum:Ze,multipleOf:nt,minLength:Gt,maxLength:je,pattern:Ct,__absolute_ref__:$r,__absolute_recursive_ref__:$i}=e,z=[];if(h===!0&&a===null&&(a=e),f==="#"){const se=a===null?r[$i]:a,te=`${o}/$recursiveRef`,le=Ce(t,a===null?e:a,n,r,s,se,i,te,c);le.valid||z.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:te,error:"A subschema had errors."},...le.errors)}if(d!==void 0){const te=r[$r||d];if(te===void 0){let D=`Unresolved $ref "${d}".`;throw $r&&$r!==d&&(D+=` Absolute URI "${$r}".`),D+=`\nKnown schemas:\n- ${Object.keys(r).join(`\n- `)}`,new Error(D)}const le=`${o}/$ref`,Z=Ce(t,te,n,r,s,a,i,le,c);if(Z.valid||z.push({instanceLocation:i,keyword:"$ref",keywordLocation:le,error:"A subschema had errors."},...Z.errors),n==="4"||n==="7")return{valid:z.length===0,errors:z}}if(Array.isArray(p)){let se=p.length,te=!1;for(let le=0;le<se;le++)if(l===p[le]||p[le]==="integer"&&l==="number"&&t%1===0&&t===t){te=!0;break}te||z.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${p.join(\'", "\')}".`})}else p==="integer"?(l!=="number"||t%1||t!==t)&&z.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${p}".`}):p!==void 0&&l!==p&&z.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${p}".`});if(m!==void 0&&(l==="object"||l==="array"?Gn(t,m)||z.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(m)}.`}):t!==m&&z.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(m)}.`})),y!==void 0&&(l==="object"||l==="array"?y.some(se=>Gn(t,se))||z.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`}):y.some(se=>t===se)||z.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`})),w!==void 0){const se=`${o}/not`;Ce(t,w,n,r,s,a,i,se).valid&&z.push({instanceLocation:i,keyword:"not",keywordLocation:se,error:\'Instance matched "not" schema.\'})}let er=[];if(E!==void 0){const se=`${o}/anyOf`,te=z.length;let le=!1;for(let Z=0;Z<E.length;Z++){const D=E[Z],ce=Object.create(c),ae=Ce(t,D,n,r,s,h===!0?a:null,i,`${se}/${Z}`,ce);z.push(...ae.errors),le=le||ae.valid,ae.valid&&er.push(ce)}le?z.length=te:z.splice(te,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:se,error:"Instance does not match any subschemas."})}if(x!==void 0){const se=`${o}/allOf`,te=z.length;let le=!0;for(let Z=0;Z<x.length;Z++){const D=x[Z],ce=Object.create(c),ae=Ce(t,D,n,r,s,h===!0?a:null,i,`${se}/${Z}`,ce);z.push(...ae.errors),le=le&&ae.valid,ae.valid&&er.push(ce)}le?z.length=te:z.splice(te,0,{instanceLocation:i,keyword:"allOf",keywordLocation:se,error:"Instance does not match every subschema."})}if(A!==void 0){const se=`${o}/oneOf`,te=z.length,le=A.filter((Z,D)=>{const ce=Object.create(c),ae=Ce(t,Z,n,r,s,h===!0?a:null,i,`${se}/${D}`,ce);return z.push(...ae.errors),ae.valid&&er.push(ce),ae.valid}).length;le===1?z.length=te:z.splice(te,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:se,error:`Instance does not match exactly one subschema (${le} matches).`})}if((l==="object"||l==="array")&&Object.assign(c,...er),N!==void 0){const se=`${o}/if`;if(Ce(t,N,n,r,s,a,i,se,c).valid){if(j!==void 0){const le=Ce(t,j,n,r,s,a,i,`${o}/then`,c);le.valid||z.push({instanceLocation:i,keyword:"if",keywordLocation:se,error:\'Instance does not match "then" schema.\'},...le.errors)}}else if(b!==void 0){const le=Ce(t,b,n,r,s,a,i,`${o}/else`,c);le.valid||z.push({instanceLocation:i,keyword:"if",keywordLocation:se,error:\'Instance does not match "else" schema.\'},...le.errors)}}if(l==="object"){if(v!==void 0)for(const Z of v)Z in t||z.push({instanceLocation:i,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${Z}".`});const se=Object.keys(t);if(L!==void 0&&se.length<L&&z.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${L} properties.`}),R!==void 0&&se.length>R&&z.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${R} properties.`}),P!==void 0){const Z=`${o}/propertyNames`;for(const D in t){const ce=`${i}/${Bt(D)}`,ae=Ce(D,P,n,r,s,a,ce,Z);ae.valid||z.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:Z,error:`Property name "${D}" does not match schema.`},...ae.errors)}}if(H!==void 0){const Z=`${o}/dependantRequired`;for(const D in H)if(D in t){const ce=H[D];for(const ae of ce)ae in t||z.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:Z,error:`Instance has "${D}" but does not have "${ae}".`})}}if(Y!==void 0)for(const Z in Y){const D=`${o}/dependentSchemas`;if(Z in t){const ce=Ce(t,Y[Z],n,r,s,a,i,`${D}/${Bt(Z)}`,c);ce.valid||z.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:D,error:`Instance has "${Z}" but does not match dependant schema.`},...ce.errors)}}if(q!==void 0){const Z=`${o}/dependencies`;for(const D in q)if(D in t){const ce=q[D];if(Array.isArray(ce))for(const ae of ce)ae in t||z.push({instanceLocation:i,keyword:"dependencies",keywordLocation:Z,error:`Instance has "${D}" but does not have "${ae}".`});else{const ae=Ce(t,ce,n,r,s,a,i,`${Z}/${Bt(D)}`);ae.valid||z.push({instanceLocation:i,keyword:"dependencies",keywordLocation:Z,error:`Instance has "${D}" but does not match dependant schema.`},...ae.errors)}}}const te=Object.create(null);let le=!1;if(ue!==void 0){const Z=`${o}/properties`;for(const D in ue){if(!(D in t))continue;const ce=`${i}/${Bt(D)}`,ae=Ce(t[D],ue[D],n,r,s,a,ce,`${Z}/${Bt(D)}`);if(ae.valid)c[D]=te[D]=!0;else if(le=s,z.push({instanceLocation:i,keyword:"properties",keywordLocation:Z,error:`Property "${D}" does not match schema.`},...ae.errors),le)break}}if(!le&&X!==void 0){const Z=`${o}/patternProperties`;for(const D in X){const ce=new RegExp(D,"u"),ae=X[D];for(const _t in t){if(!ce.test(_t))continue;const X_=`${i}/${Bt(_t)}`,Y_=Ce(t[_t],ae,n,r,s,a,X_,`${Z}/${Bt(D)}`);Y_.valid?c[_t]=te[_t]=!0:(le=s,z.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:Z,error:`Property "${_t}" matches pattern "${D}" but does not match associated schema.`},...Y_.errors))}}}if(!le&&Be!==void 0){const Z=`${o}/additionalProperties`;for(const D in t){if(te[D])continue;const ce=`${i}/${Bt(D)}`,ae=Ce(t[D],Be,n,r,s,a,ce,Z);ae.valid?c[D]=!0:(le=s,z.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:Z,error:`Property "${D}" does not match additional properties schema.`},...ae.errors))}}else if(!le&&kt!==void 0){const Z=`${o}/unevaluatedProperties`;for(const D in t)if(!c[D]){const ce=`${i}/${Bt(D)}`,ae=Ce(t[D],kt,n,r,s,a,ce,Z);ae.valid?c[D]=!0:z.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:Z,error:`Property "${D}" does not match unevaluated properties schema.`},...ae.errors)}}}else if(l==="array"){k!==void 0&&t.length>k&&z.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${t.length} > ${k}).`}),g!==void 0&&t.length<g&&z.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${t.length} < ${g}).`});const se=t.length;let te=0,le=!1;if(ne!==void 0){const Z=`${o}/prefixItems`,D=Math.min(ne.length,se);for(;te<D;te++){const ce=Ce(t[te],ne[te],n,r,s,a,`${i}/${te}`,`${Z}/${te}`);if(c[te]=!0,!ce.valid&&(le=s,z.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:Z,error:"Items did not match schema."},...ce.errors),le))break}}if(me!==void 0){const Z=`${o}/items`;if(Array.isArray(me)){const D=Math.min(me.length,se);for(;te<D;te++){const ce=Ce(t[te],me[te],n,r,s,a,`${i}/${te}`,`${Z}/${te}`);if(c[te]=!0,!ce.valid&&(le=s,z.push({instanceLocation:i,keyword:"items",keywordLocation:Z,error:"Items did not match schema."},...ce.errors),le))break}}else for(;te<se;te++){const D=Ce(t[te],me,n,r,s,a,`${i}/${te}`,Z);if(c[te]=!0,!D.valid&&(le=s,z.push({instanceLocation:i,keyword:"items",keywordLocation:Z,error:"Items did not match schema."},...D.errors),le))break}if(!le&&fe!==void 0){const D=`${o}/additionalItems`;for(;te<se;te++){const ce=Ce(t[te],fe,n,r,s,a,`${i}/${te}`,D);c[te]=!0,ce.valid||(le=s,z.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:D,error:"Items did not match additional items schema."},...ce.errors))}}}if(ze!==void 0)if(se===0&&Ee===void 0)z.push({instanceLocation:i,keyword:"contains",keywordLocation:`${o}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Ee!==void 0&&se<Ee)z.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array has less items (${se}) than minContains (${Ee}).`});else{const Z=`${o}/contains`,D=z.length;let ce=0;for(let ae=0;ae<se;ae++){const _t=Ce(t[ae],ze,n,r,s,a,`${i}/${ae}`,Z);_t.valid?(c[ae]=!0,ce++):z.push(..._t.errors)}ce>=(Ee||0)&&(z.length=D),Ee===void 0&&_===void 0&&ce===0?z.splice(D,0,{instanceLocation:i,keyword:"contains",keywordLocation:Z,error:"Array does not contain item matching schema."}):Ee!==void 0&&ce<Ee?z.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array must contain at least ${Ee} items matching schema. Only ${ce} items were found.`}):_!==void 0&&ce>_&&z.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${_} items matching schema. ${ce} items were found.`})}if(!le&&Se!==void 0){const Z=`${o}/unevaluatedItems`;for(te;te<se;te++){if(c[te])continue;const D=Ce(t[te],Se,n,r,s,a,`${i}/${te}`,Z);c[te]=!0,D.valid||z.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:Z,error:"Items did not match unevaluated items schema."},...D.errors)}}if(S)for(let Z=0;Z<se;Z++){const D=t[Z],ce=typeof D=="object"&&D!==null;for(let ae=0;ae<se;ae++){if(Z===ae)continue;const _t=t[ae];(D===_t||ce&&(typeof _t=="object"&&_t!==null)&&Gn(D,_t))&&(z.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${o}/uniqueItems`,error:`Duplicate items at indexes ${Z} and ${ae}.`}),Z=Number.MAX_SAFE_INTEGER,ae=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(n==="4"?(ye!==void 0&&(Oe===!0&&t<=ye||t<ye)&&z.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${t} is less than ${Oe?"or equal to ":""} ${ye}.`}),Ie!==void 0&&(Ze===!0&&t>=Ie||t>Ie)&&z.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${t} is greater than ${Ze?"or equal to ":""} ${Ie}.`})):(ye!==void 0&&t<ye&&z.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${t} is less than ${ye}.`}),Ie!==void 0&&t>Ie&&z.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${t} is greater than ${Ie}.`}),Oe!==void 0&&t<=Oe&&z.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${t} is less than ${Oe}.`}),Ze!==void 0&&t>=Ze&&z.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${t} is greater than or equal to ${Ze}.`})),nt!==void 0){const se=t%nt;Math.abs(0-se)>=11920929e-14&&Math.abs(nt-se)>=11920929e-14&&z.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${t} is not a multiple of ${nt}.`})}}else if(l==="string"){const se=Gt===void 0&&je===void 0?0:AI(t);Gt!==void 0&&se<Gt&&z.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${se} < ${Gt}).`}),je!==void 0&&se>je&&z.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${se} > ${je}).`}),Ct!==void 0&&!new RegExp(Ct,"u").test(t)&&z.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),oe!==void 0&&qp[oe]&&!qp[oe](t)&&z.push({instanceLocation:i,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${oe}".`})}return{valid:z.length===0,errors:z}}class kI{schema;draft;shortCircuit;lookup;constructor(e,n="2019-09",r=!0){this.schema=e,this.draft=n,this.shortCircuit=r,this.lookup=Nn(e)}validate(e){return Ce(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,n){n&&(e={...e,$id:n}),Nn(e,this.lookup)}}var OI={};ge(OI,{Validator:()=>kI,deepCompareStrict:()=>Gn,toJsonSchema:()=>_r,validatesOnlyStrings:()=>os});function _r(t,e){if(Ne(t)){const n=pp(t,!0);if(Yt(n)){const r=Ta(n,!0);return cp(r,e)}else return cp(t,e)}return Ve(t)?Yx(t):t}function os(t){if(!t||typeof t!="object"||Object.keys(t).length===0||Array.isArray(t))return!1;if("type"in t)return typeof t.type=="string"?t.type==="string":Array.isArray(t.type)?t.type.every(e=>e==="string"):!1;if("enum"in t)return Array.isArray(t.enum)&&t.enum.length>0&&t.enum.every(e=>typeof e=="string");if("const"in t)return typeof t.const=="string";if("allOf"in t&&Array.isArray(t.allOf))return t.allOf.some(e=>os(e));if("anyOf"in t&&Array.isArray(t.anyOf)||"oneOf"in t&&Array.isArray(t.oneOf)){const e="anyOf"in t?t.anyOf:t.oneOf;return e.length>0&&e.every(n=>os(n))}if("not"in t)return!1;if("$ref"in t&&typeof t.$ref=="string"){const e=t.$ref,n=Nn(t);return n[e]?os(n[e]):!1}return!1}var $I={};ge($I,{Graph:()=>ou});function CI(t,e){if(t!==void 0&&!Dr(t))return t;if(Cc(e))try{let n=e.getName();return n=n.startsWith("Runnable")?n.slice(8):n,n}catch{return e.getName()}else return e.name??"UnknownSchema"}function RI(t){return Cc(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{..._r(t.data.schema),title:t.data.name}}}var ou=class ay{nodes={};edges=[];constructor(e){this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach((n,r)=>{e[n.id]=Dr(n.id)?r:n.id}),{nodes:Object.values(this.nodes).map(n=>({id:e[n.id],...RI(n)})),edges:this.edges.map(n=>{const r={source:e[n.source],target:e[n.target]};return typeof n.data<"u"&&(r.data=n.data),typeof n.conditional<"u"&&(r.conditional=n.conditional),r})}}addNode(e,n,r){if(n!==void 0&&this.nodes[n]!==void 0)throw new Error(`Node with id ${n} already exists`);const s=n??Fn(),a={id:s,data:e,name:CI(n,e),metadata:r};return this.nodes[s]=a,a}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(n=>n.source!==e.id&&n.target!==e.id)}addEdge(e,n,r,s){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[n.id]===void 0)throw new Error(`Target node ${n.id} not in graph`);const a={source:e.id,target:n.id,data:r,conditional:s};return this.edges.push(a),a}firstNode(){return Gp(this)}lastNode(){return Wp(this)}extend(e,n=""){let r=n;Object.values(e.nodes).map(u=>u.id).every(Dr)&&(r="");const a=u=>r?`${r}:${u}`:u;Object.entries(e.nodes).forEach(([u,l])=>{this.nodes[a(u)]={...l,id:a(u)}});const i=e.edges.map(u=>({...u,source:a(u.source),target:a(u.target)}));this.edges=[...this.edges,...i];const o=e.firstNode(),c=e.lastNode();return[o?{id:a(o.id),data:o.data}:void 0,c?{id:a(c.id),data:c.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&Gp(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&Wp(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map(s=>[s.id,s.name])),n=new Map;Object.values(e).forEach(s=>{n.set(s,(n.get(s)||0)+1)});const r=s=>{const a=e[s];return Dr(s)&&n.get(a)===1?a:s};return new ay({nodes:Object.fromEntries(Object.entries(this.nodes).map(([s,a])=>[r(s),{...a,id:r(s)}])),edges:this.edges.map(s=>({...s,source:r(s.source),target:r(s.target)}))})}drawMermaid(e){const{withStyles:n,curveStyle:r,nodeColors:s={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:a}=e??{},i=this.reid(),o=i.firstNode(),c=i.lastNode();return FT(i.nodes,i.edges,{firstNode:o?.id,lastNode:c?.id,withStyles:n,curveStyle:r,nodeColors:s,wrapLabelNWords:a})}async drawMermaidPng(e){const n=this.drawMermaid(e);return UT(n,{backgroundColor:e?.backgroundColor})}};function Gp(t,e=[]){const n=new Set(t.edges.filter(s=>!e.includes(s.source)).map(s=>s.target)),r=[];for(const s of Object.values(t.nodes))!e.includes(s.id)&&!n.has(s.id)&&r.push(s);return r.length===1?r[0]:void 0}function Wp(t,e=[]){const n=new Set(t.edges.filter(s=>!e.includes(s.target)).map(s=>s.source)),r=[];for(const s of Object.values(t.nodes))!e.includes(s.id)&&!n.has(s.id)&&r.push(s);return r.length===1?r[0]:void 0}function NI(t){const e=new TextEncoder,n=new ReadableStream({async start(r){for await(const s of t)r.enqueue(e.encode(`event: data\ndata: ${JSON.stringify(s)}\n\n`));r.enqueue(e.encode(`event: end\n\n`)),r.close()}});return Dt.fromReadableStream(n)}function Jp(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}const PI=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function";function cu(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*Kp(t,e){for(;;){const{value:n,done:r}=jt.runWithConfig(un(t),e.next.bind(e),!0);if(r)break;yield n}}async function*uu(t,e){const n=e[Symbol.asyncIterator]();for(;;){const{value:r,done:s}=await jt.runWithConfig(un(t),n.next.bind(e),!0);if(s)break;yield r}}function He(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}var Pe=class extends Dn{lc_runnable=!0;name;getName(t){const e=this.name??this.constructor.lc_name()??this.constructor.name;return t?`${e}${t}`:e}withRetry(t){return new lu({bound:this,kwargs:{},config:{},maxAttemptNumber:t?.stopAfterAttempt,...t})}withConfig(t){return new yr({bound:this,config:t,kwargs:{}})}withFallbacks(t){const e=Array.isArray(t)?t:t.fallbacks;return new Xp({runnable:this,fallbacks:e})}_getOptionsList(t,e=0){if(Array.isArray(t)&&t.length!==e)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${t.length} options for ${e} inputs`);if(Array.isArray(t))return t.map(we);if(e>1&&!Array.isArray(t)&&t.runId){console.warn("Provided runId will be used only for the first element of the batch.");const n=Object.fromEntries(Object.entries(t).filter(([r])=>r!=="runId"));return Array.from({length:e},(r,s)=>we(s===0?t:n))}return Array.from({length:e},()=>we(t))}async batch(t,e,n){const r=this._getOptionsList(e??{},t.length),s=r[0]?.maxConcurrency??n?.maxConcurrency,a=new Xr({maxConcurrency:s,onFailedAttempt:o=>{throw o}}),i=t.map((o,c)=>a.call(async()=>{try{return await this.invoke(o,r[c])}catch(u){if(n?.returnExceptions)return u;throw u}}));return Promise.all(i)}async*_streamIterator(t,e){yield this.invoke(t,e)}async stream(t,e){const n=we(e),r=new Bn({generator:this._streamIterator(t,n),config:n});return await r.setup,Dt.fromAsyncGenerator(r)}_separateRunnableConfigFromCallOptions(t){let e;t===void 0?e=we(t):e=we({callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,runName:t.runName,configurable:t.configurable,recursionLimit:t.recursionLimit,maxConcurrency:t.maxConcurrency,runId:t.runId,timeout:t.timeout,signal:t.signal});const n={...t};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[e,n]}async _callWithConfig(t,e,n){const r=we(n),a=await(await wt(r))?.handleChainStart(this.toJSON(),He(e,"input"),r.runId,r?.runType,void 0,void 0,r?.runName??this.getName());delete r.runId;let i;try{const o=t.call(this,e,r,a);i=await ln(o,n?.signal)}catch(o){throw await a?.handleChainError(o),o}return await a?.handleChainEnd(He(i,"output")),i}async _batchWithConfig(t,e,n,r){const s=this._getOptionsList(n??{},e.length),a=await Promise.all(s.map(wt)),i=await Promise.all(a.map(async(c,u)=>{const l=await c?.handleChainStart(this.toJSON(),He(e[u],"input"),s[u].runId,s[u].runType,void 0,void 0,s[u].runName??this.getName());return delete s[u].runId,l}));let o;try{const c=t.call(this,e,s,i,r);o=await ln(c,s?.[0]?.signal)}catch(c){throw await Promise.all(i.map(u=>u?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(He(o,"output")))),o}_concatOutputChunks(t,e){return In(t,e)}async*_transformStreamWithConfig(t,e,n){let r,s=!0,a,i=!0;const o=we(n),c=await wt(o),u=this;async function*l(){for await(const f of t){if(s)if(r===void 0)r=f;else try{r=u._concatOutputChunks(r,f)}catch{r=void 0,s=!1}yield f}}let d;try{const f=await uf(e.bind(this),l(),async()=>c?.handleChainStart(this.toJSON(),{input:""},o.runId,o.runType,void 0,void 0,o.runName??this.getName(),void 0,{lc_defers_inputs:!0}),n?.signal,o);delete o.runId,d=f.setup;const h=d?.handlers.find(P0);let p=f.output;h!==void 0&&d!==void 0&&(p=h.tapOutputIterable(d.runId,p));const m=d?.handlers.find(pf);m!==void 0&&d!==void 0&&(p=m.tapOutputIterable(d.runId,p));for await(const y of p)if(yield y,i)if(a===void 0)a=y;else try{a=this._concatOutputChunks(a,y)}catch{a=void 0,i=!1}}catch(f){throw await d?.handleChainError(f,void 0,void 0,void 0,{inputs:He(r,"input")}),f}await d?.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:He(r,"input")})}getGraph(t){const e=new ou,n=e.addNode({name:`${this.getName()}Input`,schema:jp()}),r=e.addNode(this),s=e.addNode({name:`${this.getName()}Output`,schema:jp()});return e.addEdge(n,r),e.addEdge(r,s),e}pipe(t){return new Na({first:this,last:Zt(t)})}pick(t){return this.pipe(new Yp(t))}assign(t){return this.pipe(new du(new wr({steps:t})))}async*transform(t,e){let n;for await(const r of t)n===void 0?n=r:n=this._concatOutputChunks(n,r);yield*this._streamIterator(n,we(e))}async*streamLog(t,e,n){const r=new kc({...n,autoClose:!1,_schemaFormat:"original"}),s=we(e);yield*this._streamLog(t,r,s)}async*_streamLog(t,e,n){const{callbacks:r}=n;if(r===void 0)n.callbacks=[e];else if(Array.isArray(r))n.callbacks=r.concat([e]);else{const o=r.copy();o.addHandler(e,!0),n.callbacks=o}const s=this.stream(t,n);async function a(){try{const o=await s;for await(const c of o){const u=new dn({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await e.writer.write(u)}}finally{await e.writer.close()}}const i=a();try{for await(const o of e)yield o}finally{await i}}streamEvents(t,e,n){let r;if(e.version==="v1")r=this._streamEventsV1(t,e,n);else if(e.version==="v2")r=this._streamEventsV2(t,e,n);else throw new Error(\'Only versions "v1" and "v2" of the schema are currently supported.\');return e.encoding==="text/event-stream"?NI(r):Dt.fromAsyncGenerator(r)}async*_streamEventsV2(t,e,n){const r=new M0({...n,autoClose:!1}),s=we(e),a=s.runId??Fn();s.runId=a;const i=s.callbacks;if(i===void 0)s.callbacks=[r];else if(Array.isArray(i))s.callbacks=i.concat(r);else{const h=i.copy();h.addHandler(r,!0),s.callbacks=h}const o=new AbortController,c=this;async function u(){let h,p=null;try{e?.signal?"any"in AbortSignal?h=AbortSignal.any([o.signal,e.signal]):(h=e.signal,p=()=>{o.abort()},e.signal.addEventListener("abort",p,{once:!0})):h=o.signal;const m=await c.stream(t,{...s,signal:h}),y=r.tapOutputIterable(a,m);for await(const v of y)if(o.signal.aborted)break}finally{await r.finish(),h&&p&&h.removeEventListener("abort",p)}}const l=u();let d=!1,f;try{for await(const h of r){if(!d){h.data.input=t,d=!0,f=h.run_id,yield h;continue}h.run_id===f&&h.event.endsWith("_end")&&h.data?.input&&delete h.data.input,yield h}}finally{o.abort(),await l}}async*_streamEventsV1(t,e,n){let r,s=!1;const a=we(e),i=a.tags??[],o=a.metadata??{},c=a.runName??this.getName(),u=new kc({...n,autoClose:!1,_schemaFormat:"streaming_events"}),l=new G0({...n}),d=this._streamLog(t,u,a);for await(const h of d){if(r?r=r.concat(h):r=Ac.fromRunLogPatch(h),r.state===void 0)throw new Error(\'Internal error: "streamEvents" state is missing. Please open a bug report.\');if(!s){s=!0;const v={...r.state},w={run_id:v.id,event:`on_${v.type}_start`,name:c,tags:i,metadata:o,data:{input:t}};l.includeEvent(w,v.type)&&(yield w)}const p=h.ops.filter(v=>v.path.startsWith("/logs/")).map(v=>v.path.split("/")[2]),m=[...new Set(p)];for(const v of m){let w,E={};const x=r.state.logs[v];if(x.end_time===void 0?x.streamed_output.length>0?w="stream":w="start":w="end",w==="start")x.inputs!==void 0&&(E.input=x.inputs);else if(w==="end")x.inputs!==void 0&&(E.input=x.inputs),E.output=x.final_output;else if(w==="stream"){const A=x.streamed_output.length;if(A!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${A} instead. Encountered in: "${x.name}"`);E={chunk:x.streamed_output[0]},x.streamed_output=[]}yield{event:`on_${x.type}_${w}`,name:x.name,run_id:x.id,tags:x.tags,metadata:x.metadata,data:E}}const{state:y}=r;if(y.streamed_output.length>0){const v=y.streamed_output.length;if(v!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${v} instead. Encountered in: "${y.name}"`);const w={chunk:y.streamed_output[0]};y.streamed_output=[];const E={event:`on_${y.type}_stream`,run_id:y.id,tags:i,metadata:o,name:c,data:w};l.includeEvent(E,y.type)&&(yield E)}}const f=r?.state;if(f!==void 0){const h={event:`on_${f.type}_end`,name:c,run_id:f.id,tags:i,metadata:o,data:{output:f.final_output}};l.includeEvent(h,f.type)&&(yield h)}}static isRunnable(t){return Cc(t)}withListeners({onStart:t,onEnd:e,onError:n}){return new yr({bound:this,config:{},configFactories:[r=>({callbacks:[new yf({config:r,onStart:t,onEnd:e,onError:n})]})]})}asTool(t){return zI(this,t)}},yr=class iy extends Pe{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(e){super(e),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){const n=la(this.config,...e);return la(n,...this.configFactories?await Promise.all(this.configFactories.map(async r=>await r(n))):[])}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new lu({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,n){return this.bound.invoke(e,await this._mergeConfig(n,this.kwargs))}async batch(e,n,r){const s=Array.isArray(n)?await Promise.all(n.map(async a=>this._mergeConfig(we(a),this.kwargs))):await this._mergeConfig(we(n),this.kwargs);return this.bound.batch(e,s,r)}_concatOutputChunks(e,n){return this.bound._concatOutputChunks(e,n)}async*_streamIterator(e,n){yield*this.bound._streamIterator(e,await this._mergeConfig(we(n),this.kwargs))}async stream(e,n){return this.bound.stream(e,await this._mergeConfig(we(n),this.kwargs))}async*transform(e,n){yield*this.bound.transform(e,await this._mergeConfig(we(n),this.kwargs))}streamEvents(e,n,r){const s=this,a=async function*(){yield*s.bound.streamEvents(e,{...await s._mergeConfig(we(n),s.kwargs),version:n.version},r)};return Dt.fromAsyncGenerator(a())}static isRunnableBinding(e){return e.bound&&Pe.isRunnable(e.bound)}withListeners({onStart:e,onEnd:n,onError:r}){return new iy({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[s=>({callbacks:[new yf({config:s,onStart:e,onEnd:n,onError:r})]})]})}},MI=class oy extends Pe{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(e){super(e),this.bound=e.bound}async invoke(e,n){return this._callWithConfig(this._invoke.bind(this),e,n)}async _invoke(e,n,r){return this.bound.batch(e,Ae(n,{callbacks:r?.getChild()}))}withListeners({onStart:e,onEnd:n,onError:r}){return new oy({bound:this.bound.withListeners({onStart:e,onEnd:n,onError:r})})}},lu=class extends yr{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(t){super(t),this.maxAttemptNumber=t.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=t.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(t,e,n){const r=t>1?`retry:attempt:${t}`:void 0;return Ae(e,{callbacks:n?.getChild(r)})}async _invoke(t,e,n){return $c(r=>super.invoke(t,this._patchConfigForRetry(r,e,n)),{onFailedAttempt:({error:r})=>this.onFailedAttempt(r,t),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(t,e){return this._callWithConfig(this._invoke.bind(this),t,e)}async _batch(t,e,n,r){const s={};try{await $c(async a=>{const i=t.map((d,f)=>f).filter(d=>s[d.toString()]===void 0||s[d.toString()]instanceof Error),o=i.map(d=>t[d]),c=i.map(d=>this._patchConfigForRetry(a,e?.[d],n?.[d])),u=await super.batch(o,c,{...r,returnExceptions:!0});let l;for(let d=0;d<u.length;d+=1){const f=u[d],h=i[d];f instanceof Error&&l===void 0&&(l=f,l.input=o[d]),s[h.toString()]=f}if(l)throw l;return u},{onFailedAttempt:({error:a})=>this.onFailedAttempt(a,a.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(a){if(r?.returnExceptions!==!0)throw a}return Object.keys(s).sort((a,i)=>parseInt(a,10)-parseInt(i,10)).map(a=>s[parseInt(a,10)])}async batch(t,e,n){return this._batchWithConfig(this._batch.bind(this),t,e,n)}},Na=class Cs extends Pe{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(e){super(e),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,n){const r=we(n),a=await(await wt(r))?.handleChainStart(this.toJSON(),He(e,"input"),r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;let i=e,o;try{const c=[this.first,...this.middle];for(let u=0;u<c.length;u+=1){const d=c[u].invoke(i,Ae(r,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${u+1}`)}));i=await ln(d,n?.signal)}if(n?.signal?.aborted)throw Wr(n.signal);o=await this.last.invoke(i,Ae(r,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(c){throw await a?.handleChainError(c),c}return await a?.handleChainEnd(He(o,"output")),o}async batch(e,n,r){const s=this._getOptionsList(n??{},e.length),a=await Promise.all(s.map(wt)),i=await Promise.all(a.map(async(c,u)=>{const l=await c?.handleChainStart(this.toJSON(),He(e[u],"input"),s[u].runId,void 0,void 0,void 0,s[u].runName);return delete s[u].runId,l}));let o=e;try{for(let c=0;c<this.steps.length;c+=1){const l=this.steps[c].batch(o,i.map((d,f)=>{const h=d?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return Ae(s[f],{callbacks:h})}),r);o=await ln(l,s[0]?.signal)}}catch(c){throw await Promise.all(i.map(u=>u?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(He(o,"output")))),o}_concatOutputChunks(e,n){return this.last._concatOutputChunks(e,n)}async*_streamIterator(e,n){const r=await wt(n),{runId:s,...a}=n??{},i=await r?.handleChainStart(this.toJSON(),He(e,"input"),s,void 0,void 0,void 0,a?.runName),o=[this.first,...this.middle,this.last];let c=!0,u;async function*l(){yield e}try{let d=o[0].transform(l(),Ae(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let f=1;f<o.length;f+=1)d=await o[f].transform(d,Ae(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${f+1}`)}));for await(const f of d)if(n?.signal?.throwIfAborted(),yield f,c)if(u===void 0)u=f;else try{u=this._concatOutputChunks(u,f)}catch{u=void 0,c=!1}}catch(d){throw await i?.handleChainError(d),d}await i?.handleChainEnd(He(u,"output"))}getGraph(e){const n=new ou;let r=null;return this.steps.forEach((s,a)=>{const i=s.getGraph(e);a!==0&&i.trimFirstNode(),a!==this.steps.length-1&&i.trimLastNode(),n.extend(i);const o=i.firstNode();if(!o)throw new Error(`Runnable ${s} has no first node`);r&&n.addEdge(r,o),r=i.lastNode()}),n}pipe(e){return Cs.isRunnableSequence(e)?new Cs({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new Cs({first:this.first,middle:[...this.middle,this.last],last:Zt(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&Pe.isRunnable(e)}static from([e,...n],r){let s={};return typeof r=="string"?s.name=r:r!==void 0&&(s=r),new Cs({...s,first:Zt(e),middle:n.slice(0,-1).map(Zt),last:Zt(n[n.length-1])})}},wr=class cy extends Pe{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),this.steps={};for(const[n,r]of Object.entries(e.steps))this.steps[n]=Zt(r)}static from(e){return new cy({steps:e})}async invoke(e,n){const r=we(n),a=await(await wt(r))?.handleChainStart(this.toJSON(),{input:e},r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;const i={};try{const o=Object.entries(this.steps).map(async([c,u])=>{i[c]=await u.invoke(e,Ae(r,{callbacks:a?.getChild(`map:key:${c}`)}))});await ln(Promise.all(o),n?.signal)}catch(o){throw await a?.handleChainError(o),o}return await a?.handleChainEnd(i),i}async*_transform(e,n,r){const s={...this.steps},a=bc(e,Object.keys(s).length),i=new Map(Object.entries(s).map(([o,c],u)=>{const l=c.transform(a[u],Ae(r,{callbacks:n?.getChild(`map:key:${o}`)}));return[o,l.next().then(d=>({key:o,gen:l,result:d}))]}));for(;i.size;){const o=Promise.race(i.values()),{key:c,result:u,gen:l}=await ln(o,r?.signal);i.delete(c),u.done||(yield{[c]:u.value},i.set(c,l.next().then(d=>({key:c,gen:l,result:d}))))}}transform(e,n){return this._transformStreamWithConfig(e,this._transform.bind(this),n)}async stream(e,n){async function*r(){yield e}const s=we(n),a=new Bn({generator:this.transform(r(),s),config:s});return await a.setup,Dt.fromAsyncGenerator(a)}},LI=class uy extends Pe{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(e){if(super(e),!_c(e.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,n){const[r]=this._getOptionsList(n??{},1),s=await wt(r),a=this.func(Ae(r,{callbacks:s}),e);return ln(a,r?.signal)}async*_streamIterator(e,n){const[r]=this._getOptionsList(n??{},1),s=await this.invoke(e,n);if(cu(s)){for await(const a of s)r?.signal?.throwIfAborted(),yield a;return}if(PI(s)){for(;;){r?.signal?.throwIfAborted();const a=s.next();if(a.done)break;yield a.value}return}yield s}static from(e){return new uy({func:e})}};function jI(t){if(_c(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn\'t happen.")}var Pn=class ly extends Pe{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(e){if(_c(e.func))return LI.from(e.func);super(e),jI(e.func),this.func=e.func}static from(e){return new ly({func:e})}async _invoke(e,n,r){return new Promise((s,a)=>{const i=Ae(n,{callbacks:r?.getChild(),recursionLimit:(n?.recursionLimit??wc)-1});jt.runWithConfig(un(i),async()=>{try{let o=await this.func(e,{...i});if(o&&Pe.isRunnable(o)){if(n?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(e,{...i,recursionLimit:(i.recursionLimit??wc)-1})}else if(cu(o)){let c;for await(const u of uu(i,o))if(n?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}o=c}else if(Jp(o)){let c;for(const u of Kp(i,o))if(n?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}o=c}s(o)}catch(o){a(o)}})})}async invoke(e,n){return this._callWithConfig(this._invoke.bind(this),e,n)}async*_transform(e,n,r){let s;for await(const o of e)if(s===void 0)s=o;else try{s=this._concatOutputChunks(s,o)}catch{s=o}const a=Ae(r,{callbacks:n?.getChild(),recursionLimit:(r?.recursionLimit??wc)-1}),i=await new Promise((o,c)=>{jt.runWithConfig(un(a),async()=>{try{const u=await this.func(s,{...a,config:a});o(u)}catch(u){c(u)}})});if(i&&Pe.isRunnable(i)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");const o=await i.stream(s,a);for await(const c of o)yield c}else if(cu(i))for await(const o of uu(a,i))r?.signal?.throwIfAborted(),yield o;else if(Jp(i))for(const o of Kp(a,i))r?.signal?.throwIfAborted(),yield o;else yield i}transform(e,n){return this._transformStreamWithConfig(e,this._transform.bind(this),n)}async stream(e,n){async function*r(){yield e}const s=we(n),a=new Bn({generator:this.transform(r(),s),config:s});return await a.setup,Dt.fromAsyncGenerator(a)}},DI=class extends wr{},Xp=class extends Pe{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(t){super(t),this.runnable=t.runnable,this.fallbacks=t.fallbacks}*runnables(){yield this.runnable;for(const t of this.fallbacks)yield t}async invoke(t,e){const n=we(e),r=await wt(n),{runId:s,...a}=n,i=await r?.handleChainStart(this.toJSON(),He(t,"input"),s,void 0,void 0,void 0,a?.runName),o=Ae(a,{callbacks:i?.getChild()});return await jt.runWithConfig(o,async()=>{let u;for(const l of this.runnables()){n?.signal?.throwIfAborted();try{const d=await l.invoke(t,o);return await i?.handleChainEnd(He(d,"output")),d}catch(d){u===void 0&&(u=d)}}throw u===void 0?new Error("No error stored at end of fallback."):(await i?.handleChainError(u),u)})}async*_streamIterator(t,e){const n=we(e),r=await wt(n),{runId:s,...a}=n,i=await r?.handleChainStart(this.toJSON(),He(t,"input"),s,void 0,void 0,void 0,a?.runName);let o,c;for(const l of this.runnables()){n?.signal?.throwIfAborted();const d=Ae(a,{callbacks:i?.getChild()});try{const f=await l.stream(t,d);c=uu(d,f);break}catch(f){o===void 0&&(o=f)}}if(c===void 0){const l=o??new Error("No error stored at end of fallback.");throw await i?.handleChainError(l),l}let u;try{for await(const l of c){yield l;try{u=u===void 0?u:this._concatOutputChunks(u,l)}catch{u=void 0}}}catch(l){throw await i?.handleChainError(l),l}await i?.handleChainEnd(He(u,"output"))}async batch(t,e,n){if(n?.returnExceptions)throw new Error("Not implemented.");const r=this._getOptionsList(e??{},t.length),s=await Promise.all(r.map(o=>wt(o))),a=await Promise.all(s.map(async(o,c)=>{const u=await o?.handleChainStart(this.toJSON(),He(t[c],"input"),r[c].runId,void 0,void 0,void 0,r[c].runName);return delete r[c].runId,u}));let i;for(const o of this.runnables()){r[0].signal?.throwIfAborted();try{const c=await o.batch(t,a.map((u,l)=>Ae(r[l],{callbacks:u?.getChild()})),n);return await Promise.all(a.map((u,l)=>u?.handleChainEnd(He(c[l],"output")))),c}catch(c){i===void 0&&(i=c)}}throw i?(await Promise.all(a.map(o=>o?.handleChainError(i))),i):new Error("No error stored at end of fallbacks.")}};function Zt(t){if(typeof t=="function")return new Pn({func:t});if(Pe.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){const e={};for(const[n,r]of Object.entries(t))e[n]=Zt(r);return new wr({steps:e})}else throw new Error(`Expected a Runnable, function or object.\nInstead got an unsupported type.`)}var du=class extends Pe{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(t){t instanceof wr&&(t={mapper:t}),super(t),this.mapper=t.mapper}async invoke(t,e){const n=await this.mapper.invoke(t,e);return{...t,...n}}async*_transform(t,e,n){const r=this.mapper.getStepsKeys(),[s,a]=bc(t),i=this.mapper.transform(a,Ae(n,{callbacks:e?.getChild()})),o=i.next();for await(const c of s){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);const u=Object.fromEntries(Object.entries(c).filter(([l])=>!r.includes(l)));Object.keys(u).length>0&&(yield u)}yield(await o).value;for await(const c of i)yield c}transform(t,e){return this._transformStreamWithConfig(t,this._transform.bind(this),e)}async stream(t,e){async function*n(){yield t}const r=we(e),s=new Bn({generator:this.transform(n(),r),config:r});return await s.setup,Dt.fromAsyncGenerator(s)}},Yp=class extends Pe{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(t){(typeof t=="string"||Array.isArray(t))&&(t={keys:t}),super(t),this.keys=t.keys}async _pick(t){if(typeof this.keys=="string")return t[this.keys];{const e=this.keys.map(n=>[n,t[n]]).filter(n=>n[1]!==void 0);return e.length===0?void 0:Object.fromEntries(e)}}async invoke(t,e){return this._callWithConfig(this._pick.bind(this),t,e)}async*_transform(t){for await(const e of t){const n=await this._pick(e);n!==void 0&&(yield n)}}transform(t,e){return this._transformStreamWithConfig(t,this._transform.bind(this),e)}async stream(t,e){async function*n(){yield t}const r=we(e),s=new Bn({generator:this.transform(n(),r),config:r});return await s.setup,Dt.fromAsyncGenerator(s)}},hu=class extends yr{name;description;schema;constructor(t){const e=Na.from([Pn.from(async n=>{let r;if(Cr(n))try{r=await Ea(this.schema,n.args)}catch{throw new js("Received tool input did not match expected schema",JSON.stringify(n.args))}else r=n;return r}).withConfig({runName:`${t.name}:parse_input`}),t.bound]).withConfig({runName:t.name});super({bound:e,config:t.config??{}}),this.name=t.name,this.description=t.description,this.schema=t.schema}static lc_name(){return"RunnableToolLike"}};function zI(t,e){const n=e.name??t.getName(),r=e.description??Zc(e.schema);return qc(e.schema)?new hu({name:n,description:r,schema:Ca({input:$a()}).transform(s=>s.input),bound:t}):new hu({name:n,description:r,schema:e.schema,bound:t})}var Qp=class extends Pe{lc_namespace=["langchain_core","documents","transformers"];invoke(t,e){return this.transformDocuments(t)}},FI=class extends Qp{async transformDocuments(t){const e=[];for(const n of t){const r=await this._transformDocument(n);e.push(r)}return e}},UI={};ge(UI,{BaseDocumentTransformer:()=>Qp,Document:()=>jn,MappingDocumentTransformer:()=>FI});function BI(t,e){let n=0,r=0,s=0;for(let a=0;a<t.length;a++)n+=t[a]*e[a],r+=t[a]*t[a],s+=e[a]*e[a];return n/(Math.sqrt(r)*Math.sqrt(s))}function ZI(t,e){let n=0;for(let r=0;r<t.length;r++)n+=t[r]*e[r];return n}function qI(t,e){let n=0;for(let r=0;r<t.length;r++)n+=(t[r]-e[r])*(t[r]-e[r]);return n}function VI(t,e){return Math.sqrt(qI(t,e))}var HI={};ge(HI,{cosineSimilarity:()=>fu,euclideanDistance:()=>JI,innerProduct:()=>WI,matrixFunc:()=>Pa,maximalMarginalRelevance:()=>em,normalize:()=>GI});function Pa(t,e,n){if(t.length===0||t[0].length===0||e.length===0||e[0].length===0)return[[]];if(t[0].length!==e[0].length)throw new Error(`Number of columns in X and Y must be the same. X has shape ${[t.length,t[0].length]} and Y has shape ${[e.length,e[0].length]}.`);return t.map(r=>e.map(s=>n(r,s)).map(s=>Number.isNaN(s)?0:s))}function GI(t,e=!1){const n=KI(t);return t.map(r=>r.map(s=>e?1-s/n:s/n))}function fu(t,e){return Pa(t,e,BI)}function WI(t,e){return Pa(t,e,ZI)}function JI(t,e){return Pa(t,e,VI)}function em(t,e,n=.5,r=4){if(Math.min(r,e.length)<=0)return[];const s=Array.isArray(t[0])?t:[t],a=fu(s,e)[0],i=tm(a).maxIndex,o=[e[i]],c=[i];for(;c.length<Math.min(r,e.length);){let u=-1/0,l=-1;const d=fu(e,o);a.forEach((f,h)=>{if(c.includes(h))return;const p=Math.max(...d[h]),m=n*f-(1-n)*p;m>u&&(u=m,l=h)}),o.push(e[l]),c.push(l)}return c}function tm(t){if(t.length===0)return{maxIndex:-1,maxValue:NaN};let e=t[0],n=0;for(let r=1;r<t.length;r+=1)t[r]>e&&(n=r,e=t[r]);return{maxIndex:n,maxValue:e}}function KI(t){return t.reduce((e,n)=>Math.max(e,tm(n).maxValue),0)}var XI={};ge(XI,{BaseRetriever:()=>nm});var nm=class extends Pe{callbacks;tags;metadata;verbose;constructor(t){super(t),this.callbacks=t?.callbacks,this.tags=t?.tags??[],this.metadata=t?.metadata??{},this.verbose=t?.verbose??!1}_getRelevantDocuments(t,e){throw new Error("Not implemented!")}async invoke(t,e){const n=we(Vr(e)),s=await(await lt.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),t,n.runId,void 0,void 0,void 0,n.runName);try{const a=await this._getRelevantDocuments(t,s);return await s?.handleRetrieverEnd(a),a}catch(a){throw await s?.handleRetrieverError(a),a}}},YI={};ge(YI,{SaveableVectorStore:()=>QI,VectorStore:()=>pu,VectorStoreRetriever:()=>Ma});var Ma=class extends nm{static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}vectorStore;k=4;searchType="similarity";searchKwargs;filter;_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(t){super(t),this.vectorStore=t.vectorStore,this.k=t.k??this.k,this.searchType=t.searchType??this.searchType,this.filter=t.filter,t.searchType==="mmr"&&(this.searchKwargs=t.searchKwargs)}async _getRelevantDocuments(t,e){if(this.searchType==="mmr"){if(typeof this.vectorStore.maxMarginalRelevanceSearch!="function")throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(t,{k:this.k,filter:this.filter,...this.searchKwargs},e?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(t,this.k,this.filter,e?.getChild("vectorstore"))}async addDocuments(t,e){return this.vectorStore.addDocuments(t,e)}},pu=class extends Dn{lc_namespace=["langchain","vectorstores",this._vectorstoreType()];embeddings;constructor(t,e){super(e),this.embeddings=t}async delete(t){throw new Error("Not implemented.")}async similaritySearch(t,e=4,n=void 0,r=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(t),e,n)).map(a=>a[0])}async similaritySearchWithScore(t,e=4,n=void 0,r=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(t),e,n)}static fromTexts(t,e,n,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(t,e,n){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(t,e,n,r,s,a){if(typeof t=="number")return new Ma({vectorStore:this,k:t,filter:e,tags:[...r??[],this._vectorstoreType()],metadata:s,verbose:a,callbacks:n});{const i={vectorStore:this,k:t?.k,filter:t?.filter,tags:[...t?.tags??[],this._vectorstoreType()],metadata:t?.metadata,verbose:t?.verbose,callbacks:t?.callbacks,searchType:t?.searchType};return t?.searchType==="mmr"?new Ma({...i,searchKwargs:t.searchKwargs}):new Ma({...i})}}},QI=class extends pu{static load(t,e){throw new Error("Not implemented")}},eA={};py(eA,{MemoryVectorStore:()=>mu});var mu=class dy extends pu{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(e,{similarity:n,...r}={}){super(e,r),this.similarity=n??my}async addDocuments(e){const n=e.map(({pageContent:r})=>r);return this.addVectors(await this.embeddings.embedDocuments(n),e)}async addVectors(e,n){const r=e.map((s,a)=>({content:n[a].pageContent,embedding:s,metadata:n[a].metadata,id:n[a].id}));this.memoryVectors=this.memoryVectors.concat(r)}async _queryVectors(e,n,r){const s=i=>{if(!r)return!0;const o=new jn({metadata:i.metadata,pageContent:i.content,id:i.id});return r(o)};return this.memoryVectors.filter(s).map((i,o)=>({similarity:this.similarity(e,i.embedding),index:o,metadata:i.metadata,content:i.content,embedding:i.embedding,id:i.id})).sort((i,o)=>i.similarity>o.similarity?-1:0).slice(0,n)}async similaritySearchVectorWithScore(e,n,r){return(await this._queryVectors(e,n,r)).map(i=>[new jn({metadata:i.metadata,pageContent:i.content,id:i.id}),i.similarity])}async maxMarginalRelevanceSearch(e,n){const r=await this.embeddings.embedQuery(e),s=await this._queryVectors(r,n.fetchK??20,n.filter),a=s.map(o=>o.embedding);return em(r,a,n.lambda,n.k).map(o=>new jn({metadata:s[o].metadata,pageContent:s[o].content,id:s[o].id}))}static async fromTexts(e,n,r,s){const a=[];for(let i=0;i<e.length;i+=1){const o=Array.isArray(n)?n[i]:n,c=new jn({pageContent:e[i],metadata:o});a.push(c)}return dy.fromDocuments(a,r,s)}static async fromDocuments(e,n,r){const s=new this(n,r);return await s.addDocuments(e),s}static async fromExistingIndex(e,n){return new this(e,n)}};function La(t,e){return t.lc_error_code=e,t.message=`${t.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/\n`,t}function re(t,e,n,r,s){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}function T(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)}let rm=function(){const{crypto:t}=globalThis;if(t?.randomUUID)return rm=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))};function gu(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const _u=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class ee extends Error{}class Qe extends ee{constructor(e,n,r,s){super(`${Qe.makeMessage(e,n,r)}`),this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=n;const a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,n,r){const s=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,n,r,s){if(!e||!s)return new ja({message:r,cause:_u(n)});const a=n?.error;return e===400?new sm(e,a,r,s):e===401?new am(e,a,r,s):e===403?new im(e,a,r,s):e===404?new om(e,a,r,s):e===409?new cm(e,a,r,s):e===422?new um(e,a,r,s):e===429?new lm(e,a,r,s):e>=500?new dm(e,a,r,s):new Qe(e,a,r,s)}}class Et extends Qe{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class ja extends Qe{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class Da extends ja{constructor({message:e}={}){super({message:e??"Request timed out."})}}class sm extends Qe{}class am extends Qe{}class im extends Qe{}class om extends Qe{}class cm extends Qe{}class um extends Qe{}class lm extends Qe{}class dm extends Qe{}class hm extends ee{constructor(){super("Could not parse response content as the length limit was reached")}}class fm extends ee{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class cs extends Error{constructor(e){super(e)}}const tA=/^[a-z][a-z0-9+.-]*:/i,nA=t=>tA.test(t);let gt=t=>(gt=Array.isArray,gt(t)),pm=gt;function mm(t){return typeof t!="object"?{}:t??{}}function rA(t){if(!t)return!0;for(const e in t)return!1;return!0}function sA(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function yu(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}const aA=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ee(`${t} must be an integer`);if(e<0)throw new ee(`${t} must be a positive integer`);return e},iA=t=>{try{return JSON.parse(t)}catch{return}},us=t=>new Promise(e=>setTimeout(e,t)),br="6.16.0",oA=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function cA(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const uA=()=>{const t=cA();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":br,"X-Stainless-OS":_m(Deno.build.os),"X-Stainless-Arch":gm(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":br,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":br,"X-Stainless-OS":_m(globalThis.process.platform??"unknown"),"X-Stainless-Arch":gm(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=lA();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":br,"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":br,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function lA(){if(typeof navigator>"u"||!navigator)return null;const t=[{key:"edge",pattern:/Edge(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/},{key:"ie",pattern:/MSIE(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\\:(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/},{key:"safari",pattern:/(?:Version\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?(?:\\W+Mobile\\S*)?\\W+Safari/}];for(const{key:e,pattern:n}of t){const r=n.exec(navigator.userAgent);if(r){const s=r[1]||0,a=r[2]||0,i=r[3]||0;return{browser:e,version:`${s}.${a}.${i}`}}}return null}const gm=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",_m=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let ym;const dA=()=>ym??(ym=uA());function hA(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function wm(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function bm(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return wm({start(){},async pull(n){const{done:r,value:s}=await e.next();r?n.close():n.enqueue(s)},async cancel(){await e.return?.()}})}function vm(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){const n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function fA(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}const e=t.getReader(),n=e.cancel();e.releaseLock(),await n}const pA=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),Em="RFC3986",Sm=t=>String(t),Tm={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:Sm},mA="RFC1738";let wu=(t,e)=>(wu=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),wu(t,e));const en=(()=>{const t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})(),bu=1024,gA=(t,e,n,r,s)=>{if(t.length===0)return t;let a=t;if(typeof t=="symbol"?a=Symbol.prototype.toString.call(t):typeof t!="string"&&(a=String(t)),n==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let i="";for(let o=0;o<a.length;o+=bu){const c=a.length>=bu?a.slice(o,o+bu):a,u=[];for(let l=0;l<c.length;++l){let d=c.charCodeAt(l);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||s===mA&&(d===40||d===41)){u[u.length]=c.charAt(l);continue}if(d<128){u[u.length]=en[d];continue}if(d<2048){u[u.length]=en[192|d>>6]+en[128|d&63];continue}if(d<55296||d>=57344){u[u.length]=en[224|d>>12]+en[128|d>>6&63]+en[128|d&63];continue}l+=1,d=65536+((d&1023)<<10|c.charCodeAt(l)&1023),u[u.length]=en[240|d>>18]+en[128|d>>12&63]+en[128|d>>6&63]+en[128|d&63]}i+=u.join("")}return i};function _A(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function xm(t,e){if(gt(t)){const n=[];for(let r=0;r<t.length;r+=1)n.push(e(t[r]));return n}return e(t)}const Im={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Am=function(t,e){Array.prototype.push.apply(t,gt(e)?e:[e])};let km;const Ge={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:gA,encodeValuesOnly:!1,format:Em,formatter:Sm,indices:!1,serializeDate(t){return(km??(km=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function yA(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}const vu={};function Om(t,e,n,r,s,a,i,o,c,u,l,d,f,h,p,m,y,v){let w=t,E=v,x=0,A=!1;for(;(E=E.get(vu))!==void 0&&!A;){const ue=E.get(t);if(x+=1,typeof ue<"u"){if(ue===x)throw new RangeError("Cyclic object value");A=!0}typeof E.get(vu)>"u"&&(x=0)}if(typeof u=="function"?w=u(e,w):w instanceof Date?w=f?.(w):n==="comma"&&gt(w)&&(w=xm(w,function(ue){return ue instanceof Date?f?.(ue):ue})),w===null){if(a)return c&&!m?c(e,Ge.encoder,y,"key",h):e;w=""}if(yA(w)||_A(w)){if(c){const ue=m?e:c(e,Ge.encoder,y,"key",h);return[p?.(ue)+"="+p?.(c(w,Ge.encoder,y,"value",h))]}return[p?.(e)+"="+p?.(String(w))]}const N=[];if(typeof w>"u")return N;let j;if(n==="comma"&&gt(w))m&&c&&(w=xm(w,c)),j=[{value:w.length>0?w.join(",")||null:void 0}];else if(gt(u))j=u;else{const ue=Object.keys(w);j=l?ue.sort(l):ue}const b=o?String(e).replace(/\\./g,"%2E"):String(e),oe=r&&gt(w)&&w.length===1?b+"[]":b;if(s&&gt(w)&&w.length===0)return oe+"[]";for(let ue=0;ue<j.length;++ue){const X=j[ue],Be=typeof X=="object"&&typeof X.value<"u"?X.value:w[X];if(i&&Be===null)continue;const kt=d&&o?X.replace(/\\./g,"%2E"):X,L=gt(w)?typeof n=="function"?n(oe,kt):oe:oe+(d?"."+kt:"["+kt+"]");v.set(t,x);const R=new WeakMap;R.set(vu,v),Am(N,Om(Be,L,n,r,s,a,i,o,n==="comma"&&m&&gt(w)?null:c,u,l,d,f,h,p,m,y,R))}return N}function wA(t=Ge){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=t.charset||Ge.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=Em;if(typeof t.format<"u"){if(!wu(Tm,t.format))throw new TypeError("Unknown format option provided.");n=t.format}const r=Tm[n];let s=Ge.filter;(typeof t.filter=="function"||gt(t.filter))&&(s=t.filter);let a;if(t.arrayFormat&&t.arrayFormat in Im?a=t.arrayFormat:"indices"in t?a=t.indices?"indices":"repeat":a=Ge.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:Ge.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:Ge.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:Ge.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:Ge.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?Ge.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:Ge.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:Ge.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:Ge.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:Ge.encodeValuesOnly,filter:s,format:n,formatter:r,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:Ge.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:Ge.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:Ge.strictNullHandling}}function bA(t,e={}){let n=t;const r=wA(e);let s,a;typeof r.filter=="function"?(a=r.filter,n=a("",n)):gt(r.filter)&&(a=r.filter,s=a);const i=[];if(typeof n!="object"||n===null)return"";const o=Im[r.arrayFormat],c=o==="comma"&&r.commaRoundTrip;s||(s=Object.keys(n)),r.sort&&s.sort(r.sort);const u=new WeakMap;for(let f=0;f<s.length;++f){const h=s[f];r.skipNulls&&n[h]===null||Am(i,Om(n[h],h,o,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,u))}const l=i.join(r.delimiter);let d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),l.length>0?d+l:""}function vA(t){let e=0;for(const s of t)e+=s.length;const n=new Uint8Array(e);let r=0;for(const s of t)n.set(s,r),r+=s.length;return n}let $m;function Eu(t){let e;return($m??(e=new globalThis.TextEncoder,$m=e.encode.bind(e)))(t)}let Cm;function Rm(t){let e;return(Cm??(e=new globalThis.TextDecoder,Cm=e.decode.bind(e)))(t)}var St,Tt;class za{constructor(){St.set(this,void 0),Tt.set(this,void 0),re(this,St,new Uint8Array),re(this,Tt,null)}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Eu(e):e;re(this,St,vA([T(this,St,"f"),n]));const r=[];let s;for(;(s=EA(T(this,St,"f"),T(this,Tt,"f")))!=null;){if(s.carriage&&T(this,Tt,"f")==null){re(this,Tt,s.index);continue}if(T(this,Tt,"f")!=null&&(s.index!==T(this,Tt,"f")+1||s.carriage)){r.push(Rm(T(this,St,"f").subarray(0,T(this,Tt,"f")-1))),re(this,St,T(this,St,"f").subarray(T(this,Tt,"f"))),re(this,Tt,null);continue}const a=T(this,Tt,"f")!==null?s.preceding-1:s.preceding,i=Rm(T(this,St,"f").subarray(0,a));r.push(i),re(this,St,T(this,St,"f").subarray(s.index)),re(this,Tt,null)}return r}flush(){return T(this,St,"f").length?this.decode(`\n`):[]}}St=new WeakMap,Tt=new WeakMap,za.NEWLINE_CHARS=new Set([`\n`,"\\r"]),za.NEWLINE_REGEXP=/\\r\\n|[\\n\\r]/g;function EA(t,e){for(let s=e??0;s<t.length;s++){if(t[s]===10)return{preceding:s,index:s+1,carriage:!1};if(t[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function SA(t){for(let r=0;r<t.length-1;r++){if(t[r]===10&&t[r+1]===10||t[r]===13&&t[r+1]===13)return r+2;if(t[r]===13&&t[r+1]===10&&r+3<t.length&&t[r+2]===13&&t[r+3]===10)return r+4}return-1}const Fa={off:0,error:200,warn:300,info:400,debug:500},Nm=(t,e,n)=>{if(t){if(sA(Fa,t))return t;et(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(Fa))}`)}};function ls(){}function Ua(t,e,n){return!e||Fa[t]>Fa[n]?ls:e[t].bind(e)}const TA={error:ls,warn:ls,info:ls,debug:ls};let Pm=new WeakMap;function et(t){const e=t.logger,n=t.logLevel??"off";if(!e)return TA;const r=Pm.get(e);if(r&&r[0]===n)return r[1];const s={error:Ua("error",e,n),warn:Ua("warn",e,n),info:Ua("info",e,n),debug:Ua("debug",e,n)};return Pm.set(e,[n,s]),s}const Wn=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var ds;class tn{constructor(e,n,r){this.iterator=e,ds.set(this,void 0),this.controller=n,re(this,ds,r)}static fromSSEResponse(e,n,r){let s=!1;const a=r?et(r):console;async function*i(){if(s)throw new ee("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(const c of xA(e,n))if(!o){if(c.data.startsWith("[DONE]")){o=!0;continue}if(c.event===null||!c.event.startsWith("thread.")){let u;try{u=JSON.parse(c.data)}catch(l){throw a.error("Could not parse message into JSON:",c.data),a.error("From chunk:",c.raw),l}if(u&&u.error)throw new Qe(void 0,u.error,void 0,e.headers);yield u}else{let u;try{u=JSON.parse(c.data)}catch(l){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),l}if(c.event=="error")throw new Qe(void 0,u.error,u.message,void 0);yield{event:c.event,data:u}}}o=!0}catch(c){if(gu(c))return;throw c}finally{o||n.abort()}}return new tn(i,n,r)}static fromReadableStream(e,n,r){let s=!1;async function*a(){const o=new za,c=vm(e);for await(const u of c)for(const l of o.decode(u))yield l;for(const u of o.flush())yield u}async function*i(){if(s)throw new ee("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(const c of a())o||c&&(yield JSON.parse(c));o=!0}catch(c){if(gu(c))return;throw c}finally{o||n.abort()}}return new tn(i,n,r)}[(ds=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],n=[],r=this.iterator(),s=a=>({next:()=>{if(a.length===0){const i=r.next();e.push(i),n.push(i)}return a.shift()}});return[new tn(()=>s(e),this.controller,T(this,ds,"f")),new tn(()=>s(n),this.controller,T(this,ds,"f"))]}toReadableStream(){const e=this;let n;return wm({async start(){n=e[Symbol.asyncIterator]()},async pull(r){try{const{value:s,done:a}=await n.next();if(a)return r.close();const i=Eu(JSON.stringify(s)+`\n`);r.enqueue(i)}catch(s){r.error(s)}},async cancel(){await n.return?.()}})}}async function*xA(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ee("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new ee("Attempted to iterate over a response with no body");const n=new AA,r=new za,s=vm(t.body);for await(const a of IA(s))for(const i of r.decode(a)){const o=n.decode(i);o&&(yield o)}for(const a of r.flush()){const i=n.decode(a);i&&(yield i)}}async function*IA(t){let e=new Uint8Array;for await(const n of t){if(n==null)continue;const r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?Eu(n):n;let s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let a;for(;(a=SA(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class AA{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const a={event:this.event,data:this.data.join(`\n`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,s]=kA(e,":");return s.startsWith(" ")&&(s=s.substring(1)),n==="event"?this.event=s:n==="data"&&this.data.push(s),null}}function kA(t,e){const n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}async function Mm(t,e){const{response:n,requestLogID:r,retryOfRequestLogID:s,startTime:a}=e,i=await(async()=>{if(e.options.stream)return et(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller,t):tn.fromSSEResponse(n,e.controller,t);if(n.status===204)return null;if(e.options.__binaryResponse)return n;const c=n.headers.get("content-type")?.split(";")[0]?.trim();if(c?.includes("application/json")||c?.endsWith("+json")){const d=await n.json();return Lm(d,n)}return await n.text()})();return et(t).debug(`[${r}] response parsed`,Wn({retryOfRequestLogID:s,url:n.url,status:n.status,body:i,durationMs:Date.now()-a})),i}function Lm(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var hs;class Ba extends Promise{constructor(e,n,r=Mm){super(s=>{s(null)}),this.responsePromise=n,this.parseResponse=r,hs.set(this,void 0),re(this,hs,e)}_thenUnwrap(e){return new Ba(T(this,hs,"f"),this.responsePromise,async(n,r)=>Lm(e(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(T(this,hs,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}hs=new WeakMap;var Za;class Su{constructor(e,n,r,s){Za.set(this,void 0),re(this,Za,e),this.options=s,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new ee("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await T(this,Za,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Za=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const n of e.getPaginatedItems())yield n}}class OA extends Ba{constructor(e,n,r){super(e,n,async(s,a)=>new r(s,a.response,await Mm(s,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const n of e)yield n}}class qa extends Su{constructor(e,n,r,s){super(e,n,r,s),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class Ue extends Su{constructor(e,n,r,s){super(e,n,r,s),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.getPaginatedItems(),n=e[e.length-1]?.id;return n?{...this.options,query:{...mm(this.options.query),after:n}}:null}}class Va extends Su{constructor(e,n,r,s){super(e,n,r,s),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.last_id;return e?{...this.options,query:{...mm(this.options.query),after:e}}:null}}const jm=()=>{if(typeof File>"u"){const{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import(\'node:buffer\').File`.":""))}};function fs(t,e,n){return jm(),new File(t,e??"unknown_file",n)}function Ha(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\\\/]/).pop()||void 0}const Tu=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Dm=async(t,e)=>xu(t.body)?{...t,body:await Fm(t.body,e)}:t,Jn=async(t,e)=>({...t,body:await Fm(t.body,e)}),zm=new WeakMap;function $A(t){const e=typeof t=="function"?t:t.fetch,n=zm.get(e);if(n)return n;const r=(async()=>{try{const s="Response"in e?e.Response:(await e("data:,")).constructor,a=new FormData;return a.toString()!==await new s(a).text()}catch{return!0}})();return zm.set(e,r),r}const Fm=async(t,e)=>{if(!await $A(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const n=new FormData;return await Promise.all(Object.entries(t||{}).map(([r,s])=>Iu(n,r,s))),n},Um=t=>t instanceof Blob&&"name"in t,CA=t=>typeof t=="object"&&t!==null&&(t instanceof Response||Tu(t)||Um(t)),xu=t=>{if(CA(t))return!0;if(Array.isArray(t))return t.some(xu);if(t&&typeof t=="object"){for(const e in t)if(xu(t[e]))return!0}return!1},Iu=async(t,e,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string \'null\'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response)t.append(e,fs([await n.blob()],Ha(n)));else if(Tu(n))t.append(e,fs([await new Response(bm(n)).blob()],Ha(n)));else if(Um(n))t.append(e,n,Ha(n));else if(Array.isArray(n))await Promise.all(n.map(r=>Iu(t,e+"[]",r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([r,s])=>Iu(t,`${e}[${r}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},Bm=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",RA=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Bm(t),NA=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function PA(t,e,n){if(jm(),t=await t,RA(t))return t instanceof File?t:fs([await t.arrayBuffer()],t.name);if(NA(t)){const s=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\\\/]/).pop()),fs(await Au(s),e,n)}const r=await Au(t);if(e||(e=Ha(t)),!n?.type){const s=r.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof s=="string"&&(n={...n,type:s})}return fs(r,e,n)}async function Au(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Bm(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Tu(t))for await(const n of t)e.push(...await Au(n));else{const n=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${n?`; constructor: ${n}`:""}${MA(t)}`)}return e}function MA(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}class K{constructor(e){this._client=e}}function Zm(t){return t.replace(/[^A-Za-z0-9\\-._~!$&\'()*+,;=:@]+/g,encodeURIComponent)}const qm=Object.freeze(Object.create(null)),O=((t=Zm)=>function(n,...r){if(n.length===1)return n[0];let s=!1;const a=[],i=n.reduce((l,d,f)=>{/[?#]/.test(d)&&(s=!0);const h=r[f];let p=(s?encodeURIComponent:t)(""+h);return f!==r.length&&(h==null||typeof h=="object"&&h.toString===Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??qm)??qm)?.toString)&&(p=h+"",a.push({start:l.length+d.length,length:p.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),l+d+(f===r.length?"":p)},""),o=i.split(/[?#]/,1)[0],c=/(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)/gi;let u;for(;(u=c.exec(o))!==null;)a.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can\'t be safely passed as a path parameter`});if(a.sort((l,d)=>l.start-d.start),a.length>0){let l=0;const d=a.reduce((f,h)=>{const p=" ".repeat(h.start-l),m="^".repeat(h.length);return l=h.start+h.length,f+p+m},"");throw new ee(`Path parameters result in path with invalid segments:\n${a.map(f=>f.error).join(`\n`)}\n${i}\n${d}`)}return i})(Zm);let Vm=class extends K{list(e,n={},r){return this._client.getAPIList(O`/chat/completions/${e}/messages`,Ue,{query:n,...r})}};function Ga(t){return t!==void 0&&"function"in t&&t.function!==void 0}function ku(t){return t?.$brand==="auto-parseable-response-format"}function ps(t){return t?.$brand==="auto-parseable-tool"}function LA(t,e){return!e||!Hm(e)?{...t,choices:t.choices.map(n=>(Gm(n.message.tool_calls),{...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:Ou(t,e)}function Ou(t,e){const n=t.choices.map(r=>{if(r.finish_reason==="length")throw new hm;if(r.finish_reason==="content_filter")throw new fm;return Gm(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(s=>DA(e,s))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?jA(e,r.message.content):null}}});return{...t,choices:n}}function jA(t,e){return t.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function DA(t,e){const n=t.tools?.find(r=>Ga(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:ps(n)?n.$parseRaw(e.function.arguments):n?.function.strict?JSON.parse(e.function.arguments):null}}}function zA(t,e){if(!t||!("tools"in t)||!t.tools)return!1;const n=t.tools?.find(r=>Ga(r)&&r.function?.name===e.function.name);return Ga(n)&&(ps(n)||n?.function.strict||!1)}function Hm(t){return ku(t.response_format)?!0:t.tools?.some(e=>ps(e)||e.type==="function"&&e.function.strict===!0)??!1}function Gm(t){for(const e of t||[])if(e.type!=="function")throw new ee(`Currently only \\`function\\` tool calls are supported; Received \\`${e.type}\\``)}function FA(t){for(const e of t??[]){if(e.type!=="function")throw new ee(`Currently only \\`function\\` tool types support auto-parsing; Received \\`${e.type}\\``);if(e.function.strict!==!0)throw new ee(`The \\`${e.function.name}\\` tool is not marked with \\`strict: true\\`. Only strict function tools can be auto-parsed`)}}const Wa=t=>t?.role==="assistant",Wm=t=>t?.role==="tool";var $u,Ja,Ka,ms,gs,Xa,_s,pn,ys,Ya,Qa,vr,Jm;class Cu{constructor(){$u.add(this),this.controller=new AbortController,Ja.set(this,void 0),Ka.set(this,()=>{}),ms.set(this,()=>{}),gs.set(this,void 0),Xa.set(this,()=>{}),_s.set(this,()=>{}),pn.set(this,{}),ys.set(this,!1),Ya.set(this,!1),Qa.set(this,!1),vr.set(this,!1),re(this,Ja,new Promise((e,n)=>{re(this,Ka,e,"f"),re(this,ms,n,"f")})),re(this,gs,new Promise((e,n)=>{re(this,Xa,e,"f"),re(this,_s,n,"f")})),T(this,Ja,"f").catch(()=>{}),T(this,gs,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},T(this,$u,"m",Jm).bind(this))},0)}_connected(){this.ended||(T(this,Ka,"f").call(this),this._emit("connect"))}get ended(){return T(this,ys,"f")}get errored(){return T(this,Ya,"f")}get aborted(){return T(this,Qa,"f")}abort(){this.controller.abort()}on(e,n){return(T(this,pn,"f")[e]||(T(this,pn,"f")[e]=[])).push({listener:n}),this}off(e,n){const r=T(this,pn,"f")[e];if(!r)return this;const s=r.findIndex(a=>a.listener===n);return s>=0&&r.splice(s,1),this}once(e,n){return(T(this,pn,"f")[e]||(T(this,pn,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{re(this,vr,!0),e!=="error"&&this.once("error",r),this.once(e,n)})}async done(){re(this,vr,!0),await T(this,gs,"f")}_emit(e,...n){if(T(this,ys,"f"))return;e==="end"&&(re(this,ys,!0),T(this,Xa,"f").call(this));const r=T(this,pn,"f")[e];if(r&&(T(this,pn,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...n))),e==="abort"){const s=n[0];!T(this,vr,"f")&&!r?.length&&Promise.reject(s),T(this,ms,"f").call(this,s),T(this,_s,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=n[0];!T(this,vr,"f")&&!r?.length&&Promise.reject(s),T(this,ms,"f").call(this,s),T(this,_s,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Ja=new WeakMap,Ka=new WeakMap,ms=new WeakMap,gs=new WeakMap,Xa=new WeakMap,_s=new WeakMap,pn=new WeakMap,ys=new WeakMap,Ya=new WeakMap,Qa=new WeakMap,vr=new WeakMap,$u=new WeakSet,Jm=function(e){if(re(this,Ya,!0),e instanceof Error&&e.name==="AbortError"&&(e=new Et),e instanceof Et)return re(this,Qa,!0),this._emit("abort",e);if(e instanceof ee)return this._emit("error",e);if(e instanceof Error){const n=new ee(e.message);return n.cause=e,this._emit("error",n)}return this._emit("error",new ee(String(e)))};function UA(t){return typeof t.parse=="function"}var ht,Ru,ei,Nu,Pu,Mu,Km,Xm;const BA=10;class Ym extends Cu{constructor(){super(...arguments),ht.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const n=e.choices[0]?.message;return n&&this._addMessage(n),e}_addMessage(e,n=!0){if("content"in e||(e.content=null),this.messages.push(e),n){if(this._emit("message",e),Wm(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Wa(e)&&e.tool_calls)for(const r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new ee("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),T(this,ht,"m",Ru).call(this)}async finalMessage(){return await this.done(),T(this,ht,"m",ei).call(this)}async finalFunctionToolCall(){return await this.done(),T(this,ht,"m",Nu).call(this)}async finalFunctionToolCallResult(){return await this.done(),T(this,ht,"m",Pu).call(this)}async totalUsage(){return await this.done(),T(this,ht,"m",Mu).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const n=T(this,ht,"m",ei).call(this);n&&this._emit("finalMessage",n);const r=T(this,ht,"m",Ru).call(this);r&&this._emit("finalContent",r);const s=T(this,ht,"m",Nu).call(this);s&&this._emit("finalFunctionToolCall",s);const a=T(this,ht,"m",Pu).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",T(this,ht,"m",Mu).call(this))}async _createChatCompletion(e,n,r){const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),T(this,ht,"m",Km).call(this,n);const a=await e.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Ou(a,n))}async _runChatCompletion(e,n,r){for(const s of n.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,n,r)}async _runTools(e,n,r){const s="tool",{tool_choice:a="auto",stream:i,...o}=n,c=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:u=BA}=r||{},l=n.tools.map(h=>{if(ps(h)){if(!h.$callback)throw new ee("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:h.$callback,name:h.function.name,description:h.function.description||"",parameters:h.function.parameters,parse:h.$parseRaw,strict:!0}}}return h}),d={};for(const h of l)h.type==="function"&&(d[h.function.name||h.function.function.name]=h.function);const f="tools"in n?l.map(h=>h.type==="function"?{type:"function",function:{name:h.function.name||h.function.function.name,parameters:h.function.parameters,description:h.function.description,strict:h.function.strict}}:h):void 0;for(const h of n.messages)this._addMessage(h,!1);for(let h=0;h<u;++h){const m=(await this._createChatCompletion(e,{...o,tool_choice:a,tools:f,messages:[...this.messages]},r)).choices[0]?.message;if(!m)throw new ee("missing message in ChatCompletion response");if(!m.tool_calls?.length)return;for(const y of m.tool_calls){if(y.type!=="function")continue;const v=y.id,{name:w,arguments:E}=y.function,x=d[w];if(x){if(c&&c!==w){const b=`Invalid tool_call: ${JSON.stringify(w)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:s,tool_call_id:v,content:b});continue}}else{const b=`Invalid tool_call: ${JSON.stringify(w)}. Available options are: ${Object.keys(d).map(oe=>JSON.stringify(oe)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:v,content:b});continue}let A;try{A=UA(x)?await x.parse(E):E}catch(b){const oe=b instanceof Error?b.message:String(b);this._addMessage({role:s,tool_call_id:v,content:oe});continue}const N=await x.function(A,this),j=T(this,ht,"m",Xm).call(this,N);if(this._addMessage({role:s,tool_call_id:v,content:j}),c)return}}}}ht=new WeakSet,Ru=function(){return T(this,ht,"m",ei).call(this).content??null},ei=function(){let e=this.messages.length;for(;e-- >0;){const n=this.messages[e];if(Wa(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new ee("stream ended without producing a ChatCompletionMessage with role=assistant")},Nu=function(){for(let e=this.messages.length-1;e>=0;e--){const n=this.messages[e];if(Wa(n)&&n?.tool_calls?.length)return n.tool_calls.filter(r=>r.type==="function").at(-1)?.function}},Pu=function(){for(let e=this.messages.length-1;e>=0;e--){const n=this.messages[e];if(Wm(n)&&n.content!=null&&typeof n.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(s=>s.type==="function"&&s.id===n.tool_call_id)))return n.content}},Mu=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:n}of this._chatCompletions)n&&(e.completion_tokens+=n.completion_tokens,e.prompt_tokens+=n.prompt_tokens,e.total_tokens+=n.total_tokens);return e},Km=function(e){if(e.n!=null&&e.n>1)throw new ee("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Xm=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Lu extends Ym{static runTools(e,n,r){const s=new Lu,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,n,a)),s}_addMessage(e,n=!0){super._addMessage(e,n),Wa(e)&&e.content&&this._emit("content",e.content)}}const Qm=1,eg=2,tg=4,ng=8,rg=16,sg=32,ag=64,ig=128,og=256,cg=ig|og,ug=rg|sg|cg|ag,lg=Qm|eg|ug,dg=tg|ng,ZA=lg|dg,Ke={STR:Qm,NUM:eg,ARR:tg,OBJ:ng,NULL:rg,BOOL:sg,NAN:ag,INFINITY:ig,MINUS_INFINITY:og,INF:cg,SPECIAL:ug,ATOM:lg,COLLECTION:dg,ALL:ZA};class qA extends Error{}class VA extends Error{}function HA(t,e=Ke.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return GA(t.trim(),e)}const GA=(t,e)=>{const n=t.length;let r=0;const s=f=>{throw new qA(`${f} at position ${r}`)},a=f=>{throw new VA(`${f} at position ${r}`)},i=()=>(d(),r>=n&&s("Unexpected end of input"),t[r]===\'"\'?o():t[r]==="{"?c():t[r]==="["?u():t.substring(r,r+4)==="null"||Ke.NULL&e&&n-r<4&&"null".startsWith(t.substring(r))?(r+=4,null):t.substring(r,r+4)==="true"||Ke.BOOL&e&&n-r<4&&"true".startsWith(t.substring(r))?(r+=4,!0):t.substring(r,r+5)==="false"||Ke.BOOL&e&&n-r<5&&"false".startsWith(t.substring(r))?(r+=5,!1):t.substring(r,r+8)==="Infinity"||Ke.INFINITY&e&&n-r<8&&"Infinity".startsWith(t.substring(r))?(r+=8,1/0):t.substring(r,r+9)==="-Infinity"||Ke.MINUS_INFINITY&e&&1<n-r&&n-r<9&&"-Infinity".startsWith(t.substring(r))?(r+=9,-1/0):t.substring(r,r+3)==="NaN"||Ke.NAN&e&&n-r<3&&"NaN".startsWith(t.substring(r))?(r+=3,NaN):l()),o=()=>{const f=r;let h=!1;for(r++;r<n&&(t[r]!==\'"\'||h&&t[r-1]==="\\\\");)h=t[r]==="\\\\"?!h:!1,r++;if(t.charAt(r)==\'"\')try{return JSON.parse(t.substring(f,++r-Number(h)))}catch(p){a(String(p))}else if(Ke.STR&e)try{return JSON.parse(t.substring(f,r-Number(h))+\'"\')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\\\"))+\'"\')}s("Unterminated string literal")},c=()=>{r++,d();const f={};try{for(;t[r]!=="}";){if(d(),r>=n&&Ke.OBJ&e)return f;const h=o();d(),r++;try{const p=i();Object.defineProperty(f,h,{value:p,writable:!0,enumerable:!0,configurable:!0})}catch(p){if(Ke.OBJ&e)return f;throw p}d(),t[r]===","&&r++}}catch{if(Ke.OBJ&e)return f;s("Expected \'}\' at end of object")}return r++,f},u=()=>{r++;const f=[];try{for(;t[r]!=="]";)f.push(i()),d(),t[r]===","&&r++}catch{if(Ke.ARR&e)return f;s("Expected \']\' at end of array")}return r++,f},l=()=>{if(r===0){t==="-"&&Ke.NUM&e&&s("Not sure what \'-\' is");try{return JSON.parse(t)}catch(h){if(Ke.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}a(String(h))}}const f=r;for(t[r]==="-"&&r++;t[r]&&!",]}".includes(t[r]);)r++;r==n&&!(Ke.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(t.substring(f,r))}catch{t.substring(f,r)==="-"&&Ke.NUM&e&&s("Not sure what \'-\' is");try{return JSON.parse(t.substring(f,t.lastIndexOf("e")))}catch(p){a(String(p))}}},d=()=>{for(;r<n&&` \n\\r `.includes(t[r]);)r++};return i()},hg=t=>HA(t,Ke.ALL^Ke.NUM);var We,mn,Er,Mn,ju,ti,Du,zu,Fu,ni,Uu,fg;class ws extends Ym{constructor(e){super(),We.add(this),mn.set(this,void 0),Er.set(this,void 0),Mn.set(this,void 0),re(this,mn,e),re(this,Er,[])}get currentChatCompletionSnapshot(){return T(this,Mn,"f")}static fromReadableStream(e){const n=new ws(null);return n._run(()=>n._fromReadableStream(e)),n}static createChatCompletion(e,n,r){const s=new ws(n);return s._run(()=>s._runChatCompletion(e,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,n,r){super._createChatCompletion;const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),T(this,We,"m",ju).call(this);const a=await e.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const i of a)T(this,We,"m",Du).call(this,i);if(a.controller.signal?.aborted)throw new Et;return this._addChatCompletion(T(this,We,"m",ni).call(this))}async _fromReadableStream(e,n){const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),T(this,We,"m",ju).call(this),this._connected();const s=tn.fromReadableStream(e,this.controller);let a;for await(const i of s)a&&a!==i.id&&this._addChatCompletion(T(this,We,"m",ni).call(this)),T(this,We,"m",Du).call(this,i),a=i.id;if(s.controller.signal?.aborted)throw new Et;return this._addChatCompletion(T(this,We,"m",ni).call(this))}[(mn=new WeakMap,Er=new WeakMap,Mn=new WeakMap,We=new WeakSet,ju=function(){this.ended||re(this,Mn,void 0)},ti=function(n){let r=T(this,Er,"f")[n.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},T(this,Er,"f")[n.index]=r,r)},Du=function(n){if(this.ended)return;const r=T(this,We,"m",fg).call(this,n);this._emit("chunk",n,r);for(const s of n.choices){const a=r.choices[s.index];s.delta.content!=null&&a.message?.role==="assistant"&&a.message?.content&&(this._emit("content",s.delta.content,a.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:a.message.content,parsed:a.message.parsed})),s.delta.refusal!=null&&a.message?.role==="assistant"&&a.message?.refusal&&this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:a.message.refusal}),s.logprobs?.content!=null&&a.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:a.logprobs?.content??[]}),s.logprobs?.refusal!=null&&a.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:a.logprobs?.refusal??[]});const i=T(this,We,"m",ti).call(this,a);a.finish_reason&&(T(this,We,"m",Fu).call(this,a),i.current_tool_call_index!=null&&T(this,We,"m",zu).call(this,a,i.current_tool_call_index));for(const o of s.delta.tool_calls??[])i.current_tool_call_index!==o.index&&(T(this,We,"m",Fu).call(this,a),i.current_tool_call_index!=null&&T(this,We,"m",zu).call(this,a,i.current_tool_call_index)),i.current_tool_call_index=o.index;for(const o of s.delta.tool_calls??[]){const c=a.message.tool_calls?.[o.index];c?.type&&(c?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:c.function?.name,index:o.index,arguments:c.function.arguments,parsed_arguments:c.function.parsed_arguments,arguments_delta:o.function?.arguments??""}):(c?.type,void 0))}}},zu=function(n,r){if(T(this,We,"m",ti).call(this,n).done_tool_calls.has(r))return;const a=n.message.tool_calls?.[r];if(!a)throw new Error("no tool call snapshot");if(!a.type)throw new Error("tool call snapshot missing `type`");if(a.type==="function"){const i=T(this,mn,"f")?.tools?.find(o=>Ga(o)&&o.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:r,arguments:a.function.arguments,parsed_arguments:ps(i)?i.$parseRaw(a.function.arguments):i?.function.strict?JSON.parse(a.function.arguments):null})}else a.type},Fu=function(n){const r=T(this,We,"m",ti).call(this,n);if(n.message.content&&!r.content_done){r.content_done=!0;const s=T(this,We,"m",Uu).call(this);this._emit("content.done",{content:n.message.content,parsed:s?s.$parseRaw(n.message.content):null})}n.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:n.message.refusal})),n.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:n.logprobs.content})),n.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:n.logprobs.refusal}))},ni=function(){if(this.ended)throw new ee("stream has ended, this shouldn\'t happen");const n=T(this,Mn,"f");if(!n)throw new ee("request ended without sending any chunks");return re(this,Mn,void 0),re(this,Er,[]),WA(n,T(this,mn,"f"))},Uu=function(){const n=T(this,mn,"f")?.response_format;return ku(n)?n:null},fg=function(n){var r,s,a,i;let o=T(this,Mn,"f");const{choices:c,...u}=n;o?Object.assign(o,u):o=re(this,Mn,{...u,choices:[]});for(const{delta:l,finish_reason:d,index:f,logprobs:h=null,...p}of n.choices){let m=o.choices[f];if(m||(m=o.choices[f]={finish_reason:d,index:f,message:{},logprobs:h,...p}),h)if(!m.logprobs)m.logprobs=Object.assign({},h);else{const{content:N,refusal:j,...b}=h;Object.assign(m.logprobs,b),N&&((r=m.logprobs).content??(r.content=[]),m.logprobs.content.push(...N)),j&&((s=m.logprobs).refusal??(s.refusal=[]),m.logprobs.refusal.push(...j))}if(d&&(m.finish_reason=d,T(this,mn,"f")&&Hm(T(this,mn,"f")))){if(d==="length")throw new hm;if(d==="content_filter")throw new fm}if(Object.assign(m,p),!l)continue;const{content:y,refusal:v,function_call:w,role:E,tool_calls:x,...A}=l;if(Object.assign(m.message,A),v&&(m.message.refusal=(m.message.refusal||"")+v),E&&(m.message.role=E),w&&(m.message.function_call?(w.name&&(m.message.function_call.name=w.name),w.arguments&&((a=m.message.function_call).arguments??(a.arguments=""),m.message.function_call.arguments+=w.arguments)):m.message.function_call=w),y&&(m.message.content=(m.message.content||"")+y,!m.message.refusal&&T(this,We,"m",Uu).call(this)&&(m.message.parsed=hg(m.message.content))),x){m.message.tool_calls||(m.message.tool_calls=[]);for(const{index:N,id:j,type:b,function:oe,...ue}of x){const X=(i=m.message.tool_calls)[N]??(i[N]={});Object.assign(X,ue),j&&(X.id=j),b&&(X.type=b),oe&&(X.function??(X.function={name:oe.name??"",arguments:""})),oe?.name&&(X.function.name=oe.name),oe?.arguments&&(X.function.arguments+=oe.arguments,zA(T(this,mn,"f"),X)&&(X.function.parsed_arguments=hg(X.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("chunk",s=>{const a=n.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const a of n)a.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const a of n)a.reject(s);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((a,i)=>n.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new tn(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function WA(t,e){const{id:n,choices:r,created:s,model:a,system_fingerprint:i,...o}=t,c={...o,id:n,choices:r.map(({message:u,finish_reason:l,index:d,logprobs:f,...h})=>{if(!l)throw new ee(`missing finish_reason for choice ${d}`);const{content:p=null,function_call:m,tool_calls:y,...v}=u,w=u.role;if(!w)throw new ee(`missing role for choice ${d}`);if(m){const{arguments:E,name:x}=m;if(E==null)throw new ee(`missing function_call.arguments for choice ${d}`);if(!x)throw new ee(`missing function_call.name for choice ${d}`);return{...h,message:{content:p,function_call:{arguments:E,name:x},role:w,refusal:u.refusal??null},finish_reason:l,index:d,logprobs:f}}return y?{...h,index:d,finish_reason:l,logprobs:f,message:{...v,role:w,content:p,refusal:u.refusal??null,tool_calls:y.map((E,x)=>{const{function:A,type:N,id:j,...b}=E,{arguments:oe,name:ue,...X}=A||{};if(j==null)throw new ee(`missing choices[${d}].tool_calls[${x}].id\n${ri(t)}`);if(N==null)throw new ee(`missing choices[${d}].tool_calls[${x}].type\n${ri(t)}`);if(ue==null)throw new ee(`missing choices[${d}].tool_calls[${x}].function.name\n${ri(t)}`);if(oe==null)throw new ee(`missing choices[${d}].tool_calls[${x}].function.arguments\n${ri(t)}`);return{...b,id:j,type:N,function:{...X,name:ue,arguments:oe}}})}}:{...h,message:{...v,content:p,role:w,refusal:u.refusal??null},finish_reason:l,index:d,logprobs:f}}),created:s,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return LA(c,e)}function ri(t){return JSON.stringify(t)}function tC(t){}class si extends ws{static fromReadableStream(e){const n=new si(null);return n._run(()=>n._fromReadableStream(e)),n}static runTools(e,n,r){const s=new si(n),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,n,a)),s}}let Bu=class extends K{constructor(){super(...arguments),this.messages=new Vm(this._client)}create(e,n){return this._client.post("/chat/completions",{body:e,...n,stream:e.stream??!1})}retrieve(e,n){return this._client.get(O`/chat/completions/${e}`,n)}update(e,n,r){return this._client.post(O`/chat/completions/${e}`,{body:n,...r})}list(e={},n){return this._client.getAPIList("/chat/completions",Ue,{query:e,...n})}delete(e,n){return this._client.delete(O`/chat/completions/${e}`,n)}parse(e,n){return FA(e.tools),this._client.chat.completions.create(e,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>Ou(r,e))}runTools(e,n){return e.stream?si.runTools(this._client,e,n):Lu.runTools(this._client,e,n)}stream(e,n){return ws.createChatCompletion(this._client,e,n)}};Bu.Messages=Vm;class Zu extends K{constructor(){super(...arguments),this.completions=new Bu(this._client)}}Zu.Completions=Bu;const pg=Symbol("brand.privateNullableHeaders");function*JA(t){if(!t)return;if(pg in t){const{values:r,nulls:s}=t;yield*r.entries();for(const a of s)yield[a,null];return}let e=!1,n;t instanceof Headers?n=t.entries():pm(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let r of n){const s=r[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const a=pm(r[1])?r[1]:[r[1]];let i=!1;for(const o of a)o!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,o])}}const U=t=>{const e=new Headers,n=new Set;for(const r of t){const s=new Set;for(const[a,i]of JA(r)){const o=a.toLowerCase();s.has(o)||(e.delete(a),s.add(o)),i===null?(e.delete(a),n.add(o)):(e.append(a,i),n.delete(o))}}return{[pg]:!0,values:e,nulls:n}};class mg extends K{create(e,n){return this._client.post("/audio/speech",{body:e,...n,headers:U([{Accept:"application/octet-stream"},n?.headers]),__binaryResponse:!0})}}class gg extends K{create(e,n){return this._client.post("/audio/transcriptions",Jn({body:e,...n,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class _g extends K{create(e,n){return this._client.post("/audio/translations",Jn({body:e,...n,__metadata:{model:e.model}},this._client))}}class bs extends K{constructor(){super(...arguments),this.transcriptions=new gg(this._client),this.translations=new _g(this._client),this.speech=new mg(this._client)}}bs.Transcriptions=gg,bs.Translations=_g,bs.Speech=mg;class yg extends K{create(e,n){return this._client.post("/batches",{body:e,...n})}retrieve(e,n){return this._client.get(O`/batches/${e}`,n)}list(e={},n){return this._client.getAPIList("/batches",Ue,{query:e,...n})}cancel(e,n){return this._client.post(O`/batches/${e}/cancel`,n)}}class wg extends K{create(e,n){return this._client.post("/assistants",{body:e,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,n){return this._client.get(O`/assistants/${e}`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,n,r){return this._client.post(O`/assistants/${e}`,{body:n,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},n){return this._client.getAPIList("/assistants",Ue,{query:e,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,n){return this._client.delete(O`/assistants/${e}`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}}let bg=class extends K{create(e,n){return this._client.post("/realtime/sessions",{body:e,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};class vg extends K{create(e,n){return this._client.post("/realtime/transcription_sessions",{body:e,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}}let ai=class extends K{constructor(){super(...arguments),this.sessions=new bg(this._client),this.transcriptionSessions=new vg(this._client)}};ai.Sessions=bg,ai.TranscriptionSessions=vg;class Eg extends K{create(e,n){return this._client.post("/chatkit/sessions",{body:e,...n,headers:U([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}cancel(e,n){return this._client.post(O`/chatkit/sessions/${e}/cancel`,{...n,headers:U([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}}let Sg=class extends K{retrieve(e,n){return this._client.get(O`/chatkit/threads/${e}`,{...n,headers:U([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}list(e={},n){return this._client.getAPIList("/chatkit/threads",Va,{query:e,...n,headers:U([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}delete(e,n){return this._client.delete(O`/chatkit/threads/${e}`,{...n,headers:U([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}listItems(e,n={},r){return this._client.getAPIList(O`/chatkit/threads/${e}/items`,Va,{query:n,...r,headers:U([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}};class ii extends K{constructor(){super(...arguments),this.sessions=new Eg(this._client),this.threads=new Sg(this._client)}}ii.Sessions=Eg,ii.Threads=Sg;class Tg extends K{create(e,n,r){return this._client.post(O`/threads/${e}/messages`,{body:n,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,n,r){const{thread_id:s}=n;return this._client.get(O`/threads/${s}/messages/${e}`,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,n,r){const{thread_id:s,...a}=n;return this._client.post(O`/threads/${s}/messages/${e}`,{body:a,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,n={},r){return this._client.getAPIList(O`/threads/${e}/messages`,Ue,{query:n,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,n,r){const{thread_id:s}=n;return this._client.delete(O`/threads/${s}/messages/${e}`,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class xg extends K{retrieve(e,n,r){const{thread_id:s,run_id:a,...i}=n;return this._client.get(O`/threads/${s}/runs/${a}/steps/${e}`,{query:i,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,n,r){const{thread_id:s,...a}=n;return this._client.getAPIList(O`/threads/${s}/runs/${e}/steps`,Ue,{query:a,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}const KA=t=>{if(typeof Buffer<"u"){const e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(t),n=e.length,r=new Uint8Array(n);for(let s=0;s<n;s++)r[s]=e.charCodeAt(s);return Array.from(new Float32Array(r.buffer))}},Sr=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()};var tt,Kn,qu,nn,oi,qt,Xn,Tr,Yn,ci,xt,ui,li,vs,Es,Ss,Ig,Ag,kg,Og,$g,Cg,Rg;class Ts extends Cu{constructor(){super(...arguments),tt.add(this),qu.set(this,[]),nn.set(this,{}),oi.set(this,{}),qt.set(this,void 0),Xn.set(this,void 0),Tr.set(this,void 0),Yn.set(this,void 0),ci.set(this,void 0),xt.set(this,void 0),ui.set(this,void 0),li.set(this,void 0),vs.set(this,void 0)}[(qu=new WeakMap,nn=new WeakMap,oi=new WeakMap,qt=new WeakMap,Xn=new WeakMap,Tr=new WeakMap,Yn=new WeakMap,ci=new WeakMap,xt=new WeakMap,ui=new WeakMap,li=new WeakMap,vs=new WeakMap,tt=new WeakSet,Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("event",s=>{const a=n.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const a of n)a.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const a of n)a.reject(s);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((a,i)=>n.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const n=new Kn;return n._run(()=>n._fromReadableStream(e)),n}async _fromReadableStream(e,n){const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=tn.fromReadableStream(e,this.controller);for await(const a of s)T(this,tt,"m",Es).call(this,a);if(s.controller.signal?.aborted)throw new Et;return this._addRun(T(this,tt,"m",Ss).call(this))}toReadableStream(){return new tn(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,n,r,s){const a=new Kn;return a._run(()=>a._runToolAssistantStream(e,n,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,n,r,s){const a=s?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},o=await e.submitToolOutputs(n,i,{...s,signal:this.controller.signal});this._connected();for await(const c of o)T(this,tt,"m",Es).call(this,c);if(o.controller.signal?.aborted)throw new Et;return this._addRun(T(this,tt,"m",Ss).call(this))}static createThreadAssistantStream(e,n,r){const s=new Kn;return s._run(()=>s._threadAssistantStream(e,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,n,r,s){const a=new Kn;return a._run(()=>a._runAssistantStream(e,n,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return T(this,ui,"f")}currentRun(){return T(this,li,"f")}currentMessageSnapshot(){return T(this,qt,"f")}currentRunStepSnapshot(){return T(this,vs,"f")}async finalRunSteps(){return await this.done(),Object.values(T(this,nn,"f"))}async finalMessages(){return await this.done(),Object.values(T(this,oi,"f"))}async finalRun(){if(await this.done(),!T(this,Xn,"f"))throw Error("Final run was not received.");return T(this,Xn,"f")}async _createThreadAssistantStream(e,n,r){const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const a={...n,stream:!0},i=await e.createAndRun(a,{...r,signal:this.controller.signal});this._connected();for await(const o of i)T(this,tt,"m",Es).call(this,o);if(i.controller.signal?.aborted)throw new Et;return this._addRun(T(this,tt,"m",Ss).call(this))}async _createAssistantStream(e,n,r,s){const a=s?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},o=await e.create(n,i,{...s,signal:this.controller.signal});this._connected();for await(const c of o)T(this,tt,"m",Es).call(this,c);if(o.controller.signal?.aborted)throw new Et;return this._addRun(T(this,tt,"m",Ss).call(this))}static accumulateDelta(e,n){for(const[r,s]of Object.entries(n)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let a=e[r];if(a==null){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof a=="string"&&typeof s=="string")a+=s;else if(typeof a=="number"&&typeof s=="number")a+=s;else if(yu(a)&&yu(s))a=this.accumulateDelta(a,s);else if(Array.isArray(a)&&Array.isArray(s)){if(a.every(i=>typeof i=="string"||typeof i=="number")){a.push(...s);continue}for(const i of s){if(!yu(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const o=i.index;if(o==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof o!="number")throw new Error(`Expected array delta entry \\`index\\` property to be a number but got ${o}`);const c=a[o];c==null?a.push(i):a[o]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${a}`);e[r]=a}return e}_addRun(e){return e}async _threadAssistantStream(e,n,r){return await this._createThreadAssistantStream(n,e,r)}async _runAssistantStream(e,n,r,s){return await this._createAssistantStream(n,e,r,s)}async _runToolAssistantStream(e,n,r,s){return await this._createToolAssistantStream(n,e,r,s)}}Kn=Ts,Es=function(e){if(!this.ended)switch(re(this,ui,e),T(this,tt,"m",kg).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":T(this,tt,"m",Rg).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":T(this,tt,"m",Ag).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":T(this,tt,"m",Ig).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Ss=function(){if(this.ended)throw new ee("stream has ended, this shouldn\'t happen");if(!T(this,Xn,"f"))throw Error("Final run has not been received");return T(this,Xn,"f")},Ig=function(e){const[n,r]=T(this,tt,"m",$g).call(this,e,T(this,qt,"f"));re(this,qt,n),T(this,oi,"f")[n.id]=n;for(const s of r){const a=n.content[s.index];a?.type=="text"&&this._emit("textCreated",a.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,n),e.data.delta.content)for(const s of e.data.delta.content){if(s.type=="text"&&s.text){let a=s.text,i=n.content[s.index];if(i&&i.type=="text")this._emit("textDelta",a,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=T(this,Tr,"f")){if(T(this,Yn,"f"))switch(T(this,Yn,"f").type){case"text":this._emit("textDone",T(this,Yn,"f").text,T(this,qt,"f"));break;case"image_file":this._emit("imageFileDone",T(this,Yn,"f").image_file,T(this,qt,"f"));break}re(this,Tr,s.index)}re(this,Yn,n.content[s.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(T(this,Tr,"f")!==void 0){const s=e.data.content[T(this,Tr,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,T(this,qt,"f"));break;case"text":this._emit("textDone",s.text,T(this,qt,"f"));break}}T(this,qt,"f")&&this._emit("messageDone",e.data),re(this,qt,void 0)}},Ag=function(e){const n=T(this,tt,"m",Og).call(this,e);switch(re(this,vs,n),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&n.step_details.type=="tool_calls")for(const a of r.step_details.tool_calls)a.index==T(this,ci,"f")?this._emit("toolCallDelta",a,n.step_details.tool_calls[a.index]):(T(this,xt,"f")&&this._emit("toolCallDone",T(this,xt,"f")),re(this,ci,a.index),re(this,xt,n.step_details.tool_calls[a.index]),T(this,xt,"f")&&this._emit("toolCallCreated",T(this,xt,"f")));this._emit("runStepDelta",e.data.delta,n);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":re(this,vs,void 0),e.data.step_details.type=="tool_calls"&&T(this,xt,"f")&&(this._emit("toolCallDone",T(this,xt,"f")),re(this,xt,void 0)),this._emit("runStepDone",e.data,n);break}},kg=function(e){T(this,qu,"f").push(e),this._emit("event",e)},Og=function(e){switch(e.event){case"thread.run.step.created":return T(this,nn,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let n=T(this,nn,"f")[e.data.id];if(!n)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){const s=Kn.accumulateDelta(n,r.delta);T(this,nn,"f")[e.data.id]=s}return T(this,nn,"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":T(this,nn,"f")[e.data.id]=e.data;break}if(T(this,nn,"f")[e.data.id])return T(this,nn,"f")[e.data.id];throw new Error("No snapshot available")},$g=function(e,n){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!n)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(const a of s.delta.content)if(a.index in n.content){let i=n.content[a.index];n.content[a.index]=T(this,tt,"m",Cg).call(this,a,i)}else n.content[a.index]=a,r.push(a);return[n,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(n)return[n,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Cg=function(e,n){return Kn.accumulateDelta(n,e)},Rg=function(e){switch(re(this,li,e.data),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":re(this,Xn,e.data),T(this,xt,"f")&&(this._emit("toolCallDone",T(this,xt,"f")),re(this,xt,void 0));break}};let Vu=class extends K{constructor(){super(...arguments),this.steps=new xg(this._client)}create(e,n,r){const{include:s,...a}=n;return this._client.post(O`/threads/${e}/runs`,{query:{include:s},body:a,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:n.stream??!1})}retrieve(e,n,r){const{thread_id:s}=n;return this._client.get(O`/threads/${s}/runs/${e}`,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,n,r){const{thread_id:s,...a}=n;return this._client.post(O`/threads/${s}/runs/${e}`,{body:a,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,n={},r){return this._client.getAPIList(O`/threads/${e}/runs`,Ue,{query:n,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,n,r){const{thread_id:s}=n;return this._client.post(O`/threads/${s}/runs/${e}/cancel`,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,n,r){const s=await this.create(e,n,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,n,r){return Ts.createAssistantStream(e,this._client.beta.threads.runs,n,r)}async poll(e,n,r){const s=U([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:a,response:i}=await this.retrieve(e,n,{...r,headers:{...r?.headers,...s}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{const c=i.headers.get("openai-poll-after-ms");if(c){const u=parseInt(c);isNaN(u)||(o=u)}}await us(o);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,n,r){return Ts.createAssistantStream(e,this._client.beta.threads.runs,n,r)}submitToolOutputs(e,n,r){const{thread_id:s,...a}=n;return this._client.post(O`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:a,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:n.stream??!1})}async submitToolOutputsAndPoll(e,n,r){const s=await this.submitToolOutputs(e,n,r);return await this.poll(s.id,n,r)}submitToolOutputsStream(e,n,r){return Ts.createToolAssistantStream(e,this._client.beta.threads.runs,n,r)}};Vu.Steps=xg;class di extends K{constructor(){super(...arguments),this.runs=new Vu(this._client),this.messages=new Tg(this._client)}create(e={},n){return this._client.post("/threads",{body:e,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,n){return this._client.get(O`/threads/${e}`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,n,r){return this._client.post(O`/threads/${e}`,{body:n,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,n){return this._client.delete(O`/threads/${e}`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}createAndRun(e,n){return this._client.post("/threads/runs",{body:e,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,n){const r=await this.createAndRun(e,n);return await this.runs.poll(r.id,{thread_id:r.thread_id},n)}createAndRunStream(e,n){return Ts.createThreadAssistantStream(e,this._client.beta.threads,n)}}di.Runs=Vu,di.Messages=Tg;class xr extends K{constructor(){super(...arguments),this.realtime=new ai(this._client),this.chatkit=new ii(this._client),this.assistants=new wg(this._client),this.threads=new di(this._client)}}xr.Realtime=ai,xr.ChatKit=ii,xr.Assistants=wg,xr.Threads=di;class Ng extends K{create(e,n){return this._client.post("/completions",{body:e,...n,stream:e.stream??!1})}}class Pg extends K{retrieve(e,n,r){const{container_id:s}=n;return this._client.get(O`/containers/${s}/files/${e}/content`,{...r,headers:U([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}let Hu=class extends K{constructor(){super(...arguments),this.content=new Pg(this._client)}create(e,n,r){return this._client.post(O`/containers/${e}/files`,Jn({body:n,...r},this._client))}retrieve(e,n,r){const{container_id:s}=n;return this._client.get(O`/containers/${s}/files/${e}`,r)}list(e,n={},r){return this._client.getAPIList(O`/containers/${e}/files`,Ue,{query:n,...r})}delete(e,n,r){const{container_id:s}=n;return this._client.delete(O`/containers/${s}/files/${e}`,{...r,headers:U([{Accept:"*/*"},r?.headers])})}};Hu.Content=Pg;class Gu extends K{constructor(){super(...arguments),this.files=new Hu(this._client)}create(e,n){return this._client.post("/containers",{body:e,...n})}retrieve(e,n){return this._client.get(O`/containers/${e}`,n)}list(e={},n){return this._client.getAPIList("/containers",Ue,{query:e,...n})}delete(e,n){return this._client.delete(O`/containers/${e}`,{...n,headers:U([{Accept:"*/*"},n?.headers])})}}Gu.Files=Hu;class Mg extends K{create(e,n,r){const{include:s,...a}=n;return this._client.post(O`/conversations/${e}/items`,{query:{include:s},body:a,...r})}retrieve(e,n,r){const{conversation_id:s,...a}=n;return this._client.get(O`/conversations/${s}/items/${e}`,{query:a,...r})}list(e,n={},r){return this._client.getAPIList(O`/conversations/${e}/items`,Va,{query:n,...r})}delete(e,n,r){const{conversation_id:s}=n;return this._client.delete(O`/conversations/${s}/items/${e}`,r)}}class Wu extends K{constructor(){super(...arguments),this.items=new Mg(this._client)}create(e={},n){return this._client.post("/conversations",{body:e,...n})}retrieve(e,n){return this._client.get(O`/conversations/${e}`,n)}update(e,n,r){return this._client.post(O`/conversations/${e}`,{body:n,...r})}delete(e,n){return this._client.delete(O`/conversations/${e}`,n)}}Wu.Items=Mg;let Lg=class extends K{create(e,n){const r=!!e.encoding_format;let s=r?e.encoding_format:"base64";r&&et(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const a=this._client.post("/embeddings",{body:{...e,encoding_format:s},...n});return r?a:(et(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(i=>(i&&i.data&&i.data.forEach(o=>{const c=o.embedding;o.embedding=KA(c)}),i)))}};class jg extends K{retrieve(e,n,r){const{eval_id:s,run_id:a}=n;return this._client.get(O`/evals/${s}/runs/${a}/output_items/${e}`,r)}list(e,n,r){const{eval_id:s,...a}=n;return this._client.getAPIList(O`/evals/${s}/runs/${e}/output_items`,Ue,{query:a,...r})}}class Ju extends K{constructor(){super(...arguments),this.outputItems=new jg(this._client)}create(e,n,r){return this._client.post(O`/evals/${e}/runs`,{body:n,...r})}retrieve(e,n,r){const{eval_id:s}=n;return this._client.get(O`/evals/${s}/runs/${e}`,r)}list(e,n={},r){return this._client.getAPIList(O`/evals/${e}/runs`,Ue,{query:n,...r})}delete(e,n,r){const{eval_id:s}=n;return this._client.delete(O`/evals/${s}/runs/${e}`,r)}cancel(e,n,r){const{eval_id:s}=n;return this._client.post(O`/evals/${s}/runs/${e}`,r)}}Ju.OutputItems=jg;class Ku extends K{constructor(){super(...arguments),this.runs=new Ju(this._client)}create(e,n){return this._client.post("/evals",{body:e,...n})}retrieve(e,n){return this._client.get(O`/evals/${e}`,n)}update(e,n,r){return this._client.post(O`/evals/${e}`,{body:n,...r})}list(e={},n){return this._client.getAPIList("/evals",Ue,{query:e,...n})}delete(e,n){return this._client.delete(O`/evals/${e}`,n)}}Ku.Runs=Ju;let Dg=class extends K{create(e,n){return this._client.post("/files",Jn({body:e,...n},this._client))}retrieve(e,n){return this._client.get(O`/files/${e}`,n)}list(e={},n){return this._client.getAPIList("/files",Ue,{query:e,...n})}delete(e,n){return this._client.delete(O`/files/${e}`,n)}content(e,n){return this._client.get(O`/files/${e}/content`,{...n,headers:U([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:n=5e3,maxWait:r=1800*1e3}={}){const s=new Set(["processed","error","deleted"]),a=Date.now();let i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await us(n),i=await this.retrieve(e),Date.now()-a>r)throw new Da({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};class zg extends K{}let Fg=class extends K{run(e,n){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...n})}validate(e,n){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...n})}};class Xu extends K{constructor(){super(...arguments),this.graders=new Fg(this._client)}}Xu.Graders=Fg;class Ug extends K{create(e,n,r){return this._client.getAPIList(O`/fine_tuning/checkpoints/${e}/permissions`,qa,{body:n,method:"post",...r})}retrieve(e,n={},r){return this._client.get(O`/fine_tuning/checkpoints/${e}/permissions`,{query:n,...r})}delete(e,n,r){const{fine_tuned_model_checkpoint:s}=n;return this._client.delete(O`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}}let Yu=class extends K{constructor(){super(...arguments),this.permissions=new Ug(this._client)}};Yu.Permissions=Ug;class Bg extends K{list(e,n={},r){return this._client.getAPIList(O`/fine_tuning/jobs/${e}/checkpoints`,Ue,{query:n,...r})}}class Qu extends K{constructor(){super(...arguments),this.checkpoints=new Bg(this._client)}create(e,n){return this._client.post("/fine_tuning/jobs",{body:e,...n})}retrieve(e,n){return this._client.get(O`/fine_tuning/jobs/${e}`,n)}list(e={},n){return this._client.getAPIList("/fine_tuning/jobs",Ue,{query:e,...n})}cancel(e,n){return this._client.post(O`/fine_tuning/jobs/${e}/cancel`,n)}listEvents(e,n={},r){return this._client.getAPIList(O`/fine_tuning/jobs/${e}/events`,Ue,{query:n,...r})}pause(e,n){return this._client.post(O`/fine_tuning/jobs/${e}/pause`,n)}resume(e,n){return this._client.post(O`/fine_tuning/jobs/${e}/resume`,n)}}Qu.Checkpoints=Bg;class Ir extends K{constructor(){super(...arguments),this.methods=new zg(this._client),this.jobs=new Qu(this._client),this.checkpoints=new Yu(this._client),this.alpha=new Xu(this._client)}}Ir.Methods=zg,Ir.Jobs=Qu,Ir.Checkpoints=Yu,Ir.Alpha=Xu;class Zg extends K{}class el extends K{constructor(){super(...arguments),this.graderModels=new Zg(this._client)}}el.GraderModels=Zg;class qg extends K{createVariation(e,n){return this._client.post("/images/variations",Jn({body:e,...n},this._client))}edit(e,n){return this._client.post("/images/edits",Jn({body:e,...n,stream:e.stream??!1},this._client))}generate(e,n){return this._client.post("/images/generations",{body:e,...n,stream:e.stream??!1})}}class Vg extends K{retrieve(e,n){return this._client.get(O`/models/${e}`,n)}list(e){return this._client.getAPIList("/models",qa,e)}delete(e,n){return this._client.delete(O`/models/${e}`,n)}}class Hg extends K{create(e,n){return this._client.post("/moderations",{body:e,...n})}}class Gg extends K{accept(e,n,r){return this._client.post(O`/realtime/calls/${e}/accept`,{body:n,...r,headers:U([{Accept:"*/*"},r?.headers])})}hangup(e,n){return this._client.post(O`/realtime/calls/${e}/hangup`,{...n,headers:U([{Accept:"*/*"},n?.headers])})}refer(e,n,r){return this._client.post(O`/realtime/calls/${e}/refer`,{body:n,...r,headers:U([{Accept:"*/*"},r?.headers])})}reject(e,n={},r){return this._client.post(O`/realtime/calls/${e}/reject`,{body:n,...r,headers:U([{Accept:"*/*"},r?.headers])})}}class Wg extends K{create(e,n){return this._client.post("/realtime/client_secrets",{body:e,...n})}}class hi extends K{constructor(){super(...arguments),this.clientSecrets=new Wg(this._client),this.calls=new Gg(this._client)}}hi.ClientSecrets=Wg,hi.Calls=Gg;function XA(t,e){return!e||!QA(e)?{...t,output_parsed:null,output:t.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(r=>({...r,parsed:null}))}:n)}:Jg(t,e)}function Jg(t,e){const n=t.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:nk(e,s)};if(s.type==="message"){const a=s.content.map(i=>i.type==="output_text"?{...i,parsed:YA(e,i.text)}:i);return{...s,content:a}}return s}),r=Object.assign({},t,{output:n});return Object.getOwnPropertyDescriptor(t,"output_text")||tl(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(const s of r.output)if(s.type==="message"){for(const a of s.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),r}function YA(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function QA(t){return!!ku(t.text?.format)}function ek(t){return t?.$brand==="auto-parseable-tool"}function tk(t,e){return t.find(n=>n.type==="function"&&n.name===e)}function nk(t,e){const n=tk(t.tools??[],e.name);return{...e,...e,parsed_arguments:ek(n)?n.$parseRaw(e.arguments):n?.strict?JSON.parse(e.arguments):null}}function tl(t){const e=[];for(const n of t.output)if(n.type==="message")for(const r of n.content)r.type==="output_text"&&e.push(r.text);t.output_text=e.join("")}var Ar,fi,Ln,pi,Kg,Xg,Yg,Qg;class nl extends Cu{constructor(e){super(),Ar.add(this),fi.set(this,void 0),Ln.set(this,void 0),pi.set(this,void 0),re(this,fi,e)}static createResponse(e,n,r){const s=new nl(n);return s._run(()=>s._createOrRetrieveResponse(e,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,n,r){const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),T(this,Ar,"m",Kg).call(this);let a,i=null;"response_id"in n?(a=await e.responses.retrieve(n.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=n.starting_after??null):a=await e.responses.create({...n,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(const o of a)T(this,Ar,"m",Xg).call(this,o,i);if(a.controller.signal?.aborted)throw new Et;return T(this,Ar,"m",Yg).call(this)}[(fi=new WeakMap,Ln=new WeakMap,pi=new WeakMap,Ar=new WeakSet,Kg=function(){this.ended||re(this,Ln,void 0)},Xg=function(n,r){if(this.ended)return;const s=(i,o)=>{(r==null||o.sequence_number>r)&&this._emit(i,o)},a=T(this,Ar,"m",Qg).call(this,n);switch(s("event",n),n.type){case"response.output_text.delta":{const i=a.output[n.output_index];if(!i)throw new ee(`missing output at index ${n.output_index}`);if(i.type==="message"){const o=i.content[n.content_index];if(!o)throw new ee(`missing content at index ${n.content_index}`);if(o.type!=="output_text")throw new ee(`expected content to be \'output_text\', got ${o.type}`);s("response.output_text.delta",{...n,snapshot:o.text})}break}case"response.function_call_arguments.delta":{const i=a.output[n.output_index];if(!i)throw new ee(`missing output at index ${n.output_index}`);i.type==="function_call"&&s("response.function_call_arguments.delta",{...n,snapshot:i.arguments});break}default:s(n.type,n);break}},Yg=function(){if(this.ended)throw new ee("stream has ended, this shouldn\'t happen");const n=T(this,Ln,"f");if(!n)throw new ee("request ended without sending any events");re(this,Ln,void 0);const r=rk(n,T(this,fi,"f"));return re(this,pi,r),r},Qg=function(n){let r=T(this,Ln,"f");if(!r){if(n.type!=="response.created")throw new ee(`When snapshot hasn\'t been set yet, expected \'response.created\' event, got ${n.type}`);return r=re(this,Ln,n.response),r}switch(n.type){case"response.output_item.added":{r.output.push(n.item);break}case"response.content_part.added":{const s=r.output[n.output_index];if(!s)throw new ee(`missing output at index ${n.output_index}`);const a=s.type,i=n.part;a==="message"&&i.type!=="reasoning_text"?s.content.push(i):a==="reasoning"&&i.type==="reasoning_text"&&(s.content||(s.content=[]),s.content.push(i));break}case"response.output_text.delta":{const s=r.output[n.output_index];if(!s)throw new ee(`missing output at index ${n.output_index}`);if(s.type==="message"){const a=s.content[n.content_index];if(!a)throw new ee(`missing content at index ${n.content_index}`);if(a.type!=="output_text")throw new ee(`expected content to be \'output_text\', got ${a.type}`);a.text+=n.delta}break}case"response.function_call_arguments.delta":{const s=r.output[n.output_index];if(!s)throw new ee(`missing output at index ${n.output_index}`);s.type==="function_call"&&(s.arguments+=n.delta);break}case"response.reasoning_text.delta":{const s=r.output[n.output_index];if(!s)throw new ee(`missing output at index ${n.output_index}`);if(s.type==="reasoning"){const a=s.content?.[n.content_index];if(!a)throw new ee(`missing content at index ${n.content_index}`);if(a.type!=="reasoning_text")throw new ee(`expected content to be \'reasoning_text\', got ${a.type}`);a.text+=n.delta}break}case"response.completed":{re(this,Ln,n.response);break}}return r},Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("event",s=>{const a=n.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const a of n)a.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const a of n)a.reject(s);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((a,i)=>n.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=T(this,pi,"f");if(!e)throw new ee("stream ended without producing a ChatCompletion");return e}}function rk(t,e){return XA(t,e)}class e_ extends K{list(e,n={},r){return this._client.getAPIList(O`/responses/${e}/input_items`,Ue,{query:n,...r})}}class t_ extends K{count(e={},n){return this._client.post("/responses/input_tokens",{body:e,...n})}}class mi extends K{constructor(){super(...arguments),this.inputItems=new e_(this._client),this.inputTokens=new t_(this._client)}create(e,n){return this._client.post("/responses",{body:e,...n,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&tl(r),r))}retrieve(e,n={},r){return this._client.get(O`/responses/${e}`,{query:n,...r,stream:n?.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&tl(s),s))}delete(e,n){return this._client.delete(O`/responses/${e}`,{...n,headers:U([{Accept:"*/*"},n?.headers])})}parse(e,n){return this._client.responses.create(e,n)._thenUnwrap(r=>Jg(r,e))}stream(e,n){return nl.createResponse(this._client,e,n)}cancel(e,n){return this._client.post(O`/responses/${e}/cancel`,n)}compact(e,n){return this._client.post("/responses/compact",{body:e,...n})}}mi.InputItems=e_,mi.InputTokens=t_;class n_ extends K{create(e,n,r){return this._client.post(O`/uploads/${e}/parts`,Jn({body:n,...r},this._client))}}class rl extends K{constructor(){super(...arguments),this.parts=new n_(this._client)}create(e,n){return this._client.post("/uploads",{body:e,...n})}cancel(e,n){return this._client.post(O`/uploads/${e}/cancel`,n)}complete(e,n,r){return this._client.post(O`/uploads/${e}/complete`,{body:n,...r})}}rl.Parts=n_;const sk=async t=>{const e=await Promise.allSettled(t),n=e.filter(s=>s.status==="rejected");if(n.length){for(const s of n)console.error(s.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const r=[];for(const s of e)s.status==="fulfilled"&&r.push(s.value);return r};class r_ extends K{create(e,n,r){return this._client.post(O`/vector_stores/${e}/file_batches`,{body:n,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,n,r){const{vector_store_id:s}=n;return this._client.get(O`/vector_stores/${s}/file_batches/${e}`,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,n,r){const{vector_store_id:s}=n;return this._client.post(O`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,n,r){const s=await this.create(e,n);return await this.poll(e,s.id,r)}listFiles(e,n,r){const{vector_store_id:s,...a}=n;return this._client.getAPIList(O`/vector_stores/${s}/file_batches/${e}/files`,Ue,{query:a,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,n,r){const s=U([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:a,response:i}=await this.retrieve(n,{vector_store_id:e},{...r,headers:s}).withResponse();switch(a.status){case"in_progress":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{const c=i.headers.get("openai-poll-after-ms");if(c){const u=parseInt(c);isNaN(u)||(o=u)}}await us(o);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:n,fileIds:r=[]},s){if(n==null||n.length==0)throw new Error("No `files` provided to process. If you\'ve already uploaded files you should use `.createAndPoll()` instead");const a=s?.maxConcurrency??5,i=Math.min(a,n.length),o=this._client,c=n.values(),u=[...r];async function l(f){for(let h of f){const p=await o.files.create({file:h,purpose:"assistants"},s);u.push(p.id)}}const d=Array(i).fill(c).map(l);return await sk(d),await this.createAndPoll(e,{file_ids:u})}}class s_ extends K{create(e,n,r){return this._client.post(O`/vector_stores/${e}/files`,{body:n,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,n,r){const{vector_store_id:s}=n;return this._client.get(O`/vector_stores/${s}/files/${e}`,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,n,r){const{vector_store_id:s,...a}=n;return this._client.post(O`/vector_stores/${s}/files/${e}`,{body:a,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,n={},r){return this._client.getAPIList(O`/vector_stores/${e}/files`,Ue,{query:n,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,n,r){const{vector_store_id:s}=n;return this._client.delete(O`/vector_stores/${s}/files/${e}`,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,n,r){const s=await this.create(e,n,r);return await this.poll(e,s.id,r)}async poll(e,n,r){const s=U([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const a=await this.retrieve(n,{vector_store_id:e},{...r,headers:s}).withResponse(),i=a.data;switch(i.status){case"in_progress":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{const c=a.response.headers.get("openai-poll-after-ms");if(c){const u=parseInt(c);isNaN(u)||(o=u)}}await us(o);break;case"failed":case"completed":return i}}}async upload(e,n,r){const s=await this._client.files.create({file:n,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,n,r){const s=await this.upload(e,n,r);return await this.poll(e,s.id,r)}content(e,n,r){const{vector_store_id:s}=n;return this._client.getAPIList(O`/vector_stores/${s}/files/${e}/content`,qa,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class gi extends K{constructor(){super(...arguments),this.files=new s_(this._client),this.fileBatches=new r_(this._client)}create(e,n){return this._client.post("/vector_stores",{body:e,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,n){return this._client.get(O`/vector_stores/${e}`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,n,r){return this._client.post(O`/vector_stores/${e}`,{body:n,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},n){return this._client.getAPIList("/vector_stores",Ue,{query:e,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,n){return this._client.delete(O`/vector_stores/${e}`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}search(e,n,r){return this._client.getAPIList(O`/vector_stores/${e}/search`,qa,{body:n,method:"post",...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}gi.Files=s_,gi.FileBatches=r_;class a_ extends K{create(e,n){return this._client.post("/videos",Dm({body:e,...n},this._client))}retrieve(e,n){return this._client.get(O`/videos/${e}`,n)}list(e={},n){return this._client.getAPIList("/videos",Va,{query:e,...n})}delete(e,n){return this._client.delete(O`/videos/${e}`,n)}downloadContent(e,n={},r){return this._client.get(O`/videos/${e}/content`,{query:n,...r,headers:U([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}remix(e,n,r){return this._client.post(O`/videos/${e}/remix`,Dm({body:n,...r},this._client))}}var kr,i_,_i;class o_ extends K{constructor(){super(...arguments),kr.add(this)}async unwrap(e,n,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,n,r,s),JSON.parse(e)}async verifySignature(e,n,r=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");T(this,kr,"m",i_).call(this,r);const a=U([n]).values,i=T(this,kr,"m",_i).call(this,a,"webhook-signature"),o=T(this,kr,"m",_i).call(this,a,"webhook-timestamp"),c=T(this,kr,"m",_i).call(this,a,"webhook-id"),u=parseInt(o,10);if(isNaN(u))throw new cs("Invalid webhook timestamp format");const l=Math.floor(Date.now()/1e3);if(l-u>s)throw new cs("Webhook timestamp is too old");if(u>l+s)throw new cs("Webhook timestamp is too new");const d=i.split(" ").map(m=>m.startsWith("v1,")?m.substring(3):m),f=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),h=c?`${c}.${o}.${e}`:`${o}.${e}`,p=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const m of d)try{const y=Buffer.from(m,"base64");if(await crypto.subtle.verify("HMAC",p,y,new TextEncoder().encode(h)))return}catch{continue}throw new cs("The given webhook signature does not match the expected signature")}}kr=new WeakSet,i_=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: \'123\' }), or passed to this function")},_i=function(e,n){if(!e)throw new Error("Headers are required");const r=e.get(n);if(r==null)throw new Error(`Missing required header: ${n}`);return r};var sl,al,yi,c_;class pe{constructor({baseURL:e=Sr("OPENAI_BASE_URL"),apiKey:n=Sr("OPENAI_API_KEY"),organization:r=Sr("OPENAI_ORG_ID")??null,project:s=Sr("OPENAI_PROJECT_ID")??null,webhookSecret:a=Sr("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(sl.add(this),yi.set(this,void 0),this.completions=new Ng(this),this.chat=new Zu(this),this.embeddings=new Lg(this),this.files=new Dg(this),this.images=new qg(this),this.audio=new bs(this),this.moderations=new Hg(this),this.models=new Vg(this),this.fineTuning=new Ir(this),this.graders=new el(this),this.vectorStores=new gi(this),this.webhooks=new o_(this),this.beta=new xr(this),this.batches=new yg(this),this.uploads=new rl(this),this.responses=new mi(this),this.realtime=new hi(this),this.conversations=new Wu(this),this.evals=new Ku(this),this.containers=new Gu(this),this.videos=new a_(this),n===void 0)throw new ee("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");const o={apiKey:n,organization:r,project:s,webhookSecret:a,...i,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&oA())throw new ee(`It looks like you\'re running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the \\`dangerouslyAllowBrowser\\` option to \\`true\\`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n`);this.baseURL=o.baseURL,this.timeout=o.timeout??al.DEFAULT_TIMEOUT,this.logger=o.logger??console;const c="warn";this.logLevel=c,this.logLevel=Nm(o.logLevel,"ClientOptions.logLevel",this)??Nm(Sr("OPENAI_LOG"),"process.env[\'OPENAI_LOG\']",this)??c,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??hA(),re(this,yi,pA),this._options=o,this.apiKey=typeof n=="string"?n:"Missing Key",this.organization=r,this.project=s,this.webhookSecret=a}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){}async authHeaders(e){return U([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return bA(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${br}`}defaultIdempotencyKey(){return`stainless-node-retry-${rm()}`}makeStatusError(e,n,r,s){return Qe.generate(e,n,r,s)}async _callApiKey(){const e=this._options.apiKey;if(typeof e!="function")return!1;let n;try{n=await e()}catch(r){throw r instanceof ee?r:new ee(`Failed to get token from \'apiKey\' function: ${r.message}`,{cause:r})}if(typeof n!="string"||!n)throw new ee(`Expected \'apiKey\' function argument to return a string but it returned ${n}`);return this.apiKey=n,!0}buildURL(e,n,r){const s=!T(this,sl,"m",c_).call(this)&&r||this.baseURL,a=nA(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return rA(i)||(n={...i,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(a.search=this.stringifyQuery(n)),a.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:n,options:r}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(s=>({method:e,path:n,...s})))}request(e,n=null){return new Ba(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){const s=await e,a=s.maxRetries??this.maxRetries;n==null&&(n=a),await this.prepareOptions(s);const{req:i,url:o,timeout:c}=await this.buildRequest(s,{retryCount:a-n});await this.prepareRequest(i,{url:o,options:s});const u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(et(this).debug(`[${u}] sending request`,Wn({retryOfRequestLogID:r,method:s.method,url:o,options:s,headers:i.headers})),s.signal?.aborted)throw new Et;const f=new AbortController,h=await this.fetchWithTimeout(o,i,c,f).catch(_u),p=Date.now();if(h instanceof globalThis.Error){const v=`retrying, ${n} attempts remaining`;if(s.signal?.aborted)throw new Et;const w=gu(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(n)return et(this).info(`[${u}] connection ${w?"timed out":"failed"} - ${v}`),et(this).debug(`[${u}] connection ${w?"timed out":"failed"} (${v})`,Wn({retryOfRequestLogID:r,url:o,durationMs:p-d,message:h.message})),this.retryRequest(s,n,r??u);throw et(this).info(`[${u}] connection ${w?"timed out":"failed"} - error; no more retries left`),et(this).debug(`[${u}] connection ${w?"timed out":"failed"} (error; no more retries left)`,Wn({retryOfRequestLogID:r,url:o,durationMs:p-d,message:h.message})),w?new Da:new ja({cause:h})}const m=[...h.headers.entries()].filter(([v])=>v==="x-request-id").map(([v,w])=>", "+v+": "+JSON.stringify(w)).join(""),y=`[${u}${l}${m}] ${i.method} ${o} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${p-d}ms`;if(!h.ok){const v=await this.shouldRetry(h);if(n&&v){const j=`retrying, ${n} attempts remaining`;return await fA(h.body),et(this).info(`${y} - ${j}`),et(this).debug(`[${u}] response error (${j})`,Wn({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:p-d})),this.retryRequest(s,n,r??u,h.headers)}const w=v?"error; no more retries left":"error; not retryable";et(this).info(`${y} - ${w}`);const E=await h.text().catch(j=>_u(j).message),x=iA(E),A=x?void 0:E;throw et(this).debug(`[${u}] response error (${w})`,Wn({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,message:A,durationMs:Date.now()-d})),this.makeStatusError(h.status,x,A,h.headers)}return et(this).info(y),et(this).debug(`[${u}] response start`,Wn({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:p-d})),{response:h,options:s,controller:f,requestLogID:u,retryOfRequestLogID:r,startTime:d}}getAPIList(e,n,r){return this.requestAPIList(n,{method:"get",path:e,...r})}requestAPIList(e,n){const r=this.makeRequest(n,null,void 0);return new OA(this,r,e)}async fetchWithTimeout(e,n,r,s){const{signal:a,method:i,...o}=n||{};a&&a.addEventListener("abort",()=>s.abort());const c=setTimeout(()=>s.abort(),r),u=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,l={signal:s.signal,...u?{duplex:"half"}:{},method:"GET",...o};i&&(l.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,l)}finally{clearTimeout(c)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,r,s){let a;const i=s?.get("retry-after-ms");if(i){const c=parseFloat(i);Number.isNaN(c)||(a=c)}const o=s?.get("retry-after");if(o&&!a){const c=parseFloat(o);Number.isNaN(c)?a=Date.parse(o)-Date.now():a=c*1e3}if(!(a&&0<=a&&a<60*1e3)){const c=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(n,c)}return await us(a),this.makeRequest(e,n-1,r)}calculateDefaultRetryTimeoutMillis(e,n){const a=n-e,i=Math.min(.5*Math.pow(2,a),8),o=1-Math.random()*.25;return i*o*1e3}async buildRequest(e,{retryCount:n=0}={}){const r={...e},{method:s,path:a,query:i,defaultBaseURL:o}=r,c=this.buildURL(a,i,o);"timeout"in r&&aA("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:u,body:l}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:s,bodyHeaders:u,retryCount:n});return{req:{method:s,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...r.fetchOptions??{}},url:c,timeout:r.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:r,retryCount:s}){let a={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);const i=U([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...dA(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};const r=U([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:bm(e)}:T(this,yi,"f").call(this,{body:e,headers:r})}}al=pe,yi=new WeakMap,sl=new WeakSet,c_=function(){return this.baseURL!=="https://api.openai.com/v1"},pe.OpenAI=al,pe.DEFAULT_TIMEOUT=6e5,pe.OpenAIError=ee,pe.APIError=Qe,pe.APIConnectionError=ja,pe.APIConnectionTimeoutError=Da,pe.APIUserAbortError=Et,pe.NotFoundError=om,pe.ConflictError=cm,pe.RateLimitError=lm,pe.BadRequestError=sm,pe.AuthenticationError=am,pe.InternalServerError=dm,pe.PermissionDeniedError=im,pe.UnprocessableEntityError=um,pe.InvalidWebhookSignatureError=cs,pe.toFile=PA,pe.Completions=Ng,pe.Chat=Zu,pe.Embeddings=Lg,pe.Files=Dg,pe.Images=qg,pe.Audio=bs,pe.Moderations=Hg,pe.Models=Vg,pe.FineTuning=Ir,pe.Graders=el,pe.VectorStores=gi,pe.Webhooks=o_,pe.Beta=xr,pe.Batches=yg,pe.Uploads=rl,pe.Responses=mi,pe.Realtime=hi,pe.Conversations=Wu,pe.Evals=Ku,pe.Containers=Gu,pe.Videos=a_;function ak(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===Da.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===Et.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=La(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=La(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=La(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=La(t,"MODEL_NOT_FOUND"):e=t,e}const wi=(t,e)=>{const n=[...new Set(e?.map(s=>{if(typeof s=="string")return s;const a=new s({});if(!("getType"in a)||typeof a.getType!="function")throw new Error("Invalid type provided.");return a.getType()}))],r=t.getType();return n.some(s=>s===r)};function ik(t,e){return Array.isArray(t)?u_(t,e):Pn.from(n=>u_(n,t))}function u_(t,e={}){const{includeNames:n,excludeNames:r,includeTypes:s,excludeTypes:a,includeIds:i,excludeIds:o}=e,c=[];for(const u of t)if(!(r&&u.name&&r.includes(u.name))){{if(a&&wi(u,a))continue;if(o&&u.id&&o.includes(u.id))continue}s||i||n?(n&&u.name&&n.some(l=>l===u.name)||s&&wi(u,s)||i&&u.id&&i.some(l=>l===u.id))&&c.push(u):c.push(u)}return c}function ok(t){return Array.isArray(t)?l_(t):Pn.from(l_)}function l_(t){if(!t.length)return[];const e=[];for(const n of t){const r=n,s=e.pop();if(!s)e.push(r);else if(r.getType()==="tool"||r.getType()!==s.getType())e.push(s,r);else{const a=Vs(s),i=Vs(r),o=a.concat(i);typeof a.content=="string"&&typeof i.content=="string"&&(o.content=`${a.content}\n${i.content}`),e.push(lk(o))}}return e}function ck(t,e){if(Array.isArray(t)){const n=t;if(!e)throw new Error("Options parameter is required when providing messages.");return d_(n,e)}else{const n=t;return Pn.from(r=>d_(r,n)).withConfig({runName:"trim_messages"})}}async function d_(t,e){const{maxTokens:n,tokenCounter:r,strategy:s="last",allowPartial:a=!1,endOn:i,startOn:o,includeSystem:c=!1,textSplitter:u}=e;if(o&&s==="first")throw new Error("`startOn` should only be specified if `strategy` is \'last\'.");if(c&&s==="first")throw new Error("`includeSystem` should only be specified if `strategy` is \'last\'.");let l;"getNumTokens"in r?l=async f=>(await Promise.all(f.map(p=>r.getNumTokens(p.content)))).reduce((p,m)=>p+m,0):l=async f=>r(f);let d=p_;if(u&&("splitText"in u?d=u.splitText:d=async f=>u(f)),s==="first")return h_(t,{maxTokens:n,tokenCounter:l,textSplitter:d,partialStrategy:a?"first":void 0,endOn:i});if(s==="last")return uk(t,{maxTokens:n,tokenCounter:l,textSplitter:d,allowPartial:a,includeSystem:c,startOn:o,endOn:i});throw new Error(`Unrecognized strategy: \'${s}\'. Must be one of \'first\' or \'last\'.`)}async function h_(t,e){const{maxTokens:n,tokenCounter:r,textSplitter:s,partialStrategy:a,endOn:i}=e;let o=[...t],c=0;for(let u=0;u<o.length;u+=1){const l=u>0?o.slice(0,-u):o;if(await r(l)<=n){c=o.length-u;break}}if(c<o.length&&a){let u=!1;if(Array.isArray(o[c].content)){const l=o[c];if(typeof l.content=="string")throw new Error("Expected content to be an array.");const d=l.content.length,f=a==="last"?[...l.content].reverse():l.content;for(let h=1;h<=d;h+=1){const p=a==="first"?f.slice(0,h):f.slice(-h),m=Object.fromEntries(Object.entries(l).filter(([w])=>w!=="type"&&!w.startsWith("lc_"))),y=il(l.getType(),{...m,content:p}),v=[...o.slice(0,c),y];if(await r(v)<=n)o=v,c+=1,u=!0;else break}u&&a==="last"&&(l.content=[...f].reverse())}if(!u){const l=o[c];let d;if(Array.isArray(l.content)&&l.content.some(f=>typeof f=="string"||f.type==="text")?d=l.content.find(h=>h.type==="text"&&h.text)?.text:typeof l.content=="string"&&(d=l.content),d){const f=await s(d),h=f.length;a==="last"&&f.reverse();for(let p=0;p<h-1;p+=1)if(f.pop(),l.content=f.join(""),await r([...o.slice(0,c),l])<=n){a==="last"&&(l.content=[...f].reverse().join("")),o=[...o.slice(0,c),l],c+=1;break}}}}if(i){const u=Array.isArray(i)?i:[i];for(;c>0&&!wi(o[c-1],u);)c-=1}return o.slice(0,c)}async function uk(t,e){const{allowPartial:n=!1,includeSystem:r=!1,endOn:s,startOn:a,...i}=e;let o=t.map(l=>{const d=Object.fromEntries(Object.entries(l).filter(([f])=>f!=="type"&&!f.startsWith("lc_")));return il(l.getType(),d,Bi(l))});if(s){const l=Array.isArray(s)?s:[s];for(;o.length>0&&!wi(o[o.length-1],l);)o=o.slice(0,-1)}const c=r&&o[0]?.getType()==="system";let u=c?o.slice(0,1).concat(o.slice(1).reverse()):o.reverse();return u=await h_(u,{...i,partialStrategy:n?"last":void 0,endOn:a}),c?[u[0],...u.slice(1).reverse()]:u.reverse()}const f_={human:{message:an,messageChunk:Zs},ai:{message:on,messageChunk:zn},system:{message:vn,messageChunk:nr},developer:{message:vn,messageChunk:nr},tool:{message:bn,messageChunk:Ds},function:{message:Us,messageChunk:Bs},generic:{message:Lr,messageChunk:Fs},remove:{message:qs,messageChunk:qs}};function il(t,e,n){let r,s;switch(t){case"human":n?r=new Zs(e):s=new an(e);break;case"ai":if(n){let a={...e};"tool_calls"in a&&(a={...a,tool_call_chunks:a.tool_calls?.map(i=>({...i,type:"tool_call_chunk",index:void 0,args:JSON.stringify(i.args)}))}),r=new zn(a)}else s=new on(e);break;case"system":n?r=new nr(e):s=new vn(e);break;case"developer":n?r=new nr({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}}):s=new vn({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in e)n?r=new Ds(e):s=new bn(e);else throw new Error("Can not convert ToolMessage to ToolMessageChunk if \'tool_call_id\' field is not defined.");break;case"function":if(n)r=new Bs(e);else{if(!e.name)throw new Error("FunctionMessage must have a \'name\' field");s=new Us(e)}break;case"generic":if("role"in e)n?r=new Fs(e):s=new Lr(e);else throw new Error("Can not convert ChatMessage to ChatMessageChunk if \'role\' field is not defined.");break;default:throw new Error(`Unrecognized message type ${t}`)}if(n&&r)return r;if(s)return s;throw new Error(`Unrecognized message type ${t}`)}function lk(t){const e=t.getType();let n;const r=Object.fromEntries(Object.entries(t).filter(([s])=>!["type","tool_call_chunks"].includes(s)&&!s.startsWith("lc_")));if(e in f_&&(n=il(e,r)),!n)throw new Error(`Unrecognized message chunk class ${e}. Supported classes are ${Object.keys(f_)}`);return n}function p_(t){const e=t.split(`\n`);return Promise.resolve([...e.slice(0,-1).map(n=>`${n}\n`),e[e.length-1]])}const dk=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"],hk=["image","video","audio","text-plain","file"],fk=["text","reasoning",...dk,...hk];var pk={};ge(pk,{AIMessage:()=>on,AIMessageChunk:()=>zn,BaseMessage:()=>sn,BaseMessageChunk:()=>yn,ChatMessage:()=>Lr,ChatMessageChunk:()=>Fs,DEFAULT_MERGE_IGNORE_KEYS:()=>Ul,FunctionMessage:()=>Us,FunctionMessageChunk:()=>Bs,HumanMessage:()=>an,HumanMessageChunk:()=>Zs,KNOWN_BLOCK_TYPES:()=>fk,RemoveMessage:()=>qs,SystemMessage:()=>vn,SystemMessageChunk:()=>nr,ToolMessage:()=>bn,ToolMessageChunk:()=>Ds,_isMessageFieldWithRole:()=>Zl,_mergeDicts:()=>rt,_mergeLists:()=>Mr,_mergeObj:()=>Bl,_mergeStatus:()=>Fl,coerceMessageLikeToMessage:()=>jr,collapseToolCallChunks:()=>rd,convertToChunk:()=>Vs,convertToOpenAIImageBlock:()=>Pl,convertToProviderContentBlock:()=>Ny,defaultTextSplitter:()=>p_,defaultToolCallParser:()=>qi,filterMessages:()=>ik,getBufferString:()=>Xi,iife:()=>ww,isAIMessage:()=>Wi,isAIMessageChunk:()=>Ji,isBase64ContentBlock:()=>ji,isBaseMessage:()=>wn,isBaseMessageChunk:()=>Bi,isChatMessage:()=>Qy,isChatMessageChunk:()=>ew,isDataContentBlock:()=>_n,isDirectToolOutput:()=>Zi,isFunctionMessage:()=>tw,isFunctionMessageChunk:()=>nw,isHumanMessage:()=>rw,isHumanMessageChunk:()=>sw,isIDContentBlock:()=>Nl,isMessage:()=>zl,isOpenAIToolCallArray:()=>Ky,isPlainTextContentBlock:()=>Cy,isSystemMessage:()=>aw,isSystemMessageChunk:()=>iw,isToolMessage:()=>ql,isToolMessageChunk:()=>Vl,isURLContentBlock:()=>Li,mapChatMessagesToStoredMessages:()=>Tw,mapStoredMessageToChatMessage:()=>Yi,mapStoredMessagesToChatMessages:()=>Sw,mergeContent:()=>rn,mergeMessageRuns:()=>ok,mergeResponseMetadata:()=>td,mergeUsageMetadata:()=>Gi,parseBase64DataUrl:()=>Di,parseMimeType:()=>Ry,trimMessages:()=>ck});const mk=t=>t();function gk(t){const{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:n,azureOpenAIApiKey:r,azureOpenAIBasePath:s,baseURL:a,azureADTokenProvider:i,azureOpenAIEndpoint:o}=t;if((r||i)&&s&&e)return`${s}/${e}`;if((r||i)&&o&&e)return`${o}/openai/deployments/${e}`;if(r||i){if(!n)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${n}.openai.azure.com/openai/deployments/${e}`}return a}function m_(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function _k(t){const e=mk(()=>{if(m_(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&m_(t.values))return t.values;if(typeof t=="object"&&t!==null){const n=Object.entries(t).filter(([,r])=>typeof r=="string").map(([r,s])=>[r,s]);return new Headers(n)}return new Headers});return Object.fromEntries(e.entries())}function yk(){let t=Qi();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function wk(t,e=!1,n="1.0.0"){const r=_k(t),s=yk(),a=`langchainjs${e?"-azure":""}-openai`;return{...r,"User-Agent":r["User-Agent"]?`${a}/${n} (${s})${r["User-Agent"]}`:`${a}/${n} (${s})`}}function ol(t){return t!==void 0&&Array.isArray(t.lc_namespace)}function cl(t){return t!==void 0&&Pe.isRunnable(t)&&"lc_name"in t.constructor&&typeof t.constructor.lc_name=="function"&&t.constructor.lc_name()==="RunnableToolLike"}function ul(t){return!!t&&typeof t=="object"&&"name"in t&&"schema"in t&&(dr(t.schema)||t.schema!=null&&typeof t.schema=="object"&&"type"in t.schema&&typeof t.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(t.schema.type))}function ll(t){return ul(t)||cl(t)||ol(t)}var bk={};ge(bk,{convertToOpenAIFunction:()=>g_,convertToOpenAITool:()=>vk,isLangChainTool:()=>ll,isRunnableToolLike:()=>cl,isStructuredTool:()=>ol,isStructuredToolParams:()=>ul});function g_(t,e){const n=typeof e=="number"?void 0:e;return{name:t.name,description:t.description,parameters:_r(t.schema),...n?.strict!==void 0?{strict:n.strict}:{}}}function vk(t,e){const n=typeof e=="number"?void 0:e;let r;return ll(t)?r={type:"function",function:g_(t)}:r=t,n?.strict!==void 0&&(r.function.strict=n.strict),r}var Ek={};ge(Ek,{extendInteropZodObject:()=>RT,getInteropZodDefaultGetter:()=>PT,getInteropZodObjectShape:()=>Hc,getSchemaDescription:()=>Zc,interopParse:()=>OT,interopParseAsync:()=>Ea,interopSafeParse:()=>kT,interopSafeParseAsync:()=>dp,interopZodObjectMakeFieldsOptional:()=>jT,interopZodObjectPartial:()=>NT,interopZodObjectPassthrough:()=>Gc,interopZodObjectStrict:()=>Ta,interopZodTransformInputSchema:()=>pp,isInteropZodError:()=>mp,isInteropZodLiteral:()=>AT,isInteropZodObject:()=>CT,isInteropZodSchema:()=>dr,isShapelessZodSchema:()=>$T,isSimpleStringZodSchema:()=>qc,isZodArrayV4:()=>Sa,isZodLiteralV3:()=>up,isZodLiteralV4:()=>lp,isZodNullableV4:()=>fp,isZodObjectV3:()=>Vc,isZodObjectV4:()=>Yt,isZodOptionalV4:()=>hp,isZodSchema:()=>IT,isZodSchemaV3:()=>Ve,isZodSchemaV4:()=>Ne});const Sk=I("ZodISODateTime",(t,e)=>{cS.init(t,e),Me.init(t,e)});function Tk(t){return cT(Sk,t)}const xk=I("ZodISODate",(t,e)=>{uS.init(t,e),Me.init(t,e)});function Ik(t){return uT(xk,t)}const Ak=I("ZodISOTime",(t,e)=>{lS.init(t,e),Me.init(t,e)});function kk(t){return lT(Ak,t)}const Ok=I("ZodISODuration",(t,e)=>{dS.init(t,e),Me.init(t,e)});function $k(t){return dT(Ok,t)}const bi=I("ZodError",(t,e)=>{xf.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>iE(t,n)},flatten:{value:n=>aE(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},{Parent:Error}),Ck=If(bi),Rk=Af(bi),Nk=Of(bi),Pk=$f(bi),De=I("ZodType",(t,e)=>(Re.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>st(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>Ck(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Nk(t,n,r),t.parseAsync=async(n,r)=>Rk(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Pk(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(AO(n,r)),t.superRefine=n=>t.check(kO(n)),t.overwrite=n=>t.check(rs(n)),t.optional=()=>T_(t),t.nullable=()=>x_(t),t.nullish=()=>T_(x_(t)),t.nonoptional=n=>wO(t,n),t.array=()=>xs(t),t.or=n=>aO([t,n]),t.and=n=>cO(t,n),t.transform=n=>A_(t,fO(n)),t.default=n=>gO(t,n),t.prefault=n=>yO(t,n),t.catch=n=>vO(t,n),t.pipe=n=>A_(t,n),t.readonly=()=>TO(t),t.describe=n=>{const r=t.clone();return Je.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return Je.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return Je.get(t);const r=t.clone();return Je.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),__=I("_ZodString",(t,e)=>{Dc.init(t,e),De.init(t,e);const n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(pT(...r)),t.includes=(...r)=>t.check(_T(...r)),t.startsWith=(...r)=>t.check(yT(...r)),t.endsWith=(...r)=>t.check(wT(...r)),t.min=(...r)=>t.check(va(...r)),t.max=(...r)=>t.check(ap(...r)),t.length=(...r)=>t.check(ip(...r)),t.nonempty=(...r)=>t.check(va(1,...r)),t.lowercase=r=>t.check(mT(r)),t.uppercase=r=>t.check(gT(r)),t.trim=()=>t.check(vT()),t.normalize=(...r)=>t.check(bT(...r)),t.toLowerCase=()=>t.check(ET()),t.toUpperCase=()=>t.check(ST())}),Mk=I("ZodString",(t,e)=>{Dc.init(t,e),__.init(t,e),t.email=n=>t.check(US(Lk,n)),t.url=n=>t.check(HS(jk,n)),t.jwt=n=>t.check(oT(Yk,n)),t.emoji=n=>t.check(GS(Dk,n)),t.guid=n=>t.check(Qf(y_,n)),t.uuid=n=>t.check(BS(vi,n)),t.uuidv4=n=>t.check(ZS(vi,n)),t.uuidv6=n=>t.check(qS(vi,n)),t.uuidv7=n=>t.check(VS(vi,n)),t.nanoid=n=>t.check(WS(zk,n)),t.guid=n=>t.check(Qf(y_,n)),t.cuid=n=>t.check(JS(Fk,n)),t.cuid2=n=>t.check(KS(Uk,n)),t.ulid=n=>t.check(XS(Bk,n)),t.base64=n=>t.check(sT(Jk,n)),t.base64url=n=>t.check(aT(Kk,n)),t.xid=n=>t.check(YS(Zk,n)),t.ksuid=n=>t.check(QS(qk,n)),t.ipv4=n=>t.check(eT(Vk,n)),t.ipv6=n=>t.check(tT(Hk,n)),t.cidrv4=n=>t.check(nT(Gk,n)),t.cidrv6=n=>t.check(rT(Wk,n)),t.e164=n=>t.check(iT(Xk,n)),t.datetime=n=>t.check(Tk(n)),t.date=n=>t.check(Ik(n)),t.time=n=>t.check(kk(n)),t.duration=n=>t.check($k(n))});function It(t){return FS(Mk,t)}const Me=I("ZodStringFormat",(t,e)=>{$e.init(t,e),__.init(t,e)}),Lk=I("ZodEmail",(t,e)=>{QE.init(t,e),Me.init(t,e)}),y_=I("ZodGUID",(t,e)=>{XE.init(t,e),Me.init(t,e)}),vi=I("ZodUUID",(t,e)=>{YE.init(t,e),Me.init(t,e)}),jk=I("ZodURL",(t,e)=>{eS.init(t,e),Me.init(t,e)}),Dk=I("ZodEmoji",(t,e)=>{tS.init(t,e),Me.init(t,e)}),zk=I("ZodNanoID",(t,e)=>{nS.init(t,e),Me.init(t,e)}),Fk=I("ZodCUID",(t,e)=>{rS.init(t,e),Me.init(t,e)}),Uk=I("ZodCUID2",(t,e)=>{sS.init(t,e),Me.init(t,e)}),Bk=I("ZodULID",(t,e)=>{aS.init(t,e),Me.init(t,e)}),Zk=I("ZodXID",(t,e)=>{iS.init(t,e),Me.init(t,e)}),qk=I("ZodKSUID",(t,e)=>{oS.init(t,e),Me.init(t,e)}),Vk=I("ZodIPv4",(t,e)=>{hS.init(t,e),Me.init(t,e)}),Hk=I("ZodIPv6",(t,e)=>{fS.init(t,e),Me.init(t,e)}),Gk=I("ZodCIDRv4",(t,e)=>{pS.init(t,e),Me.init(t,e)}),Wk=I("ZodCIDRv6",(t,e)=>{mS.init(t,e),Me.init(t,e)}),Jk=I("ZodBase64",(t,e)=>{gS.init(t,e),Me.init(t,e)}),Kk=I("ZodBase64URL",(t,e)=>{yS.init(t,e),Me.init(t,e)}),Xk=I("ZodE164",(t,e)=>{wS.init(t,e),Me.init(t,e)}),Yk=I("ZodJWT",(t,e)=>{vS.init(t,e),Me.init(t,e)}),w_=I("ZodNumber",(t,e)=>{zf.init(t,e),De.init(t,e),t.gt=(r,s)=>t.check(rp(r,s)),t.gte=(r,s)=>t.check(Bc(r,s)),t.min=(r,s)=>t.check(Bc(r,s)),t.lt=(r,s)=>t.check(np(r,s)),t.lte=(r,s)=>t.check(Uc(r,s)),t.max=(r,s)=>t.check(Uc(r,s)),t.int=r=>t.check(b_(r)),t.safe=r=>t.check(b_(r)),t.positive=r=>t.check(rp(0,r)),t.nonnegative=r=>t.check(Bc(0,r)),t.negative=r=>t.check(np(0,r)),t.nonpositive=r=>t.check(Uc(0,r)),t.multipleOf=(r,s)=>t.check(sp(r,s)),t.step=(r,s)=>t.check(sp(r,s)),t.finite=()=>t;const n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function at(t){return hT(w_,t)}const Qk=I("ZodNumberFormat",(t,e)=>{ES.init(t,e),w_.init(t,e)});function b_(t){return fT(Qk,t)}const eO=I("ZodUnknown",(t,e)=>{Ff.init(t,e),De.init(t,e)});function v_(){return ep(eO)}const tO=I("ZodNever",(t,e)=>{Uf.init(t,e),De.init(t,e)});function nO(t){return tp(tO,t)}const rO=I("ZodArray",(t,e)=>{SS.init(t,e),De.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(va(n,r)),t.nonempty=n=>t.check(va(1,n)),t.max=(n,r)=>t.check(ap(n,r)),t.length=(n,r)=>t.check(ip(n,r)),t.unwrap=()=>t.element});function xs(t,e){return TT(rO,t,e)}const sO=I("ZodObject",(t,e)=>{TS.init(t,e),De.init(t,e),ke(t,"shape",()=>e.shape),t.keyof=()=>fl(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:v_()}),t.loose=()=>t.clone({...t._zod.def,catchall:v_()}),t.strict=()=>t.clone({...t._zod.def,catchall:nO()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>Ef(t,n),t.merge=n=>rE(t,n),t.pick=n=>tE(t,n),t.omit=n=>nE(t,n),t.partial=(...n)=>Sf(S_,t,n[0]),t.required=(...n)=>sE(I_,t,n[0])});function it(t,e){const n={type:"object",get shape(){return Mc(this,"shape",{...t}),this.shape},...Q(e)};return new sO(n)}const E_=I("ZodUnion",(t,e)=>{Vf.init(t,e),De.init(t,e),t.options=e.options});function aO(t,e){return new E_({type:"union",options:t,...Q(e)})}const iO=I("ZodDiscriminatedUnion",(t,e)=>{E_.init(t,e),xS.init(t,e)});function dl(t,e,n){return new iO({type:"union",options:e,discriminator:t,...Q(n)})}const oO=I("ZodIntersection",(t,e)=>{IS.init(t,e),De.init(t,e)});function cO(t,e){return new oO({type:"intersection",left:t,right:e})}const uO=I("ZodRecord",(t,e)=>{AS.init(t,e),De.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function lO(t,e,n){return new uO({type:"record",keyType:t,valueType:e,...Q(n)})}const hl=I("ZodEnum",(t,e)=>{kS.init(t,e),De.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const n=new Set(Object.keys(e.entries));t.extract=(r,s)=>{const a={};for(const i of r)if(n.has(i))a[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new hl({...e,checks:[],...Q(s),entries:a})},t.exclude=(r,s)=>{const a={...e.entries};for(const i of r)if(n.has(i))delete a[i];else throw new Error(`Key ${i} not found in enum`);return new hl({...e,checks:[],...Q(s),entries:a})}});function fl(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new hl({type:"enum",entries:n,...Q(e)})}const dO=I("ZodLiteral",(t,e)=>{OS.init(t,e),De.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function At(t,e){return new dO({type:"literal",values:Array.isArray(t)?t:[t],...Q(e)})}const hO=I("ZodTransform",(t,e)=>{$S.init(t,e),De.init(t,e),t._zod.parse=(n,r)=>{n.addIssue=a=>{if(typeof a=="string")n.issues.push(ns(a,n.value,e));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),n.issues.push(ns(i))}};const s=e.transform(n.value,n);return s instanceof Promise?s.then(a=>(n.value=a,n)):(n.value=s,n)}});function fO(t){return new hO({type:"transform",transform:t})}const S_=I("ZodOptional",(t,e)=>{Fc.init(t,e),De.init(t,e),t.unwrap=()=>t._zod.def.innerType});function T_(t){return new S_({type:"optional",innerType:t})}const pO=I("ZodNullable",(t,e)=>{CS.init(t,e),De.init(t,e),t.unwrap=()=>t._zod.def.innerType});function x_(t){return new pO({type:"nullable",innerType:t})}const mO=I("ZodDefault",(t,e)=>{RS.init(t,e),De.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function gO(t,e){return new mO({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const _O=I("ZodPrefault",(t,e)=>{NS.init(t,e),De.init(t,e),t.unwrap=()=>t._zod.def.innerType});function yO(t,e){return new _O({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const I_=I("ZodNonOptional",(t,e)=>{PS.init(t,e),De.init(t,e),t.unwrap=()=>t._zod.def.innerType});function wO(t,e){return new I_({type:"nonoptional",innerType:t,...Q(e)})}const bO=I("ZodCatch",(t,e)=>{MS.init(t,e),De.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function vO(t,e){return new bO({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const EO=I("ZodPipe",(t,e)=>{LS.init(t,e),De.init(t,e),t.in=e.in,t.out=e.out});function A_(t,e){return new EO({type:"pipe",in:t,out:e})}const SO=I("ZodReadonly",(t,e)=>{jS.init(t,e),De.init(t,e)});function TO(t){return new SO({type:"readonly",innerType:t})}const xO=I("ZodCustom",(t,e)=>{DS.init(t,e),De.init(t,e)});function IO(t){const e=new mt({check:"custom"});return e._zod.check=t,e}function AO(t,e={}){return xT(xO,t,e)}function kO(t){const e=IO(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(ns(r,n.value,e._zod.def));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),n.issues.push(ns(s))}},t(n.value,n)));return e}var OO={};ge(OO,{BasePromptValue:()=>Ei,ChatPromptValue:()=>O_,ImagePromptValue:()=>$O,StringPromptValue:()=>k_});var Ei=class extends Dn{},k_=class extends Ei{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(t){super({value:t}),this.value=t}toString(){return this.value}toChatMessages(){return[new an(this.value)]}},O_=class extends Ei{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(t){Array.isArray(t)&&(t={messages:t}),super(t),this.messages=t.messages}toString(){return Xi(this.messages)}toChatMessages(){return this.messages}},$O=class extends Ei{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(t){"imageUrl"in t||(t={imageUrl:t}),super(t),this.imageUrl=t.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new an({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},B="0123456789abcdef".split(""),CO=[-2147483648,8388608,32768,128],Vt=[24,16,8,0],Si=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],Xe=[];function Ht(t,e){e?(Xe[0]=Xe[16]=Xe[1]=Xe[2]=Xe[3]=Xe[4]=Xe[5]=Xe[6]=Xe[7]=Xe[8]=Xe[9]=Xe[10]=Xe[11]=Xe[12]=Xe[13]=Xe[14]=Xe[15]=0,this.blocks=Xe):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=t}Ht.prototype.update=function(t){if(!this.finalized){var e,n=typeof t;if(n!=="string"){if(n==="object"){if(t===null)throw new Error(ERROR);if(ARRAY_BUFFER&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!Array.isArray(t)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(t)))throw new Error(ERROR)}else throw new Error(ERROR);e=!0}for(var r,s=0,a,i=t.length,o=this.blocks;s<i;){if(this.hashed&&(this.hashed=!1,o[0]=this.block,this.block=o[16]=o[1]=o[2]=o[3]=o[4]=o[5]=o[6]=o[7]=o[8]=o[9]=o[10]=o[11]=o[12]=o[13]=o[14]=o[15]=0),e)for(a=this.start;s<i&&a<64;++s)o[a>>>2]|=t[s]<<Vt[a++&3];else for(a=this.start;s<i&&a<64;++s)r=t.charCodeAt(s),r<128?o[a>>>2]|=r<<Vt[a++&3]:r<2048?(o[a>>>2]|=(192|r>>>6)<<Vt[a++&3],o[a>>>2]|=(128|r&63)<<Vt[a++&3]):r<55296||r>=57344?(o[a>>>2]|=(224|r>>>12)<<Vt[a++&3],o[a>>>2]|=(128|r>>>6&63)<<Vt[a++&3],o[a>>>2]|=(128|r&63)<<Vt[a++&3]):(r=65536+((r&1023)<<10|t.charCodeAt(++s)&1023),o[a>>>2]|=(240|r>>>18)<<Vt[a++&3],o[a>>>2]|=(128|r>>>12&63)<<Vt[a++&3],o[a>>>2]|=(128|r>>>6&63)<<Vt[a++&3],o[a>>>2]|=(128|r&63)<<Vt[a++&3]);this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=o[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},Ht.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=CO[e&3],this.block=t[16],e>=56&&(this.hashed||this.hash(),t[0]=this.block,t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.hBytes<<3|this.bytes>>>29,t[15]=this.bytes<<3,this.hash()}},Ht.prototype.hash=function(){var t=this.h0,e=this.h1,n=this.h2,r=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,c=this.blocks,u,l,d,f,h,p,m,y,v,w,E;for(u=16;u<64;++u)h=c[u-15],l=(h>>>7|h<<25)^(h>>>18|h<<14)^h>>>3,h=c[u-2],d=(h>>>17|h<<15)^(h>>>19|h<<13)^h>>>10,c[u]=c[u-16]+l+c[u-7]+d<<0;for(E=e&n,u=0;u<64;u+=4)this.first?(this.is224?(y=300032,h=c[0]-1413257819,o=h-150054599<<0,r=h+24177077<<0):(y=704751109,h=c[0]-210244248,o=h-1521486534<<0,r=h+143694565<<0),this.first=!1):(l=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),y=t&e,f=y^t&n^E,m=s&a^~s&i,h=o+d+m+Si[u]+c[u],p=l+f,o=r+h<<0,r=h+p<<0),l=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),v=r&t,f=v^r&e^y,m=i&o^~i&s,h=a+d+m+Si[u+1]+c[u+1],p=l+f,i=n+h<<0,n=h+p<<0,l=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),w=n&r,f=w^n&t^v,m=a&i^~a&o,h=s+d+m+Si[u+2]+c[u+2],p=l+f,a=e+h<<0,e=h+p<<0,l=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),E=e&n,f=E^e&r^w,m=a&i^~a&o,h=s+d+m+Si[u+3]+c[u+3],p=l+f,s=t+h<<0,t=h+p<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+t<<0,this.h1=this.h1+e<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+s<<0,this.h5=this.h5+a<<0,this.h6=this.h6+i<<0,this.h7=this.h7+o<<0},Ht.prototype.hex=function(){this.finalize();var t=this.h0,e=this.h1,n=this.h2,r=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,c=B[t>>>28&15]+B[t>>>24&15]+B[t>>>20&15]+B[t>>>16&15]+B[t>>>12&15]+B[t>>>8&15]+B[t>>>4&15]+B[t&15]+B[e>>>28&15]+B[e>>>24&15]+B[e>>>20&15]+B[e>>>16&15]+B[e>>>12&15]+B[e>>>8&15]+B[e>>>4&15]+B[e&15]+B[n>>>28&15]+B[n>>>24&15]+B[n>>>20&15]+B[n>>>16&15]+B[n>>>12&15]+B[n>>>8&15]+B[n>>>4&15]+B[n&15]+B[r>>>28&15]+B[r>>>24&15]+B[r>>>20&15]+B[r>>>16&15]+B[r>>>12&15]+B[r>>>8&15]+B[r>>>4&15]+B[r&15]+B[s>>>28&15]+B[s>>>24&15]+B[s>>>20&15]+B[s>>>16&15]+B[s>>>12&15]+B[s>>>8&15]+B[s>>>4&15]+B[s&15]+B[a>>>28&15]+B[a>>>24&15]+B[a>>>20&15]+B[a>>>16&15]+B[a>>>12&15]+B[a>>>8&15]+B[a>>>4&15]+B[a&15]+B[i>>>28&15]+B[i>>>24&15]+B[i>>>20&15]+B[i>>>16&15]+B[i>>>12&15]+B[i>>>8&15]+B[i>>>4&15]+B[i&15];return this.is224||(c+=B[o>>>28&15]+B[o>>>24&15]+B[o>>>20&15]+B[o>>>16&15]+B[o>>>12&15]+B[o>>>8&15]+B[o>>>4&15]+B[o&15]),c},Ht.prototype.toString=Ht.prototype.hex,Ht.prototype.digest=function(){this.finalize();var t=this.h0,e=this.h1,n=this.h2,r=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,c=[t>>>24&255,t>>>16&255,t>>>8&255,t&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255];return this.is224||c.push(o>>>24&255,o>>>16&255,o>>>8&255,o&255),c},Ht.prototype.array=Ht.prototype.digest,Ht.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(this.is224?28:32),e=new DataView(t);return e.setUint32(0,this.h0),e.setUint32(4,this.h1),e.setUint32(8,this.h2),e.setUint32(12,this.h3),e.setUint32(16,this.h4),e.setUint32(20,this.h5),e.setUint32(24,this.h6),this.is224||e.setUint32(28,this.h7),t};const $_=(...t)=>new Ht(!1,!0).update(t.join("")).hex();var RO={};ge(RO,{sha256:()=>$_});var NO={};ge(NO,{BaseCache:()=>R_,InMemoryCache:()=>N_,defaultHashKeyEncoder:()=>C_,deserializeStoredGeneration:()=>PO,serializeGeneration:()=>MO});const C_=(...t)=>$_(t.join("_"));function PO(t){return t.message!==void 0?{text:t.text,message:Yi(t.message)}:{text:t.text}}function MO(t){const e={text:t.text};return t.message!==void 0&&(e.message=t.message.toDict()),e}var R_=class{keyEncoder=C_;makeDefaultKeyEncoder(t){this.keyEncoder=t}};const LO=new Map;var N_=class hy extends R_{cache;constructor(e){super(),this.cache=e??new Map}lookup(e,n){return Promise.resolve(this.cache.get(this.keyEncoder(e,n))??null)}async update(e,n,r){this.cache.set(this.keyEncoder(e,n),r)}static global(){return new hy(LO)}},Is={},P_;function jO(){if(P_)return Is;P_=1,Is.byteLength=o,Is.toByteArray=u,Is.fromByteArray=f;for(var t=[],e=[],n=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,a=r.length;s<a;++s)t[s]=r[s],e[r.charCodeAt(s)]=s;e[45]=62,e[95]=63;function i(h){var p=h.length;if(p%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var m=h.indexOf("=");m===-1&&(m=p);var y=m===p?0:4-m%4;return[m,y]}function o(h){var p=i(h),m=p[0],y=p[1];return(m+y)*3/4-y}function c(h,p,m){return(p+m)*3/4-m}function u(h){var p,m=i(h),y=m[0],v=m[1],w=new n(c(h,y,v)),E=0,x=v>0?y-4:y,A;for(A=0;A<x;A+=4)p=e[h.charCodeAt(A)]<<18|e[h.charCodeAt(A+1)]<<12|e[h.charCodeAt(A+2)]<<6|e[h.charCodeAt(A+3)],w[E++]=p>>16&255,w[E++]=p>>8&255,w[E++]=p&255;return v===2&&(p=e[h.charCodeAt(A)]<<2|e[h.charCodeAt(A+1)]>>4,w[E++]=p&255),v===1&&(p=e[h.charCodeAt(A)]<<10|e[h.charCodeAt(A+1)]<<4|e[h.charCodeAt(A+2)]>>2,w[E++]=p>>8&255,w[E++]=p&255),w}function l(h){return t[h>>18&63]+t[h>>12&63]+t[h>>6&63]+t[h&63]}function d(h,p,m){for(var y,v=[],w=p;w<m;w+=3)y=(h[w]<<16&16711680)+(h[w+1]<<8&65280)+(h[w+2]&255),v.push(l(y));return v.join("")}function f(h){for(var p,m=h.length,y=m%3,v=[],w=16383,E=0,x=m-y;E<x;E+=w)v.push(d(h,E,E+w>x?x:E+w));return y===1?(p=h[m-1],v.push(t[p>>2]+t[p<<4&63]+"==")):y===2&&(p=(h[m-2]<<8)+h[m-1],v.push(t[p>>10]+t[p>>4&63]+t[p<<2&63]+"=")),v.join("")}return Is}var DO=jO(),zO=Ms(DO),FO=Object.defineProperty,UO=(t,e,n)=>e in t?FO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,BO=(t,e,n)=>(UO(t,e+"",n),n);function ZO(t,e){let n=Array.from({length:t.length},(r,s)=>({start:s,end:s+1}));for(;n.length>1;){let r=null;for(let s=0;s<n.length-1;s++){const a=t.slice(n[s].start,n[s+1].end),i=e.get(a.join(","));i!=null&&(r==null||i<r[0])&&(r=[i,s])}if(r!=null){const s=r[1];n[s]={start:n[s].start,end:n[s+1].end},n.splice(s+1,1)}else break}return n}function qO(t,e){return t.length===1?[e.get(t.join(","))]:ZO(t,e).map(n=>e.get(t.slice(n.start,n.end).join(","))).filter(n=>n!=null)}function VO(t){return t.replace(/[\\\\^$*+?.()|[\\]{}]/g,"\\\\$&")}var pl=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(t,e){this.patStr=t.pat_str;const n=t.bpe_ranks.split(`\n`).filter(Boolean).reduce((r,s)=>{const[a,i,...o]=s.split(" "),c=Number.parseInt(i,10);return o.forEach((u,l)=>r[u]=c+l),r},{});for(const[r,s]of Object.entries(n)){const a=zO.toByteArray(r);this.rankMap.set(a.join(","),s),this.textMap.set(s,a)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((r,[s,a])=>(r[a]=this.textEncoder.encode(s),r),{})}encode(t,e=[],n="all"){const r=new RegExp(this.patStr,"ug"),s=pl.specialTokenRegex(Object.keys(this.specialTokens)),a=[],i=new Set(e==="all"?Object.keys(this.specialTokens):e),o=new Set(n==="all"?Object.keys(this.specialTokens).filter(u=>!i.has(u)):n);if(o.size>0){const u=pl.specialTokenRegex([...o]),l=t.match(u);if(l!=null)throw new Error(`The text contains a special token that is not allowed: ${l[0]}`)}let c=0;for(;;){let u=null,l=c;for(;s.lastIndex=l,u=s.exec(t),!(u==null||i.has(u[0]));)l=u.index+1;const d=u?.index??t.length;for(const h of t.substring(c,d).matchAll(r)){const p=this.textEncoder.encode(h[0]),m=this.rankMap.get(p.join(","));if(m!=null){a.push(m);continue}a.push(...qO(p,this.rankMap))}if(u==null)break;let f=this.specialTokens[u[0]];a.push(f),c=u.index+u[0].length}return a}decode(t){const e=[];let n=0;for(let a=0;a<t.length;++a){const i=t[a],o=this.textMap.get(i)??this.inverseSpecialTokens[i];o!=null&&(e.push(o),n+=o.length)}const r=new Uint8Array(n);let s=0;for(const a of e)r.set(a,s),s+=a.length;return this.textDecoder.decode(r)}},M_=pl;BO(M_,"specialTokenRegex",t=>new RegExp(t.map(e=>VO(e)).join("|"),"g"));function HO(t){switch(t){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"gpt-5":case"gpt-5-2025-08-07":case"gpt-5-nano":case"gpt-5-nano-2025-08-07":case"gpt-5-mini":case"gpt-5-mini-2025-08-07":case"gpt-5-chat-latest":return"o200k_base";default:throw new Error("Unknown model")}}var GO={};ge(GO,{encodingForModel:()=>ml,getEncoding:()=>L_});const Ti={},WO=new Xr({});async function L_(t){return t in Ti||(Ti[t]=WO.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new M_(e)).catch(e=>{throw delete Ti[t],e})),await Ti[t]}async function ml(t){return L_(HO(t))}var JO={};ge(JO,{BaseLangChain:()=>gl,BaseLanguageModel:()=>_l,calculateMaxTokens:()=>YO,getEmbeddingContextSize:()=>KO,getModelContextSize:()=>j_,getModelNameForTiktoken:()=>xi,isOpenAITool:()=>XO});const xi=t=>t.startsWith("gpt-5")?"gpt-5":t.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":t.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":t.startsWith("gpt-4-32k")?"gpt-4-32k":t.startsWith("gpt-4-")?"gpt-4":t.startsWith("gpt-4o")?"gpt-4o":t,KO=t=>{switch(t){case"text-embedding-ada-002":return 8191;default:return 2046}},j_=t=>{switch(xi(t)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128e3;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};function XO(t){return typeof t!="object"||!t?!1:!!("type"in t&&t.type==="function"&&"function"in t&&typeof t.function=="object"&&t.function&&"name"in t.function&&"parameters"in t.function)}const YO=async({prompt:t,modelName:e})=>{let n;try{n=(await ml(xi(e))).encode(t).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),n=Math.ceil(t.length/4)}return j_(e)-n},QO=()=>!1;var gl=class extends Pe{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(t){super(t),this.verbose=t.verbose??QO(),this.callbacks=t.callbacks,this.tags=t.tags??[],this.metadata=t.metadata??{}}},_l=class extends gl{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:t,callbackManager:e,...n}){const{cache:r,...s}=n;super({callbacks:t??e,...s}),typeof r=="object"?this.cache=r:r?this.cache=N_.global():this.cache=void 0,this.caller=new Xr(n??{})}_encoding;async getNumTokens(t){let e;typeof t=="string"?e=t:e=t.map(r=>typeof r=="string"?r:r.type==="text"&&"text"in r?r.text:"").join("");let n=Math.ceil(e.length/4);if(!this._encoding)try{this._encoding=await ml("modelName"in this?xi(this.modelName):"gpt2")}catch(r){console.warn("Failed to calculate number of tokens, falling back to approximate count",r)}if(this._encoding)try{n=this._encoding.encode(e).length}catch(r){console.warn("Failed to calculate number of tokens, falling back to approximate count",r)}return n}static _convertInputToPromptValue(t){return typeof t=="string"?new k_(t):Array.isArray(t)?new O_(t.map(jr)):t}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:t,...e}){const n={...this._identifyingParams(),...e,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([a,i])=>i!==void 0).map(([a,i])=>`${a}:${JSON.stringify(i)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(t){throw new Error("Use .toJSON() instead")}get profile(){return{}}},Ii=class extends Pe{static lc_name(){return"RunnablePassthrough"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;func;constructor(t){super(t),t&&(this.func=t.func)}async invoke(t,e){const n=we(e);return this.func&&await this.func(t,n),this._callWithConfig(r=>Promise.resolve(r),t,n)}async*transform(t,e){const n=we(e);let r,s=!0;for await(const a of this._transformStreamWithConfig(t,i=>i,n))if(yield a,s)if(r===void 0)r=a;else try{r=In(r,a)}catch{r=void 0,s=!1}this.func&&r!==void 0&&await this.func(r,n)}static assign(t){return new du(new wr({steps:t}))}};const e$=t=>t();function yl(t){const e=t.constructor;return new e({...t,content:t.contentBlocks,response_metadata:{...t.response_metadata,output_version:"v1"}})}var t$={};ge(t$,{BaseChatModel:()=>D_,SimpleChatModel:()=>n$});function wl(t){const e=[];for(const n of t){let r=n;if(Array.isArray(n.content))for(let s=0;s<n.content.length;s++){const a=n.content[s];(Li(a)||ji(a))&&r===n&&(r=new n.constructor({...r,content:[...n.content.slice(0,s),Pl(a),...n.content.slice(s+1)]}))}e.push(r)}return e}var D_=class tr extends _l{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(e){super(e),this.outputVersion=e$(()=>{const n=e.outputVersion??Jt("LC_OUTPUT_VERSION");return n&&["v0","v1"].includes(n)?n:"v0"})}_separateRunnableConfigFromCallOptionsCompat(e){const[n,r]=super._separateRunnableConfigFromCallOptions(e);return r.signal=n.signal,[n,r]}async invoke(e,n){const r=tr._convertInputToPromptValue(e);return(await this.generatePrompt([r],n,n?.callbacks)).generations[0][0].message}async*_streamResponseChunks(e,n,r){throw new Error("Not implemented.")}async*_streamIterator(e,n){if(this._streamResponseChunks===tr.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(e,n);else{const s=tr._convertInputToPromptValue(e).toChatMessages(),[a,i]=this._separateRunnableConfigFromCallOptionsCompat(n),o={...a.metadata,...this.getLsParams(i)},c=await lt.configure(a.callbacks,this.callbacks,a.tags,this.tags,o,this.metadata,{verbose:this.verbose}),u={options:i,invocation_params:this?.invocationParams(i),batch_size:1},l=i.outputVersion??this.outputVersion,d=await c?.handleChatModelStart(this.toJSON(),[wl(s)],a.runId,void 0,u,void 0,void 0,a.runName);let f,h;try{for await(const p of this._streamResponseChunks(s,i,d?.[0])){if(p.message.id==null){const m=d?.at(0)?.runId;m!=null&&p.message._updateId(`run-${m}`)}p.message.response_metadata={...p.generationInfo,...p.message.response_metadata},l==="v1"?yield yl(p.message):yield p.message,f?f=f.concat(p):f=p,Ji(p.message)&&p.message.usage_metadata!==void 0&&(h={tokenUsage:{promptTokens:p.message.usage_metadata.input_tokens,completionTokens:p.message.usage_metadata.output_tokens,totalTokens:p.message.usage_metadata.total_tokens}})}}catch(p){throw await Promise.all((d??[]).map(m=>m?.handleLLMError(p))),p}await Promise.all((d??[]).map(p=>p?.handleLLMEnd({generations:[[f]],llmOutput:h})))}}getLsParams(e){const n=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:e.stop,ls_provider:n}}async _generateUncached(e,n,r,s){const a=e.map(f=>f.map(jr));let i;if(s!==void 0&&s.length===a.length)i=s;else{const f={...r.metadata,...this.getLsParams(n)},h=await lt.configure(r.callbacks,this.callbacks,r.tags,this.tags,f,this.metadata,{verbose:this.verbose}),p={options:n,invocation_params:this?.invocationParams(n),batch_size:1};i=await h?.handleChatModelStart(this.toJSON(),a.map(wl),r.runId,void 0,p,void 0,void 0,r.runName)}const o=n.outputVersion??this.outputVersion,c=[],u=[];if(!!i?.[0].handlers.find(so)&&!this.disableStreaming&&a.length===1&&this._streamResponseChunks!==tr.prototype._streamResponseChunks)try{const f=await this._streamResponseChunks(a[0],n,i?.[0]);let h,p;for await(const m of f){if(m.message.id==null){const y=i?.at(0)?.runId;y!=null&&m.message._updateId(`run-${y}`)}h===void 0?h=m:h=In(h,m),Ji(m.message)&&m.message.usage_metadata!==void 0&&(p={tokenUsage:{promptTokens:m.message.usage_metadata.input_tokens,completionTokens:m.message.usage_metadata.output_tokens,totalTokens:m.message.usage_metadata.total_tokens}})}if(h===void 0)throw new Error("Received empty response from chat model call.");c.push([h]),await i?.[0].handleLLMEnd({generations:c,llmOutput:p})}catch(f){throw await i?.[0].handleLLMError(f),f}else{const f=await Promise.allSettled(a.map(async(h,p)=>{const m=await this._generate(h,{...n,promptIndex:p},i?.[p]);if(o==="v1")for(const y of m.generations)y.message=yl(y.message);return m}));await Promise.all(f.map(async(h,p)=>{if(h.status==="fulfilled"){const m=h.value;for(const y of m.generations){if(y.message.id==null){const v=i?.at(0)?.runId;v!=null&&y.message._updateId(`run-${v}`)}y.message.response_metadata={...y.generationInfo,...y.message.response_metadata}}return m.generations.length===1&&(m.generations[0].message.response_metadata={...m.llmOutput,...m.generations[0].message.response_metadata}),c[p]=m.generations,u[p]=m.llmOutput,i?.[p]?.handleLLMEnd({generations:[m.generations],llmOutput:m.llmOutput})}else return await i?.[p]?.handleLLMError(h.reason),Promise.reject(h.reason)}))}const d={generations:c,llmOutput:u.length?this._combineLLMOutput?.(...u):void 0};return Object.defineProperty(d,Kr,{value:i?{runIds:i?.map(f=>f.runId)}:void 0,configurable:!0}),d}async _generateCached({messages:e,cache:n,llmStringKey:r,parsedOptions:s,handledOptions:a}){const i=e.map(v=>v.map(jr)),o={...a.metadata,...this.getLsParams(s)},c=await lt.configure(a.callbacks,this.callbacks,a.tags,this.tags,o,this.metadata,{verbose:this.verbose}),u={options:s,invocation_params:this?.invocationParams(s),batch_size:1},l=await c?.handleChatModelStart(this.toJSON(),i.map(wl),a.runId,void 0,u,void 0,void 0,a.runName),d=[],h=(await Promise.allSettled(i.map(async(v,w)=>{const E=tr._convertInputToPromptValue(v).toString(),x=await n.lookup(E,r);return x==null&&d.push(w),x}))).map((v,w)=>({result:v,runManager:l?.[w]})).filter(({result:v})=>v.status==="fulfilled"&&v.value!=null||v.status==="rejected"),p=s.outputVersion??this.outputVersion,m=[];await Promise.all(h.map(async({result:v,runManager:w},E)=>{if(v.status==="fulfilled"){const x=v.value;return m[E]=x.map(A=>("message"in A&&wn(A.message)&&Wi(A.message)&&(A.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},p==="v1"&&(A.message=yl(A.message))),A.generationInfo={...A.generationInfo,tokenUsage:{}},A)),x.length&&await w?.handleLLMNewToken(x[0].text),w?.handleLLMEnd({generations:[x]},void 0,void 0,void 0,{cached:!0})}else return await w?.handleLLMError(v.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(v.reason)}));const y={generations:m,missingPromptIndices:d,startedRunManagers:l};return Object.defineProperty(y,Kr,{value:l?{runIds:l?.map(v=>v.runId)}:void 0,configurable:!0}),y}async generate(e,n,r){let s;Array.isArray(n)?s={stop:n}:s=n;const a=e.map(p=>p.map(jr)),[i,o]=this._separateRunnableConfigFromCallOptionsCompat(s);if(i.callbacks=i.callbacks??r,!this.cache)return this._generateUncached(a,o,i);const{cache:c}=this,u=this._getSerializedCacheKeyParametersForCall(o),{generations:l,missingPromptIndices:d,startedRunManagers:f}=await this._generateCached({messages:a,cache:c,llmStringKey:u,parsedOptions:o,handledOptions:i});let h={};if(d.length>0){const p=await this._generateUncached(d.map(m=>a[m]),o,i,f!==void 0?d.map(m=>f?.[m]):void 0);await Promise.all(p.generations.map(async(m,y)=>{const v=d[y];l[v]=m;const w=tr._convertInputToPromptValue(a[v]).toString();return c.update(w,u,m)})),h=p.llmOutput??{}}return{generations:l,llmOutput:h}}invocationParams(e){return{}}_modelType(){return"base_chat_model"}async generatePrompt(e,n,r){const s=e.map(a=>a.toChatMessages());return this.generate(s,n,r)}withStructuredOutput(e,n){if(typeof this.bindTools!="function")throw new Error(\'Chat model must implement ".bindTools()" to use withStructuredOutput.\');if(n?.strict)throw new Error(\'"strict" mode is not supported for this model by default.\');const r=e,s=n?.name,a=Zc(r)??"A function available to call.",i=n?.method,o=n?.includeRaw;if(i==="jsonMode")throw new Error(\'Base withStructuredOutput implementation only supports "functionCalling" as a method.\');let c=s??"extract",u;dr(r)?u=[{type:"function",function:{name:c,description:a,parameters:_r(r)}}]:("name"in r&&(c=r.name),u=[{type:"function",function:{name:c,description:a,parameters:r}}]);const l=this.bindTools(u),d=Pn.from(m=>{if(!zn.isInstance(m))throw new Error("Input is not an AIMessageChunk.");if(!m.tool_calls||m.tool_calls.length===0)throw new Error("No tool calls found in the response.");const y=m.tool_calls.find(v=>v.name===c);if(!y)throw new Error(`No tool call found with name ${c}.`);return y.args});if(!o)return l.pipe(d).withConfig({runName:"StructuredOutput"});const f=Ii.assign({parsed:(m,y)=>d.invoke(m.raw,y)}),h=Ii.assign({parsed:()=>null}),p=f.withFallbacks({fallbacks:[h]});return Na.from([{raw:l},p]).withConfig({runName:"StructuredOutputRunnable"})}},n$=class extends D_{async _generate(t,e,n){const r=await this._call(t,e,n),s=new on(r);if(typeof s.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:s.content,message:s}]}}},r$=class extends Pe{static lc_name(){return"RouterRunnable"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnables;constructor(t){super(t),this.runnables=t.runnables}async invoke(t,e){const{key:n,input:r}=t,s=this.runnables[n];if(s===void 0)throw new Error(`No runnable associated with key "${n}".`);return s.invoke(r,we(e))}async batch(t,e,n){const r=t.map(d=>d.key),s=t.map(d=>d.input);if(r.find(d=>this.runnables[d]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");const i=r.map(d=>this.runnables[d]),o=this._getOptionsList(e??{},t.length),c=o[0]?.maxConcurrency??n?.maxConcurrency,u=c&&c>0?c:t.length,l=[];for(let d=0;d<s.length;d+=u){const f=s.slice(d,d+u).map((p,m)=>i[m].invoke(p,o[m])),h=await Promise.all(f);l.push(h)}return l.flat()}async stream(t,e){const{key:n,input:r}=t,s=this.runnables[n];if(s===void 0)throw new Error(`No runnable associated with key "${n}".`);return s.stream(r,e)}},s$=class extends Pe{static lc_name(){return"RunnableBranch"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;default;branches;constructor(t){super(t),this.branches=t.branches,this.default=t.default}static from(t){if(t.length<1)throw new Error("RunnableBranch requires at least one branch");const n=t.slice(0,-1).map(([s,a])=>[Zt(s),Zt(a)]),r=Zt(t[t.length-1]);return new this({branches:n,default:r})}async _invoke(t,e,n){let r;for(let s=0;s<this.branches.length;s+=1){const[a,i]=this.branches[s];if(await a.invoke(t,Ae(e,{callbacks:n?.getChild(`condition:${s+1}`)}))){r=await i.invoke(t,Ae(e,{callbacks:n?.getChild(`branch:${s+1}`)}));break}}return r||(r=await this.default.invoke(t,Ae(e,{callbacks:n?.getChild("branch:default")}))),r}async invoke(t,e={}){return this._callWithConfig(this._invoke,t,e)}async*_streamIterator(t,e){const r=await(await wt(e))?.handleChainStart(this.toJSON(),He(t,"input"),e?.runId,void 0,void 0,void 0,e?.runName);let s,a=!0,i;try{for(let o=0;o<this.branches.length;o+=1){const[c,u]=this.branches[o];if(await c.invoke(t,Ae(e,{callbacks:r?.getChild(`condition:${o+1}`)}))){i=await u.stream(t,Ae(e,{callbacks:r?.getChild(`branch:${o+1}`)}));for await(const d of i)if(yield d,a)if(s===void 0)s=d;else try{s=In(s,d)}catch{s=void 0,a=!1}break}}if(i===void 0){i=await this.default.stream(t,Ae(e,{callbacks:r?.getChild("branch:default")}));for await(const o of i)if(yield o,a)if(s===void 0)s=o;else try{s=In(s,o)}catch{s=void 0,a=!1}}}catch(o){throw await r?.handleChainError(o),o}await r?.handleChainEnd(s??{})}},a$=class extends yr{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(t){let e=Pn.from((a,i)=>this._enterHistory(a,i??{})).withConfig({runName:"loadHistory"});const n=t.historyMessagesKey??t.inputMessagesKey;n&&(e=Ii.assign({[n]:e}).withConfig({runName:"insertHistory"}));const r=e.pipe(t.runnable.withListeners({onEnd:(a,i)=>this._exitHistory(a,i??{})})).withConfig({runName:"RunnableWithMessageHistory"}),s=t.config??{};super({...t,config:s,bound:r}),this.runnable=t.runnable,this.getMessageHistory=t.getMessageHistory,this.inputMessagesKey=t.inputMessagesKey,this.outputMessagesKey=t.outputMessagesKey,this.historyMessagesKey=t.historyMessagesKey}_getInputMessages(t){let e;if(typeof t=="object"&&!Array.isArray(t)&&!wn(t)){let n;this.inputMessagesKey?n=this.inputMessagesKey:Object.keys(t).length===1?n=Object.keys(t)[0]:n="input",Array.isArray(t[n])&&Array.isArray(t[n][0])?e=t[n][0]:e=t[n]}else e=t;if(typeof e=="string")return[new an(e)];if(Array.isArray(e))return e;if(wn(e))return[e];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.\nGot ${JSON.stringify(e,null,2)}`)}_getOutputMessages(t){let e;if(!Array.isArray(t)&&!wn(t)&&typeof t!="string"){let n;this.outputMessagesKey!==void 0?n=this.outputMessagesKey:Object.keys(t).length===1?n=Object.keys(t)[0]:n="output",t.generations!==void 0?e=t.generations[0][0].message:e=t[n]}else e=t;if(typeof e=="string")return[new on(e)];if(Array.isArray(e))return e;if(wn(e))return[e];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(e,null,2)}`)}async _enterHistory(t,e){const r=await(e?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?r.concat(this._getInputMessages(t)):r}async _exitHistory(t,e){const n=e.configurable?.messageHistory;let r;Array.isArray(t.inputs)&&Array.isArray(t.inputs[0])?r=t.inputs[0]:r=t.inputs;let s=this._getInputMessages(r);if(this.historyMessagesKey===void 0){const o=await n.getMessages();s=s.slice(o.length)}const a=t.outputs;if(!a)throw new Error(`Output values from \'Run\' undefined. Run: ${JSON.stringify(t,null,2)}`);const i=this._getOutputMessages(a);await n.addMessages([...s,...i])}async _mergeConfig(...t){const e=await super._mergeConfig(...t);if(!e.configurable||!e.configurable.sessionId){const r={[this.inputMessagesKey??"input"]:"foo"},s={configurable:{sessionId:"123"}};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\neg. chain.invoke(${JSON.stringify(r)}, ${JSON.stringify(s)})`)}const{sessionId:n}=e.configurable;return e.configurable.messageHistory=await this.getMessageHistory(n),e}},i$={};ge(i$,{RouterRunnable:()=>r$,Runnable:()=>Pe,RunnableAssign:()=>du,RunnableBinding:()=>yr,RunnableBranch:()=>s$,RunnableEach:()=>MI,RunnableLambda:()=>Pn,RunnableMap:()=>wr,RunnableParallel:()=>DI,RunnablePassthrough:()=>Ii,RunnablePick:()=>Yp,RunnableRetry:()=>lu,RunnableSequence:()=>Na,RunnableToolLike:()=>hu,RunnableWithFallbacks:()=>Xp,RunnableWithMessageHistory:()=>a$,_coerceToRunnable:()=>Zt,ensureConfig:()=>we,getCallbackManagerForConfig:()=>wt,mergeConfigs:()=>la,patchConfig:()=>Ae,pickRunnableConfigKeys:()=>un,raceWithSignal:()=>ln});var z_=class extends Pe{parseResultWithPrompt(t,e,n){return this.parseResult(t,n)}_baseMessageToString(t){return typeof t.content=="string"?t.content:this._baseMessageContentToString(t.content)}_baseMessageContentToString(t){return JSON.stringify(t)}async invoke(t,e){return typeof t=="string"?this._callWithConfig(async(n,r)=>this.parseResult([{text:n}],r?.callbacks),t,{...e,runType:"parser"}):this._callWithConfig(async(n,r)=>this.parseResult([{message:n,text:this._baseMessageToString(n)}],r?.callbacks),t,{...e,runType:"parser"})}},Ai=class extends z_{parseResult(t,e){return this.parse(t[0].text,e)}async parseWithPrompt(t,e,n){return this.parse(t,n)}_type(){throw new Error("_type not implemented")}},gn=class extends Error{llmOutput;observation;sendToLLM;constructor(t,e,n,r=!1){if(super(t),this.llmOutput=e,this.observation=n,this.sendToLLM=r,r&&(n===void 0||e===void 0))throw new Error("Arguments \'observation\' & \'llmOutput\' are required if \'sendToLlm\' is true");Hl(this,"OUTPUT_PARSING_FAILURE")}},As=class extends Ai{async*_transform(t){for await(const e of t)typeof e=="string"?yield this.parseResult([{text:e}]):yield this.parseResult([{message:e,text:this._baseMessageToString(e)}])}async*transform(t,e){yield*this._transformStreamWithConfig(t,this._transform.bind(this),{...e,runType:"parser"})}},ki=class extends As{diff=!1;constructor(t){super(t),this.diff=t?.diff??this.diff}async*_transform(t){let e,n;for await(const r of t){if(typeof r!="string"&&typeof r.content!="string")throw new Error("Cannot handle non-string output.");let s;if(Bi(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");s=new Oc({message:r,text:r.content})}else if(wn(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");s=new Oc({message:Vs(r),text:r.content})}else s=new lr({text:r});n===void 0?n=s:n=n.concat(s);const a=await this.parsePartialResult([n]);a!=null&&!Gn(a,e)&&(this.diff?yield this._diff(e,a):yield a,e=a)}}getFormatInstructions(){return""}},o$=class extends As{static lc_name(){return"BytesOutputParser"}lc_namespace=["langchain_core","output_parsers","bytes"];lc_serializable=!0;textEncoder=new TextEncoder;parse(t){return Promise.resolve(this.textEncoder.encode(t))}getFormatInstructions(){return""}},ks=class extends As{re;async*_transform(t){let e="";for await(const n of t)if(typeof n=="string"?e+=n:e+=n.content,this.re){const r=[...e.matchAll(this.re)];if(r.length>1){let s=0;for(const a of r.slice(0,-1))yield[a[1]],s+=(a.index??0)+a[0].length;e=e.slice(s)}}else{const r=await this.parse(e);if(r.length>1){for(const s of r.slice(0,-1))yield[s];e=r[r.length-1]}}for(const n of await this.parse(e))yield[n]}},c$=class extends ks{static lc_name(){return"CommaSeparatedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;async parse(t){try{return t.trim().split(",").map(e=>e.trim())}catch{throw new gn(`Could not parse output: ${t}`,t)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},u$=class extends ks{lc_namespace=["langchain_core","output_parsers","list"];length;separator;constructor({length:t,separator:e}){super(...arguments),this.length=t,this.separator=e||","}async parse(t){try{const e=t.trim().split(this.separator).map(n=>n.trim());if(this.length!==void 0&&e.length!==this.length)throw new gn(`Incorrect number of items. Expected ${this.length}, got ${e.length}.`);return e}catch(e){throw Object.getPrototypeOf(e)===gn.prototype?e:new gn(`Could not parse output: ${t}`)}}getFormatInstructions(){return`Your response should be a list of ${this.length===void 0?"":`${this.length} `}items separated by "${this.separator}" (eg: \\`foo${this.separator} bar${this.separator} baz\\`)`}},l$=class extends ks{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example: \n\n1. foo\n\n2. bar\n\n3. baz`}re=/\\d+\\.\\s([^\\n]+)/g;async parse(t){return[...t.matchAll(this.re)??[]].map(e=>e[1])}},d$=class extends ks{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example: \n\n1. foo\n\n2. bar\n\n3. baz`}re=/^\\s*[-*]\\s([^\\n]+)$/gm;async parse(t){return[...t.matchAll(this.re)??[]].map(e=>e[1])}},h$=class extends As{static lc_name(){return"StrOutputParser"}lc_namespace=["langchain_core","output_parsers","string"];lc_serializable=!0;parse(t){return Promise.resolve(t)}getFormatInstructions(){return""}_textContentToString(t){return t.text}_imageUrlContentToString(t){throw new Error(\'Cannot coerce a multimodal "image_url" message part into a string.\')}_messageContentToString(t){switch(t.type){case"text":case"text_delta":if("text"in t)return this._textContentToString(t);break;case"image_url":if("image_url"in t)return this._imageUrlContentToString(t);break;default:throw new Error(`Cannot coerce "${t.type}" message part into a string.`)}throw new Error(`Invalid content type: ${t.type}`)}_baseMessageContentToString(t){return t.reduce((e,n)=>e+this._messageContentToString(n),"")}},F_=class extends Ai{static lc_name(){return"StructuredOutputParser"}lc_namespace=["langchain","output_parsers","structured"];toJSON(){return this.toJSONNotImplemented()}constructor(t){super(t),this.schema=t}static fromZodSchema(t){return new this(t)}static fromNamesAndDescriptions(t){const e=Ca(Object.fromEntries(Object.entries(t).map(([n,r])=>[n,$a().describe(r)])));return new this(e)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.\n\n"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.\n\nFor example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}\nwould 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.\nThus, 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.\n\nYour 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!\n\nHere is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:\n\\`\\`\\`json\n${JSON.stringify(_r(this.schema))}\n\\`\\`\\`\n`}async parse(t){try{const e=t.trim(),r=(e.match(/^```(?:json)?\\s*([\\s\\S]*?)```/)?.[1]||e.match(/```json\\s*([\\s\\S]*?)```/)?.[1]||e).replace(/"([^"\\\\]*(\\\\.[^"\\\\]*)*)"/g,(s,a)=>`"${a.replace(/\\n/g,"\\\\n")}"`).replace(/\\n/g,"");return await Ea(this.schema,JSON.parse(r))}catch(e){throw new gn(`Failed to parse. Text: "${t}". Error: ${e}`,t)}}},U_=class extends F_{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(t){const e=t?.interpolationDepth??1;if(e<1)throw new Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:\n\\`\\`\\`json\n${this._schemaToInstruction(_r(this.schema)).replaceAll("{","{".repeat(e)).replaceAll("}","}".repeat(e))}\n\\`\\`\\``}_schemaToInstruction(t,e=2){const n=t;if("type"in n){let r=!1,s;if(Array.isArray(n.type)){const o=n.type.findIndex(c=>c==="null");o!==-1&&(r=!0,n.type.splice(o,1)),s=n.type.join(" | ")}else s=n.type;if(n.type==="object"&&n.properties){const o=n.description?` // ${n.description}`:"";return`{\n${Object.entries(n.properties).map(([u,l])=>{const d=n.required?.includes(u)?"":" (optional)";return`${" ".repeat(e)}"${u}": ${this._schemaToInstruction(l,e+2)}${d}`}).join(`\n`)}\n${" ".repeat(e-2)}}${o}`}if(n.type==="array"&&n.items){const o=n.description?` // ${n.description}`:"";return`array[\n${" ".repeat(e)}${this._schemaToInstruction(n.items,e+2)}\n${" ".repeat(e-2)}] ${o}`}const a=r?" (nullable)":"",i=n.description?` // ${n.description}`:"";return`${s}${i}${a}`}if("anyOf"in n)return n.anyOf.map(r=>this._schemaToInstruction(r,e)).join(`\n${" ".repeat(e-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(t){return new this(t)}static fromNamesAndDescriptions(t){const e=Ca(Object.fromEntries(Object.entries(t).map(([n,r])=>[n,$a().describe(r)])));return new this(e)}},f$=class extends Ai{structuredInputParser;constructor({inputSchema:t}){super(...arguments),this.structuredInputParser=new U_(t)}async parse(t){let e;try{e=await this.structuredInputParser.parse(t)}catch(n){throw new gn(`Failed to parse. Text: "${t}". Error: ${n}`,t)}return this.outputProcessor(e)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}},p$={};ge(p$,{applyPatch:()=>ur,compare:()=>Ic});var m$=class extends ki{static lc_name(){return"JsonOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_concatOutputChunks(t,e){return this.diff?super._concatOutputChunks(t,e):e}_diff(t,e){if(e)return t?Ic(t,e):[{op:"replace",path:"",value:e}]}async parsePartialResult(t){return Vi(t[0].text)}async parse(t){return Vi(t,JSON.parse)}getFormatInstructions(){return""}_baseMessageToString(t){return t.text}};const g$=function(){const t={};t.parser=function(_,g){return new n(_,g)},t.SAXParser=n,t.SAXStream=u,t.createStream=c,t.MAX_BUFFER_LENGTH=64*1024;const e=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];t.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function n(_,g){if(!(this instanceof n))return new n(_,g);var k=this;s(k),k.q=k.c="",k.bufferCheckPosition=t.MAX_BUFFER_LENGTH,k.opt=g||{},k.opt.lowercase=k.opt.lowercase||k.opt.lowercasetags,k.looseCase=k.opt.lowercase?"toLowerCase":"toUpperCase",k.tags=[],k.closed=k.closedRoot=k.sawRoot=!1,k.tag=k.error=null,k.strict=!!_,k.noscript=!!(_||k.opt.noscript),k.state=b.BEGIN,k.strictEntities=k.opt.strictEntities,k.ENTITIES=k.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),k.attribList=[],k.opt.xmlns&&(k.ns=Object.create(p)),k.trackPosition=k.opt.position!==!1,k.trackPosition&&(k.position=k.line=k.column=0),ue(k,"onready")}Object.create||(Object.create=function(_){function g(){}g.prototype=_;var k=new g;return k}),Object.keys||(Object.keys=function(_){var g=[];for(var k in _)_.hasOwnProperty(k)&&g.push(k);return g});function r(_){for(var g=Math.max(t.MAX_BUFFER_LENGTH,10),k=0,S=0,ye=e.length;S<ye;S++){var Ie=_[e[S]].length;if(Ie>g)switch(e[S]){case"textNode":Be(_);break;case"cdata":X(_,"oncdata",_.cdata),_.cdata="";break;case"script":X(_,"onscript",_.script),_.script="";break;default:L(_,"Max buffer length exceeded: "+e[S])}k=Math.max(k,Ie)}var Oe=t.MAX_BUFFER_LENGTH-k;_.bufferCheckPosition=Oe+_.position}function s(_){for(var g=0,k=e.length;g<k;g++)_[e[g]]=""}function a(_){Be(_),_.cdata!==""&&(X(_,"oncdata",_.cdata),_.cdata=""),_.script!==""&&(X(_,"onscript",_.script),_.script="")}n.prototype={end:function(){R(this)},write:Ee,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){a(this)}};var i=ReadableStream;i||(i=function(){});var o=t.EVENTS.filter(function(_){return _!=="error"&&_!=="end"});function c(_,g){return new u(_,g)}function u(_,g){if(!(this instanceof u))return new u(_,g);i.apply(this),this._parser=new n(_,g),this.writable=!0,this.readable=!0;var k=this;this._parser.onend=function(){k.emit("end")},this._parser.onerror=function(S){k.emit("error",S),k._parser.error=null},this._decoder=null,o.forEach(function(S){Object.defineProperty(k,"on"+S,{get:function(){return k._parser["on"+S]},set:function(ye){if(!ye)return k.removeAllListeners(S),k._parser["on"+S]=ye,ye;k.on(S,ye)},enumerable:!0,configurable:!1})})}u.prototype=Object.create(i.prototype,{constructor:{value:u}}),u.prototype.write=function(_){return this._parser.write(_.toString()),this.emit("data",_),!0},u.prototype.end=function(_){return _&&_.length&&this.write(_),this._parser.end(),!0},u.prototype.on=function(_,g){var k=this;return!k._parser["on"+_]&&o.indexOf(_)!==-1&&(k._parser["on"+_]=function(){var S=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);S.splice(0,0,_),k.emit.apply(k,S)}),i.prototype.on.call(k,_,g)};var l="[CDATA[",d="DOCTYPE",f="http://www.w3.org/XML/1998/namespace",h="http://www.w3.org/2000/xmlns/",p={xml:f,xmlns:h},m=/[:_A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]/,y=/[:_A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u00B7\\u0300-\\u036F\\u203F-\\u2040.\\d-]/,v=/[#:_A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]/,w=/[#:_A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u00B7\\u0300-\\u036F\\u203F-\\u2040.\\d-]/;function E(_){return _===" "||_===`\n`||_==="\\r"||_===" "}function x(_){return _===\'"\'||_==="\'"}function A(_){return _===">"||E(_)}function N(_,g){return _.test(g)}function j(_,g){return!N(_,g)}var b=0;t.STATE={BEGIN:b++,BEGIN_WHITESPACE:b++,TEXT:b++,TEXT_ENTITY:b++,OPEN_WAKA:b++,SGML_DECL:b++,SGML_DECL_QUOTED:b++,DOCTYPE:b++,DOCTYPE_QUOTED:b++,DOCTYPE_DTD:b++,DOCTYPE_DTD_QUOTED:b++,COMMENT_STARTING:b++,COMMENT:b++,COMMENT_ENDING:b++,COMMENT_ENDED:b++,CDATA:b++,CDATA_ENDING:b++,CDATA_ENDING_2:b++,PROC_INST:b++,PROC_INST_BODY:b++,PROC_INST_ENDING:b++,OPEN_TAG:b++,OPEN_TAG_SLASH:b++,ATTRIB:b++,ATTRIB_NAME:b++,ATTRIB_NAME_SAW_WHITE:b++,ATTRIB_VALUE:b++,ATTRIB_VALUE_QUOTED:b++,ATTRIB_VALUE_CLOSED:b++,ATTRIB_VALUE_UNQUOTED:b++,ATTRIB_VALUE_ENTITY_Q:b++,ATTRIB_VALUE_ENTITY_U:b++,CLOSE_TAG:b++,CLOSE_TAG_SAW_WHITE:b++,SCRIPT:b++,SCRIPT_ENDING:b++},t.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:\'"\',apos:"\'"},t.ENTITIES={amp:"&",gt:">",lt:"<",quot:\'"\',apos:"\'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(t.ENTITIES).forEach(function(_){var g=t.ENTITIES[_],k=typeof g=="number"?String.fromCharCode(g):g;t.ENTITIES[_]=k});for(var oe in t.STATE)t.STATE[t.STATE[oe]]=oe;b=t.STATE;function ue(_,g,k){_[g]&&_[g](k)}function X(_,g,k){_.textNode&&Be(_),ue(_,g,k)}function Be(_){_.textNode=kt(_.opt,_.textNode),_.textNode&&ue(_,"ontext",_.textNode),_.textNode=""}function kt(_,g){return _.trim&&(g=g.trim()),_.normalize&&(g=g.replace(/\\s+/g," ")),g}function L(_,g){return Be(_),_.trackPosition&&(g+=`\nLine: `+_.line+`\nColumn: `+_.column+`\nChar: `+_.c),g=new Error(g),_.error=g,ue(_,"onerror",g),_}function R(_){return _.sawRoot&&!_.closedRoot&&P(_,"Unclosed root tag"),_.state!==b.BEGIN&&_.state!==b.BEGIN_WHITESPACE&&_.state!==b.TEXT&&L(_,"Unexpected end"),Be(_),_.c="",_.closed=!0,ue(_,"onend"),n.call(_,_.strict,_.opt),_}function P(_,g){if(typeof _!="object"||!(_ instanceof n))throw new Error("bad call to strictFail");_.strict&&L(_,g)}function H(_){_.strict||(_.tagName=_.tagName[_.looseCase]());var g=_.tags[_.tags.length-1]||_,k=_.tag={name:_.tagName,attributes:{}};_.opt.xmlns&&(k.ns=g.ns),_.attribList.length=0,X(_,"onopentagstart",k)}function Y(_,g){var k=_.indexOf(":"),S=k<0?["",_]:_.split(":"),ye=S[0],Ie=S[1];return g&&_==="xmlns"&&(ye="xmlns",Ie=""),{prefix:ye,local:Ie}}function q(_){if(_.strict||(_.attribName=_.attribName[_.looseCase]()),_.attribList.indexOf(_.attribName)!==-1||_.tag.attributes.hasOwnProperty(_.attribName)){_.attribName=_.attribValue="";return}if(_.opt.xmlns){var g=Y(_.attribName,!0),k=g.prefix,S=g.local;if(k==="xmlns")if(S==="xml"&&_.attribValue!==f)P(_,"xml: prefix must be bound to "+f+`\nActual: `+_.attribValue);else if(S==="xmlns"&&_.attribValue!==h)P(_,"xmlns: prefix must be bound to "+h+`\nActual: `+_.attribValue);else{var ye=_.tag,Ie=_.tags[_.tags.length-1]||_;ye.ns===Ie.ns&&(ye.ns=Object.create(Ie.ns)),ye.ns[S]=_.attribValue}_.attribList.push([_.attribName,_.attribValue])}else _.tag.attributes[_.attribName]=_.attribValue,X(_,"onattribute",{name:_.attribName,value:_.attribValue});_.attribName=_.attribValue=""}function ne(_,g){if(_.opt.xmlns){var k=_.tag,S=Y(_.tagName);k.prefix=S.prefix,k.local=S.local,k.uri=k.ns[S.prefix]||"",k.prefix&&!k.uri&&(P(_,"Unbound namespace prefix: "+JSON.stringify(_.tagName)),k.uri=S.prefix);var ye=_.tags[_.tags.length-1]||_;k.ns&&ye.ns!==k.ns&&Object.keys(k.ns).forEach(function(er){X(_,"onopennamespace",{prefix:er,uri:k.ns[er]})});for(var Ie=0,Oe=_.attribList.length;Ie<Oe;Ie++){var Ze=_.attribList[Ie],nt=Ze[0],Gt=Ze[1],je=Y(nt,!0),Ct=je.prefix,$r=je.local,$i=Ct===""?"":k.ns[Ct]||"",z={name:nt,value:Gt,prefix:Ct,local:$r,uri:$i};Ct&&Ct!=="xmlns"&&!$i&&(P(_,"Unbound namespace prefix: "+JSON.stringify(Ct)),z.uri=Ct),_.tag.attributes[nt]=z,X(_,"onattribute",z)}_.attribList.length=0}_.tag.isSelfClosing=!!g,_.sawRoot=!0,_.tags.push(_.tag),X(_,"onopentag",_.tag),g||(!_.noscript&&_.tagName.toLowerCase()==="script"?_.state=b.SCRIPT:_.state=b.TEXT,_.tag=null,_.tagName=""),_.attribName=_.attribValue="",_.attribList.length=0}function me(_){if(!_.tagName){P(_,"Weird empty close tag."),_.textNode+="</>",_.state=b.TEXT;return}if(_.script){if(_.tagName!=="script"){_.script+="</"+_.tagName+">",_.tagName="",_.state=b.SCRIPT;return}X(_,"onscript",_.script),_.script=""}var g=_.tags.length,k=_.tagName;_.strict||(k=k[_.looseCase]());for(var S=k;g--;){var ye=_.tags[g];if(ye.name!==S)P(_,"Unexpected close tag");else break}if(g<0){P(_,"Unmatched closing tag: "+_.tagName),_.textNode+="</"+_.tagName+">",_.state=b.TEXT;return}_.tagName=k;for(var Ie=_.tags.length;Ie-- >g;){var Oe=_.tag=_.tags.pop();_.tagName=_.tag.name,X(_,"onclosetag",_.tagName);var Ze={};for(var nt in Oe.ns)Ze[nt]=Oe.ns[nt];var Gt=_.tags[_.tags.length-1]||_;_.opt.xmlns&&Oe.ns!==Gt.ns&&Object.keys(Oe.ns).forEach(function(je){var Ct=Oe.ns[je];X(_,"onclosenamespace",{prefix:je,uri:Ct})})}g===0&&(_.closedRoot=!0),_.tagName=_.attribValue=_.attribName="",_.attribList.length=0,_.state=b.TEXT}function fe(_){var g=_.entity,k=g.toLowerCase(),S,ye="";return _.ENTITIES[g]?_.ENTITIES[g]:_.ENTITIES[k]?_.ENTITIES[k]:(g=k,g.charAt(0)==="#"&&(g.charAt(1)==="x"?(g=g.slice(2),S=parseInt(g,16),ye=S.toString(16)):(g=g.slice(1),S=parseInt(g,10),ye=S.toString(10))),g=g.replace(/^0+/,""),isNaN(S)||ye.toLowerCase()!==g?(P(_,"Invalid character entity"),"&"+_.entity+";"):String.fromCodePoint(S))}function Se(_,g){g==="<"?(_.state=b.OPEN_WAKA,_.startTagPosition=_.position):E(g)||(P(_,"Non-whitespace before first tag."),_.textNode=g,_.state=b.TEXT)}function ze(_,g){var k="";return g<_.length&&(k=_.charAt(g)),k}function Ee(_){var g=this;if(this.error)throw this.error;if(g.closed)return L(g,"Cannot write after close. Assign an onready handler.");if(_===null)return R(g);typeof _=="object"&&(_=_.toString());for(var k=0,S="";S=ze(_,k++),g.c=S,!!S;)switch(g.trackPosition&&(g.position++,S===`\n`?(g.line++,g.column=0):g.column++),g.state){case b.BEGIN:if(g.state=b.BEGIN_WHITESPACE,S==="\\uFEFF")continue;Se(g,S);continue;case b.BEGIN_WHITESPACE:Se(g,S);continue;case b.TEXT:if(g.sawRoot&&!g.closedRoot){for(var ye=k-1;S&&S!=="<"&&S!=="&";)S=ze(_,k++),S&&g.trackPosition&&(g.position++,S===`\n`?(g.line++,g.column=0):g.column++);g.textNode+=_.substring(ye,k-1)}S==="<"&&!(g.sawRoot&&g.closedRoot&&!g.strict)?(g.state=b.OPEN_WAKA,g.startTagPosition=g.position):(!E(S)&&(!g.sawRoot||g.closedRoot)&&P(g,"Text data outside of root node."),S==="&"?g.state=b.TEXT_ENTITY:g.textNode+=S);continue;case b.SCRIPT:S==="<"?g.state=b.SCRIPT_ENDING:g.script+=S;continue;case b.SCRIPT_ENDING:S==="/"?g.state=b.CLOSE_TAG:(g.script+="<"+S,g.state=b.SCRIPT);continue;case b.OPEN_WAKA:if(S==="!")g.state=b.SGML_DECL,g.sgmlDecl="";else if(!E(S))if(N(m,S))g.state=b.OPEN_TAG,g.tagName=S;else if(S==="/")g.state=b.CLOSE_TAG,g.tagName="";else if(S==="?")g.state=b.PROC_INST,g.procInstName=g.procInstBody="";else{if(P(g,"Unencoded <"),g.startTagPosition+1<g.position){var Ie=g.position-g.startTagPosition;S=new Array(Ie).join(" ")+S}g.textNode+="<"+S,g.state=b.TEXT}continue;case b.SGML_DECL:(g.sgmlDecl+S).toUpperCase()===l?(X(g,"onopencdata"),g.state=b.CDATA,g.sgmlDecl="",g.cdata=""):g.sgmlDecl+S==="--"?(g.state=b.COMMENT,g.comment="",g.sgmlDecl=""):(g.sgmlDecl+S).toUpperCase()===d?(g.state=b.DOCTYPE,(g.doctype||g.sawRoot)&&P(g,"Inappropriately located doctype declaration"),g.doctype="",g.sgmlDecl=""):S===">"?(X(g,"onsgmldeclaration",g.sgmlDecl),g.sgmlDecl="",g.state=b.TEXT):(x(S)&&(g.state=b.SGML_DECL_QUOTED),g.sgmlDecl+=S);continue;case b.SGML_DECL_QUOTED:S===g.q&&(g.state=b.SGML_DECL,g.q=""),g.sgmlDecl+=S;continue;case b.DOCTYPE:S===">"?(g.state=b.TEXT,X(g,"ondoctype",g.doctype),g.doctype=!0):(g.doctype+=S,S==="["?g.state=b.DOCTYPE_DTD:x(S)&&(g.state=b.DOCTYPE_QUOTED,g.q=S));continue;case b.DOCTYPE_QUOTED:g.doctype+=S,S===g.q&&(g.q="",g.state=b.DOCTYPE);continue;case b.DOCTYPE_DTD:g.doctype+=S,S==="]"?g.state=b.DOCTYPE:x(S)&&(g.state=b.DOCTYPE_DTD_QUOTED,g.q=S);continue;case b.DOCTYPE_DTD_QUOTED:g.doctype+=S,S===g.q&&(g.state=b.DOCTYPE_DTD,g.q="");continue;case b.COMMENT:S==="-"?g.state=b.COMMENT_ENDING:g.comment+=S;continue;case b.COMMENT_ENDING:S==="-"?(g.state=b.COMMENT_ENDED,g.comment=kt(g.opt,g.comment),g.comment&&X(g,"oncomment",g.comment),g.comment=""):(g.comment+="-"+S,g.state=b.COMMENT);continue;case b.COMMENT_ENDED:S!==">"?(P(g,"Malformed comment"),g.comment+="--"+S,g.state=b.COMMENT):g.state=b.TEXT;continue;case b.CDATA:S==="]"?g.state=b.CDATA_ENDING:g.cdata+=S;continue;case b.CDATA_ENDING:S==="]"?g.state=b.CDATA_ENDING_2:(g.cdata+="]"+S,g.state=b.CDATA);continue;case b.CDATA_ENDING_2:S===">"?(g.cdata&&X(g,"oncdata",g.cdata),X(g,"onclosecdata"),g.cdata="",g.state=b.TEXT):S==="]"?g.cdata+="]":(g.cdata+="]]"+S,g.state=b.CDATA);continue;case b.PROC_INST:S==="?"?g.state=b.PROC_INST_ENDING:E(S)?g.state=b.PROC_INST_BODY:g.procInstName+=S;continue;case b.PROC_INST_BODY:if(!g.procInstBody&&E(S))continue;S==="?"?g.state=b.PROC_INST_ENDING:g.procInstBody+=S;continue;case b.PROC_INST_ENDING:S===">"?(X(g,"onprocessinginstruction",{name:g.procInstName,body:g.procInstBody}),g.procInstName=g.procInstBody="",g.state=b.TEXT):(g.procInstBody+="?"+S,g.state=b.PROC_INST_BODY);continue;case b.OPEN_TAG:N(y,S)?g.tagName+=S:(H(g),S===">"?ne(g):S==="/"?g.state=b.OPEN_TAG_SLASH:(E(S)||P(g,"Invalid character in tag name"),g.state=b.ATTRIB));continue;case b.OPEN_TAG_SLASH:S===">"?(ne(g,!0),me(g)):(P(g,"Forward-slash in opening tag not followed by >"),g.state=b.ATTRIB);continue;case b.ATTRIB:if(E(S))continue;S===">"?ne(g):S==="/"?g.state=b.OPEN_TAG_SLASH:N(m,S)?(g.attribName=S,g.attribValue="",g.state=b.ATTRIB_NAME):P(g,"Invalid attribute name");continue;case b.ATTRIB_NAME:S==="="?g.state=b.ATTRIB_VALUE:S===">"?(P(g,"Attribute without value"),g.attribValue=g.attribName,q(g),ne(g)):E(S)?g.state=b.ATTRIB_NAME_SAW_WHITE:N(y,S)?g.attribName+=S:P(g,"Invalid attribute name");continue;case b.ATTRIB_NAME_SAW_WHITE:if(S==="=")g.state=b.ATTRIB_VALUE;else{if(E(S))continue;P(g,"Attribute without value"),g.tag.attributes[g.attribName]="",g.attribValue="",X(g,"onattribute",{name:g.attribName,value:""}),g.attribName="",S===">"?ne(g):N(m,S)?(g.attribName=S,g.state=b.ATTRIB_NAME):(P(g,"Invalid attribute name"),g.state=b.ATTRIB)}continue;case b.ATTRIB_VALUE:if(E(S))continue;x(S)?(g.q=S,g.state=b.ATTRIB_VALUE_QUOTED):(P(g,"Unquoted attribute value"),g.state=b.ATTRIB_VALUE_UNQUOTED,g.attribValue=S);continue;case b.ATTRIB_VALUE_QUOTED:if(S!==g.q){S==="&"?g.state=b.ATTRIB_VALUE_ENTITY_Q:g.attribValue+=S;continue}q(g),g.q="",g.state=b.ATTRIB_VALUE_CLOSED;continue;case b.ATTRIB_VALUE_CLOSED:E(S)?g.state=b.ATTRIB:S===">"?ne(g):S==="/"?g.state=b.OPEN_TAG_SLASH:N(m,S)?(P(g,"No whitespace between attributes"),g.attribName=S,g.attribValue="",g.state=b.ATTRIB_NAME):P(g,"Invalid attribute name");continue;case b.ATTRIB_VALUE_UNQUOTED:if(!A(S)){S==="&"?g.state=b.ATTRIB_VALUE_ENTITY_U:g.attribValue+=S;continue}q(g),S===">"?ne(g):g.state=b.ATTRIB;continue;case b.CLOSE_TAG:if(g.tagName)S===">"?me(g):N(y,S)?g.tagName+=S:g.script?(g.script+="</"+g.tagName,g.tagName="",g.state=b.SCRIPT):(E(S)||P(g,"Invalid tagname in closing tag"),g.state=b.CLOSE_TAG_SAW_WHITE);else{if(E(S))continue;j(m,S)?g.script?(g.script+="</"+S,g.state=b.SCRIPT):P(g,"Invalid tagname in closing tag."):g.tagName=S}continue;case b.CLOSE_TAG_SAW_WHITE:if(E(S))continue;S===">"?me(g):P(g,"Invalid characters in closing tag");continue;case b.TEXT_ENTITY:case b.ATTRIB_VALUE_ENTITY_Q:case b.ATTRIB_VALUE_ENTITY_U:var Oe,Ze;switch(g.state){case b.TEXT_ENTITY:Oe=b.TEXT,Ze="textNode";break;case b.ATTRIB_VALUE_ENTITY_Q:Oe=b.ATTRIB_VALUE_QUOTED,Ze="attribValue";break;case b.ATTRIB_VALUE_ENTITY_U:Oe=b.ATTRIB_VALUE_UNQUOTED,Ze="attribValue";break}if(S===";")if(g.opt.unparsedEntities){var nt=fe(g);g.entity="",g.state=Oe,g.write(nt)}else g[Ze]+=fe(g),g.entity="",g.state=Oe;else N(g.entity.length?w:v,S)?g.entity+=S:(P(g,"Invalid character in entity name"),g[Ze]+="&"+g.entity+S,g.entity="",g.state=Oe);continue;default:throw new Error(g,"Unknown state: "+g.state)}return g.position>=g.bufferCheckPosition&&r(g),g}return String.fromCodePoint||(function(){var _=String.fromCharCode,g=Math.floor,k=function(){var S=16384,ye=[],Ie,Oe,Ze=-1,nt=arguments.length;if(!nt)return"";for(var Gt="";++Ze<nt;){var je=Number(arguments[Ze]);if(!isFinite(je)||je<0||je>1114111||g(je)!==je)throw RangeError("Invalid code point: "+je);je<=65535?ye.push(je):(je-=65536,Ie=(je>>10)+55296,Oe=je%1024+56320,ye.push(Ie,Oe)),(Ze+1===nt||ye.length>S)&&(Gt+=_.apply(null,ye),ye.length=0)}return Gt};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:k,configurable:!0,writable:!0}):String.fromCodePoint=k})(),t}(),bl=`The output should be formatted as a XML file.\n1. Output should conform to the tags below. \n2. If tags are not given, make them on your own.\n3. Remember to always open and close all the tags.\n\nAs an example, for the tags ["foo", "bar", "baz"]:\n1. String "<foo>\n <bar>\n <baz></baz>\n </bar>\n</foo>" is a well-formatted instance of the schema. \n2. String "<foo>\n <bar>\n </foo>" is a badly-formatted instance.\n3. String "<foo>\n <tag>\n </tag>\n</foo>" is a badly-formatted instance.\n\nHere are the output tags:\n\\`\\`\\`\n{tags}\n\\`\\`\\``;var _$=class extends ki{tags;constructor(t){super(t),this.tags=t?.tags}static lc_name(){return"XMLOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_diff(t,e){if(e)return t?Ic(t,e):[{op:"replace",path:"",value:e}]}async parsePartialResult(t){return vl(t[0].text)}async parse(t){return vl(t)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?bl.replace("{tags}",this.tags?.join(", ")??""):bl}};const y$=t=>t.split(`\n`).map(e=>e.replace(/^\\s+/,"")).join(`\n`).trim(),B_=t=>{if(Object.keys(t).length===0)return{};const e={};return t.children.length>0?(e[t.name]=t.children.map(B_),e):(e[t.name]=t.text??void 0,e)};function vl(t){const e=y$(t),n=g$.parser(!0);let r={};const s=[];n.onopentag=o=>{const c={name:o.name,attributes:o.attributes,children:[],text:"",isSelfClosing:o.isSelfClosing};s.length>0?s[s.length-1].children.push(c):r=c,o.isSelfClosing||s.push(c)},n.onclosetag=()=>{if(s.length>0){const o=s.pop();s.length===0&&o&&(r=o)}},n.ontext=o=>{if(s.length>0){const c=s[s.length-1];c.text+=o}},n.onattribute=o=>{if(s.length>0){const c=s[s.length-1];c.attributes[o.name]=o.value}};const a=/```(xml)?(.*)```/s.exec(e),i=a?a[2]:e;return n.write(i).close(),r&&r.name==="?xml"&&(r=r.children[0]),B_(r)}var w$={};ge(w$,{AsymmetricStructuredOutputParser:()=>f$,BaseCumulativeTransformOutputParser:()=>ki,BaseLLMOutputParser:()=>z_,BaseOutputParser:()=>Ai,BaseTransformOutputParser:()=>As,BytesOutputParser:()=>o$,CommaSeparatedListOutputParser:()=>c$,CustomListOutputParser:()=>u$,JsonMarkdownStructuredOutputParser:()=>U_,JsonOutputParser:()=>m$,ListOutputParser:()=>ks,MarkdownListOutputParser:()=>d$,NumberedListOutputParser:()=>l$,OutputParserException:()=>gn,StringOutputParser:()=>h$,StructuredOutputParser:()=>F_,XMLOutputParser:()=>_$,XML_FORMAT_INSTRUCTIONS:()=>bl,parseJsonMarkdown:()=>Vi,parsePartialJson:()=>zs,parseXMLMarkdown:()=>vl});function Z_(t,e){if(t.function===void 0)return;let n;if(e?.partial)try{n=zs(t.function.arguments??"{}")}catch{return}else try{n=JSON.parse(t.function.arguments)}catch(s){throw new gn([`Function "${t.function.name}" arguments:`,"",t.function.arguments,"","are not valid JSON.",`Error: ${s.message}`].join(`\n`))}const r={name:t.function.name,args:n,type:"tool_call"};return e?.returnId&&(r.id=t.id),r}function b$(t){if(t.id===void 0)throw new Error(\'All OpenAI tool calls must have an "id" field.\');return{id:t.id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.args)}}}function v$(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var q_=class extends ki{static lc_name(){return"JsonOutputToolsParser"}returnId=!1;lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;constructor(t){super(t),this.returnId=t?.returnId??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(t){return await this.parsePartialResult(t,!1)}async parsePartialResult(t,e=!0){const n=t[0].message;let r;if(Wi(n)&&n.tool_calls?.length?r=n.tool_calls.map(a=>{const{id:i,...o}=a;return this.returnId?{id:i,...o}:o}):n.additional_kwargs.tool_calls!==void 0&&(r=JSON.parse(JSON.stringify(n.additional_kwargs.tool_calls)).map(i=>Z_(i,{returnId:this.returnId,partial:e}))),!r)return[];const s=[];for(const a of r)if(a!==void 0){const i={type:a.name,args:a.args,id:a.id};s.push(i)}return s}},E$=class extends q_{static lc_name(){return"JsonOutputKeyToolsParser"}lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){if(this.zodSchema===void 0)return t;const e=await dp(this.zodSchema,t);if(e.success)return e.data;throw new gn(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(e.error?.issues)}`,JSON.stringify(t,null,2))}async parsePartialResult(t){const n=(await super.parsePartialResult(t)).filter(s=>s.type===this.keyName);let r=n;if(n.length)return this.returnId||(r=n.map(s=>s.args)),this.returnSingle?r[0]:r}async parseResult(t){const n=(await super.parsePartialResult(t,!1)).filter(a=>a.type===this.keyName);let r=n;return n.length?(this.returnId||(r=n.map(a=>a.args)),this.returnSingle?this._validateResult(r[0]):await Promise.all(r.map(a=>this._validateResult(a)))):void 0}},S$={};ge(S$,{JsonOutputKeyToolsParser:()=>E$,JsonOutputToolsParser:()=>q_,convertLangChainToolCallToOpenAI:()=>b$,makeInvalidToolCall:()=>v$,parseToolCall:()=>Z_});var T$={};ge(T$,{BaseLLM:()=>V_,LLM:()=>x$});var V_=class Rs extends _l{lc_namespace=["langchain","llms",this._llmType()];async invoke(e,n){const r=Rs._convertInputToPromptValue(e);return(await this.generatePrompt([r],n,n?.callbacks)).generations[0][0].text}async*_streamResponseChunks(e,n,r){throw new Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(e){const[n,r]=super._separateRunnableConfigFromCallOptions(e);return r.signal=n.signal,[n,r]}async*_streamIterator(e,n){if(this._streamResponseChunks===Rs.prototype._streamResponseChunks)yield this.invoke(e,n);else{const r=Rs._convertInputToPromptValue(e),[s,a]=this._separateRunnableConfigFromCallOptionsCompat(n),i=await lt.configure(s.callbacks,this.callbacks,s.tags,this.tags,s.metadata,this.metadata,{verbose:this.verbose}),o={options:a,invocation_params:this?.invocationParams(a),batch_size:1},c=await i?.handleLLMStart(this.toJSON(),[r.toString()],s.runId,void 0,o,void 0,void 0,s.runName);let u=new lr({text:""});try{for await(const l of this._streamResponseChunks(r.toString(),a,c?.[0]))u?u=u.concat(l):u=l,typeof l.text=="string"&&(yield l.text)}catch(l){throw await Promise.all((c??[]).map(d=>d?.handleLLMError(l))),l}await Promise.all((c??[]).map(l=>l?.handleLLMEnd({generations:[[u]]})))}}async generatePrompt(e,n,r){const s=e.map(a=>a.toString());return this.generate(s,n,r)}invocationParams(e){return{}}_flattenLLMResult(e){const n=[];for(let r=0;r<e.generations.length;r+=1){const s=e.generations[r];if(r===0)n.push({generations:[s],llmOutput:e.llmOutput});else{const a=e.llmOutput?{...e.llmOutput,tokenUsage:{}}:void 0;n.push({generations:[s],llmOutput:a})}}return n}async _generateUncached(e,n,r,s){let a;if(s!==void 0&&s.length===e.length)a=s;else{const u=await lt.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}),l={options:n,invocation_params:this?.invocationParams(n),batch_size:e.length};a=await u?.handleLLMStart(this.toJSON(),e,r.runId,void 0,l,void 0,void 0,r?.runName)}const i=!!a?.[0].handlers.find(so);let o;if(i&&e.length===1&&this._streamResponseChunks!==Rs.prototype._streamResponseChunks)try{const u=await this._streamResponseChunks(e[0],n,a?.[0]);let l;for await(const d of u)l===void 0?l=d:l=In(l,d);if(l===void 0)throw new Error("Received empty response from chat model call.");o={generations:[[l]],llmOutput:{}},await a?.[0].handleLLMEnd(o)}catch(u){throw await a?.[0].handleLLMError(u),u}else{try{o=await this._generate(e,n,a?.[0])}catch(l){throw await Promise.all((a??[]).map(d=>d?.handleLLMError(l))),l}const u=this._flattenLLMResult(o);await Promise.all((a??[]).map((l,d)=>l?.handleLLMEnd(u[d])))}const c=a?.map(u=>u.runId)||void 0;return Object.defineProperty(o,Kr,{value:c?{runIds:c}:void 0,configurable:!0}),o}async _generateCached({prompts:e,cache:n,llmStringKey:r,parsedOptions:s,handledOptions:a,runId:i}){const o=await lt.configure(a.callbacks,this.callbacks,a.tags,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),c={options:s,invocation_params:this?.invocationParams(s),batch_size:e.length},u=await o?.handleLLMStart(this.toJSON(),e,i,void 0,c,void 0,void 0,a?.runName),l=[],f=(await Promise.allSettled(e.map(async(m,y)=>{const v=await n.lookup(m,r);return v==null&&l.push(y),v}))).map((m,y)=>({result:m,runManager:u?.[y]})).filter(({result:m})=>m.status==="fulfilled"&&m.value!=null||m.status==="rejected"),h=[];await Promise.all(f.map(async({result:m,runManager:y},v)=>{if(m.status==="fulfilled"){const w=m.value;return h[v]=w.map(E=>(E.generationInfo={...E.generationInfo,tokenUsage:{}},E)),w.length&&await y?.handleLLMNewToken(w[0].text),y?.handleLLMEnd({generations:[w]},void 0,void 0,void 0,{cached:!0})}else return await y?.handleLLMError(m.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(m.reason)}));const p={generations:h,missingPromptIndices:l,startedRunManagers:u};return Object.defineProperty(p,Kr,{value:u?{runIds:u?.map(m=>m.runId)}:void 0,configurable:!0}),p}async generate(e,n,r){if(!Array.isArray(e))throw new Error("Argument \'prompts\' is expected to be a string[]");let s;Array.isArray(n)?s={stop:n}:s=n;const[a,i]=this._separateRunnableConfigFromCallOptionsCompat(s);if(a.callbacks=a.callbacks??r,!this.cache)return this._generateUncached(e,i,a);const{cache:o}=this,c=this._getSerializedCacheKeyParametersForCall(i),{generations:u,missingPromptIndices:l,startedRunManagers:d}=await this._generateCached({prompts:e,cache:o,llmStringKey:c,parsedOptions:i,handledOptions:a,runId:a.runId});let f={};if(l.length>0){const h=await this._generateUncached(l.map(p=>e[p]),i,a,d!==void 0?l.map(p=>d?.[p]):void 0);await Promise.all(h.generations.map(async(p,m)=>{const y=l[m];return u[y]=p,o.update(e[y],c,p)})),f=h.llmOutput??{}}return{generations:u,llmOutput:f}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},x$=class extends V_{async _generate(t,e,n){return{generations:await Promise.all(t.map((s,a)=>this._call(s,{...e,promptIndex:a},n).then(i=>[{text:i}])))}}},I$={};ge(I$,{chunkArray:()=>H_});const H_=(t,e)=>t.reduce((n,r,s)=>{const a=Math.floor(s/e),i=n[a]||[];return n[a]=i.concat([r]),n},[]);var A$={};ge(A$,{Embeddings:()=>G_});var G_=class{caller;constructor(t){this.caller=new Xr(t??{})}},k$=class extends G_{model="text-embedding-ada-002";modelName;batchSize=512;stripNewLines=!0;dimensions;timeout;organization;encodingFormat;client;clientConfig;apiKey;constructor(t){const e={maxConcurrency:2,...t};super(e);const n=e?.apiKey??e?.openAIApiKey??Jt("OPENAI_API_KEY");this.organization=e?.configuration?.organization??Jt("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelName=this.model,this.batchSize=e?.batchSize??this.batchSize,this.stripNewLines=e?.stripNewLines??this.stripNewLines,this.timeout=e?.timeout,this.dimensions=e?.dimensions,this.encodingFormat=e?.encodingFormat,this.clientConfig={apiKey:n,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration}}async embedDocuments(t){const e=H_(this.stripNewLines?t.map(a=>a.replace(/\\n/g," ")):t,this.batchSize),n=e.map(a=>{const i={model:this.model,input:a};return this.dimensions&&(i.dimensions=this.dimensions),this.encodingFormat&&(i.encoding_format=this.encodingFormat),this.embeddingWithRetry(i)}),r=await Promise.all(n),s=[];for(let a=0;a<r.length;a+=1){const i=e[a],{data:o}=r[a];for(let c=0;c<i.length;c+=1)s.push(o[c].embedding)}return s}async embedQuery(t){const e={model:this.model,input:this.stripNewLines?t.replace(/\\n/g," "):t};this.dimensions&&(e.dimensions=this.dimensions),this.encodingFormat&&(e.encoding_format=this.encodingFormat);const{data:n}=await this.embeddingWithRetry(e);return n[0].embedding}async embeddingWithRetry(t){if(!this.client){const n={baseURL:this.clientConfig.baseURL},r=gk(n),s={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};s.baseURL||delete s.baseURL,s.defaultHeaders=wk(s.defaultHeaders),this.client=new pe(s)}const e={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(t,e)}catch(n){throw ak(n)}})}},O$={};ge(O$,{BaseToolkit:()=>$$,DynamicStructuredTool:()=>K_,DynamicTool:()=>J_,StructuredTool:()=>El,Tool:()=>W_,ToolInputParsingException:()=>js,isLangChainTool:()=>ll,isRunnableToolLike:()=>cl,isStructuredTool:()=>ol,isStructuredToolParams:()=>ul,tool:()=>C$});var El=class extends gl{extras;returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return["langchain","tools"]}responseFormat="content";defaultConfig;constructor(t){super(t??{}),this.verboseParsingErrors=t?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=t?.responseFormat??this.responseFormat,this.defaultConfig=t?.defaultConfig??this.defaultConfig,this.metadata=t?.metadata??this.metadata,this.extras=t?.extras??this.extras}async invoke(t,e){let n,r=we(la(this.defaultConfig,e));return Cr(t)?(n=t.args,r={...r,toolCall:t}):n=t,this.call(n,r)}async call(t,e,n){const r=Cr(t)?t.args:t;let s;if(dr(this.schema))try{s=await Ea(this.schema,r)}catch(h){let p="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(p=`${p}\nDetails: ${h.message}`),mp(h)&&(p=`${p}\n\n${cE(h)}`),new js(p,JSON.stringify(t))}else{const h=Ce(r,this.schema);if(!h.valid){let p="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(p=`${p}\nDetails: ${h.errors.map(m=>`${m.keywordLocation}: ${m.error}`).join(`\n`)}`),new js(p,JSON.stringify(t))}s=r}const a=Vr(e),o=await lt.configure(a.callbacks,this.callbacks,a.tags||n,this.tags,a.metadata,this.metadata,{verbose:this.verbose})?.handleToolStart(this.toJSON(),typeof t=="string"?t:JSON.stringify(t),a.runId,void 0,void 0,void 0,a.runName);delete a.runId;let c;try{c=await this._call(s,o,a)}catch(h){throw await o?.handleToolError(h),h}let u,l;if(this.responseFormat==="content_and_artifact")if(Array.isArray(c)&&c.length===2)[u,l]=c;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(c)}`);else u=c;let d;Cr(t)&&(d=t.id),!d&&Oy(a)&&(d=a.toolCall.id);const f=R$({content:u,artifact:l,toolCallId:d,name:this.name,metadata:this.metadata});return await o?.handleToolEnd(f),f}},W_=class extends El{schema=Ca({input:$a().optional()}).transform(t=>t.input);constructor(t){super(t)}call(t,e){const n=typeof t=="string"||t==null?{input:t}:t;return super.call(n,e)}},J_=class extends W_{static lc_name(){return"DynamicTool"}name;description;func;constructor(t){super(t),this.name=t.name,this.description=t.description,this.func=t.func,this.returnDirect=t.returnDirect??this.returnDirect}async call(t,e){const n=Vr(e);return n.runName===void 0&&(n.runName=this.name),super.call(t,n)}async _call(t,e,n){return this.func(t,e,n)}},K_=class extends El{static lc_name(){return"DynamicStructuredTool"}description;func;schema;constructor(t){super(t),this.name=t.name,this.description=t.description,this.func=t.func,this.returnDirect=t.returnDirect??this.returnDirect,this.schema=t.schema}async call(t,e,n){const r=Vr(e);return r.runName===void 0&&(r.runName=this.name),super.call(t,r,n)}_call(t,e,n){return this.func(t,e,n)}},$$=class{getTools(){return this.tools}};function C$(t,e){const n=qc(e.schema),r=os(e.schema);if(!e.schema||n||r)return new J_({...e,description:e.description??e.schema?.description??`${e.name} tool`,func:async(i,o,c)=>new Promise((u,l)=>{const d=Ae(c,{callbacks:o?.getChild()});jt.runWithConfig(un(d),async()=>{try{u(t(i,d))}catch(f){l(f)}})})});const s=e.schema,a=e.description??e.schema.description??`${e.name} tool`;return new K_({...e,description:a,schema:s,func:async(i,o,c)=>new Promise((u,l)=>{let d;const f=()=>{c?.signal&&d&&c.signal.removeEventListener("abort",d)};c?.signal&&(d=()=>{f(),l(Wr(c.signal))},c.signal.addEventListener("abort",d));const h=Ae(c,{callbacks:o?.getChild()});jt.runWithConfig(un(h),async()=>{try{const p=await t(i,h);if(c?.signal?.aborted){f();return}f(),u(p)}catch(p){f(),l(p)}})})})}function R$(t){const{content:e,artifact:n,toolCallId:r,metadata:s}=t;return r&&!Zi(e)?typeof e=="string"||Array.isArray(e)&&e.every(a=>typeof a=="object")?new bn({status:"success",content:e,artifact:n,tool_call_id:r,name:t.name,metadata:s}):new bn({status:"success",content:N$(e),artifact:n,tool_call_id:r,name:t.name,metadata:s}):e}function N$(t){try{return JSON.stringify(t)??""}catch{return`${t}`}}const P$=it({type:At("screenshot")}),M$=it({type:At("click"),x:at(),y:at(),button:fl(["left","right","wheel","back","forward"]).default("left")}),L$=it({type:At("double_click"),x:at(),y:at(),button:fl(["left","right","wheel","back","forward"]).default("left")}),j$=it({type:At("drag"),path:xs(it({x:at(),y:at()}))}),D$=it({type:At("keypress"),keys:xs(It())}),z$=it({type:At("move"),x:at(),y:at()}),F$=it({type:At("scroll"),x:at(),y:at(),scroll_x:at(),scroll_y:at()}),U$=it({type:At("type"),text:It()}),B$=it({type:At("wait"),duration:at().optional()}),Z$=dl("type",[P$,M$,L$,j$,D$,z$,F$,U$,B$]);it({action:Z$});const q$=it({type:At("exec"),command:xs(It()),env:lO(It(),It()).optional(),working_directory:It().optional(),timeout_ms:at().optional(),user:It().optional()});dl("type",[q$]),it({commands:xs(It()).describe("Array of shell commands to execute"),timeout_ms:at().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:at().optional().describe("Optional maximum number of characters to return from each command")});const V$=it({type:At("create_file"),path:It(),diff:It()}),H$=it({type:At("update_file"),path:It(),diff:It()}),G$=it({type:At("delete_file"),path:It()});dl("type",[V$,H$,G$]);const W$={default:"text-embedding-ada-002"},J$=t=>async(e,n)=>{const r=new Headers(n?.headers);return r.delete("Authorization"),r.delete("api-key"),t&&t.length>0&&r.set("X-Esri-Authorization",`Bearer ${t}`),await fetch(e,{...n,headers:r})};let Or,Qn;const Oi=new Map,K$=12,X$=10,Y$=async t=>{if(!Or)return;Qn?Qn.memoryVectors=[]:Qn=new mu(Or);const e=[];for(const[n,{layerItem:r}]of t.entries()){const s=`Name: ${r.name}\nTitle: ${r.title}\nDescription: ${r.description}`,a=new jn({id:n,pageContent:s,metadata:{layerId:n}});e.push(a)}await Qn.addDocuments(e),console.log("Layer Vectorstore contents:",Qn.memoryVectors)},Q$=async t=>{if(!Or)return;Oi.clear();const e=[];for(const[n,{fieldRegistry:r}]of t.entries()){const s=[],a=[];for(const[c,u]of r.entries()){const l=`Name: ${u.name}\nAlias: ${u.alias}\nDescription: ${u.description}`;s.push(new jn({id:c,pageContent:l,metadata:{layerId:n}})),a.push(l)}const i=new mu(Or),o=(async()=>{const c=await Or.embedDocuments(a);await i.addVectors(c,s),Oi.set(n,i)})();e.push(o)}await Promise.all(e),console.log("Field Vectorstore contents:",Array.from(Oi.entries()).map(([n,r])=>({id:n,contents:r.memoryVectors})))};globalThis.addEventListener("message",t=>{(async()=>{const{type:e,layersAndFieldsRegistry:n,layerIdForFieldsSearch:r=[],requestId:s,auth:a,precomputedEmbedding:i}=t.data;switch(e){case"generateEmbeddings":{if(!a?.token||!a.apiUrl){globalThis.postMessage({type:"error",error:"Missing token or apiUrl"});break}const o=W$.default;Or=new k$({model:o,apiKey:"dummy-key",batchSize:2048,maxConcurrency:10,configuration:{baseURL:a.apiUrl,fetch:J$(a.token)}}),n&&(await Y$(n),await Q$(n)),globalThis.postMessage("completed");break}case"layerSearch":{if(Qn){const o=await Qn.similaritySearchVectorWithScore(i,X$);globalThis.postMessage({requestId:s,results:o})}break}case"fieldSearch":{if(r.length>0){const o=r.map(async l=>{const d=Oi.get(l);if(!d)return null;const f=await d.similaritySearchVectorWithScore(i,K$);return{layerId:l,results:f}}),u=(await Promise.all(o)).filter(Boolean);globalThis.postMessage({requestId:s,results:u});return}break}default:console.warn("Unknown message type:",e)}})()})})();\n',r=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",s],{type:"text/javascript;charset=utf-8"});function a(t){let e;try{if(e=r&&(self.URL||self.webkitURL).createObjectURL(r),!e)throw"";let n=new Worker(e,{name:t?.name});return n.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),n}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(s),{name:t?.name})}}export{a as default};