@arcgis/ai-components 5.0.0-next.150 → 5.1.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/cdn/26V7SXDR.js +4 -0
  2. package/dist/cdn/3EBDE5UU.js +2 -0
  3. package/dist/cdn/4Y73V2HU.js +2 -0
  4. package/dist/cdn/62K6RJZZ.js +41 -0
  5. package/dist/cdn/63ACCRM5.js +239 -0
  6. package/dist/cdn/6T2EIYO4.js +59 -0
  7. package/dist/cdn/AF7UTDDE.js +4 -0
  8. package/dist/cdn/AQZDEJJZ.js +2 -0
  9. package/dist/cdn/CFDTXKJ6.js +2 -0
  10. package/dist/cdn/CFT5BBC6.js +69 -0
  11. package/dist/cdn/CN6VFVA2.js +19 -0
  12. package/dist/cdn/GCFT45CD.js +2 -0
  13. package/dist/cdn/HN2HMAMX.js +28 -0
  14. package/dist/cdn/I22GHLAO.js +2 -0
  15. package/dist/cdn/IFWK7P7O.js +2 -0
  16. package/dist/cdn/JDL3HFFX.js +56 -0
  17. package/dist/cdn/JOZLOFW3.js +271 -0
  18. package/dist/cdn/KJZARHAM.js +2 -0
  19. package/dist/cdn/KKHKKCYH.js +17 -0
  20. package/dist/cdn/KQ6LEQHH.js +14 -0
  21. package/dist/cdn/LSGRWCAO.js +5 -0
  22. package/dist/cdn/LTBEINKG.js +25 -0
  23. package/dist/cdn/M672SFG6.js +2 -0
  24. package/dist/cdn/M7XUI5KY.js +77 -0
  25. package/dist/cdn/NKNUZCLA.js +17 -0
  26. package/dist/cdn/OLPFL2NN.js +2 -0
  27. package/dist/cdn/OUVX4QS2.js +2 -0
  28. package/dist/cdn/PWXNH5LQ.js +2 -0
  29. package/dist/cdn/Q674OE2M.js +2 -0
  30. package/dist/cdn/QTP47HEP.js +2 -0
  31. package/dist/cdn/SOWNHB7F.js +30 -0
  32. package/dist/cdn/UY4FI7AP.js +2 -0
  33. package/dist/cdn/VUHDKXFM.js +2 -0
  34. package/dist/cdn/W5CHGOOR.js +109 -0
  35. package/dist/cdn/WBSNYWJJ.js +2 -0
  36. package/dist/cdn/X7WF7TCS.js +2 -0
  37. package/dist/cdn/XVUE27HC.js +2 -0
  38. package/dist/cdn/ZYQ6U2YH.js +88 -0
  39. package/dist/cdn/index.js +2 -2
  40. package/dist/chunks/runtime.js +2 -2
  41. package/dist/chunks/useT9n.js +1 -1
  42. package/dist/chunks/utils.js +1 -1
  43. package/dist/chunks/utils2.js +1 -1
  44. package/dist/components/arcgis-assistant/customElement.js +1 -1
  45. package/dist/components/arcgis-assistant-agent/customElement.js +1 -1
  46. package/dist/components/arcgis-assistant-chat/customElement.js +1 -1
  47. package/dist/components/arcgis-assistant-chat-card/customElement.js +1 -1
  48. package/dist/components/arcgis-assistant-chat-card-content/customElement.js +1 -1
  49. package/dist/components/arcgis-assistant-chat-entry/customElement.js +1 -1
  50. package/dist/components/arcgis-assistant-data-exploration-agent/customElement.js +1 -1
  51. package/dist/components/arcgis-assistant-interrupt/customElement.js +1 -1
  52. package/dist/components/arcgis-assistant-layer-filter-agent/customElement.js +1 -1
  53. package/dist/components/arcgis-assistant-layer-query-agent/customElement.js +1 -1
  54. package/dist/components/arcgis-assistant-layer-styling-agent/customElement.js +1 -1
  55. package/dist/components/arcgis-assistant-navigation-agent/customElement.js +1 -1
  56. package/dist/components/arcgis-assistant-shell/customElement.js +1 -1
  57. package/dist/docs/api.json +1 -1
  58. package/dist/docs/docs.json +1 -1
  59. package/dist/docs/web-types.json +1 -1
  60. package/dist/index.js +1 -1
  61. package/dist/loader.js +1 -1
  62. package/package.json +6 -6
@@ -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 gy=Object.defineProperty,_y=(t,e)=>{for(var n in e)gy(t,n,{get:e[n],enumerable:!0})};function yy(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 wy=Object.defineProperty,ge=(t,e)=>{for(var n in e)wy(t,n,{get:e[n],enumerable:!0})},Dn=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 Pi,kl;function by(){return kl||(kl=1,Pi=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()}),Pi}var vy=by(),Ey=Ms(vy),Ls={exports:{}},Ol;function Sy(){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}Sy();function Ty(t,e){return e?.[t]||Ey(t)}function xy(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 Iy(t){return"lc"in t||Object.keys(t).length===1&&$l in t}function Ay(t){return{[$l]:t}}function ky(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}function Oy(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 Mi(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return Oy(t);if(ky(t))return t;e.add(t);const n=t;if(Iy(n))return e.delete(t),Ay(n);const r={};for(const[s,a]of Object.entries(n))r[s]=Mi(a,e);return e.delete(t),r}return Array.isArray(t)?t.map(n=>Mi(n,e)):t}var $y={};ge($y,{Serializable:()=>zn,get_lc_unique_name:()=>Li});function Cl(t){return Array.isArray(t)?[...t]:{...t}}function Cy(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 Li(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 zn=class ny{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Li(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 ny||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]=Mi(u,a);const i=Object.keys(n).length?Cy(s,n):s,o=xy(i,Ty,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 Ry(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"),Ny=t=>{globalThis[Rl]=t},Nr=()=>globalThis[Rl];function yn(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 ji(t){return yn(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function Di(t){return yn(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function Py(t){return yn(t)&&t.source_type==="text"&&"text"in t&&typeof t.text=="string"}function Nl(t){return yn(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}function Pl(t){if(yn(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 My(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 zi({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 Ly(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 K(t,e){return ie(t)&&t.type===e}function ie(t){return typeof t=="object"&&t!==null}function Nt(t){return Array.isArray(t)}function M(t){return typeof t=="string"}function Pt(t){return typeof t=="number"}function Fi(t){return t instanceof Uint8Array}function Ml(t){try{return JSON.parse(t)}catch{return}}const Pr=t=>t();function jy(t){if(t.type==="char_location"&&M(t.document_title)&&Pt(t.start_char_index)&&Pt(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)&&Pt(t.start_page_number)&&Pt(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)&&Pt(t.start_block_index)&&Pt(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)&&Pt(t.start_block_index)&&Pt(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(K(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(K(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 Dy(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(K(r,"text")&&M(r.text)){const{text:s,citations:a,...i}=r;if(Nt(a)&&a.length){const o=a.reduce((c,u)=>{const l=jy(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(K(r,"thinking")&&M(r.thinking)){const{thinking:s,signature:a,...i}=r;yield{...i,type:"reasoning",reasoning:s,signature:a};continue}else if(K(r,"redacted_thinking")){yield{type:"non_standard",value:r};continue}else if(K(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(K(r,"input_json_delta")){if(Fy(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(K(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(K(r,"web_search_tool_result")&&M(r.tool_use_id)&&Nt(r.content)){const{content:s,tool_use_id:a}=r,i=s.reduce((o,c)=>K(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(K(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(K(r,"mcp_tool_use")){yield{id:r.id,type:"server_tool_call",name:"mcp_tool_use",args:r.input};continue}else if(K(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(K(r,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:r.input};continue}else if(K(r,"search_result")){yield{id:r.id,type:"non_standard",value:r};continue}else if(K(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 zy={translateContent:jl,translateContentChunk:jl};function Fy(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}function Uy(t){return ji(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:Di(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 By(t){return t.map(Uy)}function Zy(t){return!!(K(t,"image_url")&&ie(t.image_url)||K(t,"input_audio")&&ie(t.input_audio)||K(t,"file")&&ie(t.file))}function qy(t){if(K(t,"image_url")&&ie(t.image_url)&&M(t.image_url.url)){const e=zi({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(K(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(K(t,"file")&&ie(t.file)&&M(t.file.data)){const e=zi({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 Vy(t){const e=[];typeof t.content=="string"?e.push({type:"text",text:t.content}):e.push(...Ui(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 Hy(t){const e=[];typeof t.content=="string"?e.push({type:"text",text:t.content}):e.push(...Ui(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 Ui(t){const e=[];for(const n of t)Zy(n)?e.push(qy(n)):e.push(n);return e}function Gy(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)&&Nt(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(K(r,"text")){const{text:s,annotations:a,...i}=r;Array.isArray(a)?yield{...i,type:"text",text:String(s),annotations:a.map(Gy)}: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)&&Nt(t.additional_kwargs.tool_outputs))for(const r of t.additional_kwargs.tool_outputs){if(K(r,"web_search_call")){yield{id:r.id,type:"server_tool_call",name:"web_search",args:{query:r.query}};continue}else if(K(r,"file_search_call")){yield{id:r.id,type:"server_tool_call",name:"file_search",args:{query:r.query}};continue}else if(K(r,"computer_call")){yield{type:"non_standard",value:r};continue}else if(K(r,"code_interpreter_call")){if(M(r.code)&&(yield{id:r.id,type:"server_tool_call",name:"code_interpreter",args:{code:r.code}}),Nt(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(K(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(K(r,"mcp_call")){yield{id:r.id,type:"server_tool_call",name:"mcp_call",args:r.input};continue}else if(K(r,"mcp_list_tools")){yield{id:r.id,type:"server_tool_call",name:"mcp_list_tools",args:r.input};continue}else if(K(r,"mcp_approval_request")){yield{type:"non_standard",value:r};continue}else if(K(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 Wy(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 Jy={translateContent:t=>typeof t.content=="string"?Vy(t):Dl(t),translateContentChunk:t=>typeof t.content=="string"?Hy(t):Wy(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 Ky(t,e="pretty"){return e==="pretty"?Xy(t):JSON.stringify(t)}function Xy(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 Bi=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=>yn(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=>yn(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 Yy(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 zn{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[Bi]=!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[By,Ui,Dy].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&&Bi in t&&t[Bi]===!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=Yy(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return Ky(this,t)}};function Qy(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 wn=class ry extends sn{static isInstance(e){if(!super.isInstance(e))return!1;let n=Object.getPrototypeOf(e);for(;n!==null;){if(n===ry.prototype)return!0;n=Object.getPrototypeOf(n)}return!1}};function Zl(t){return typeof t.role=="string"}function bn(t){return typeof t?._getType=="function"}function Zi(t){return wn.isInstance(t)}var ew={};ge(ew,{ToolMessage:()=>vn,ToolMessageChunk:()=>Ds,defaultToolCallParser:()=>Vi,isDirectToolOutput:()=>qi,isToolMessage:()=>ql,isToolMessageChunk:()=>Vl});function qi(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}var vn=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 wn{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 Vi(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 Hi(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 tw(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:tw(t)}catch{return null}}var Lr=class sy extends sn{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return sy}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 wn{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 nw(t){return t._getType()==="generic"}function rw(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 wn{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 sw(t){return t._getType()==="function"}function aw(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 wn{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 iw(t){return t.getType()==="human"}function ow(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"}},En=class Ri extends sn{static lc_name(){return"SystemMessage"}type="system";constructor(e){super(e)}concat(e){if(typeof e=="string")return new Ri({...this,content:rn(this.content,e)});if(Ri.isInstance(e))return new Ri({...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"}},rr=class extends wn{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 cw(t){return t._getType()==="system"}function uw(t){return t._getType()==="system"}function Gi(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 lw(t){if(ie(t.document)&&ie(t.document.source)){const e=ie(t.document)&&M(t.document.format)?t.document.format:"",n=Gi(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(Fi(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(Nt(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 dw(t){if(K(t,"image")&&ie(t.image)){const e=ie(t.image)&&M(t.image.format)?t.image.format:"",n=Gi(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(Fi(t.image.source.bytes))return{type:"image",mimeType:n,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}function hw(t){if(K(t,"video")&&ie(t.video)){const e=ie(t.video)&&M(t.video.format)?t.video.format:"",n=Gi(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(Fi(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(K(r,"cache_point")){yield{type:"non_standard",value:r};continue}else if(K(r,"citations_content")&&ie(r.citationsContent)){const s=Nt(r.citationsContent.content)?r.citationsContent.content.reduce((i,o)=>ie(o)&&M(o.text)?i+o.text:i,""):"",a=Nt(r.citationsContent.citations)?r.citationsContent.citations.reduce((i,o)=>{if(ie(o)){const c=Nt(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:Pt(l.documentIndex)?l.documentIndex.toString():void 0,startIndex:Pt(l.start)?l.start:void 0,endIndex:Pt(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(K(r,"document")&&ie(r.document)){yield lw(r);continue}else if(K(r,"guard_content")){yield{type:"non_standard",value:r};continue}else if(K(r,"image")&&ie(r.image)){yield dw(r);continue}else if(K(r,"reasoning_content")&&M(r.reasoningText)){yield{type:"reasoning",reasoning:r.reasoningText};continue}else if(K(r,"text")&&M(r.text)){yield{type:"text",text:r.text};continue}else if(K(r,"tool_result")){yield{type:"non_standard",value:r};continue}else{if(K(r,"tool_call"))continue;if(K(r,"video")&&ie(r.video)){yield hw(r);continue}}yield{type:"non_standard",value:r}}}return Array.from(e())}const fw={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 pw={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(K(r,"text")&&M(r.text)){yield{type:"text",text:r.text};continue}else if(K(r,"thinking")&&M(r.thinking)){yield{type:"reasoning",reasoning:r.thinking,...r.signature?{signature:r.signature}:{}};continue}else if(K(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(K(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(K(r,"functionResponse")){yield{type:"non_standard",value:r};continue}else if(K(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(K(r,"executableCode")){yield{type:"non_standard",value:r};continue}else if(K(r,"codeExecutionResult")){yield{type:"non_standard",value:r};continue}yield{type:"non_standard",value:r}}}return Array.from(e())}const mw={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(K(r,"reasoning")&&M(r.reasoning)){const s=Pr(()=>{const a=n.indexOf(r);if(Nt(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(K(r,"thinking")&&M(r.thinking)){yield{type:"reasoning",reasoning:r.thinking,...r.signature?{signature:r.signature}:{}};continue}else if(K(r,"text")&&M(r.text)){yield{type:"text",text:r.text};continue}else if(K(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(K(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 gw={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 _w={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 yw={translateContent:Yl,translateContentChunk:Yl};function Ql(t){const e=[];if(ie(t.additional_kwargs?.reasoning)){const r=t.additional_kwargs.reasoning;if(Nt(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 ww={translateContent:Ql,translateContentChunk:Ql};globalThis.lc_block_translators_registry??=new Map([["anthropic",zy],["bedrock-converse",fw],["deepseek",pw],["google-genai",mw],["google-vertexai",gw],["groq",_w],["ollama",yw],["openai",Jy],["xai",ww]]);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 bw(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 vw(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 Wi(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:bw(t?.input_token_details,e?.input_token_details),output_token_details:vw(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]=Vi(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 Ji(t){return t._getType()==="ai"}function Ki(t){return t._getType()==="ai"}var Fn=class extends wn{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=Wi(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 Ew=t=>t();function Sw(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 Tw(t){return typeof t=="object"&&t!=null&&t.lc===1&&Array.isArray(t.id)&&t.kwargs!=null&&typeof t.kwargs=="object"}function Xi(t){let e,n;if(Tw(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(Sw);return new on({...s,tool_calls:a})}else{if(e==="system")return new En(n);if(e==="developer")return new En({...n,additional_kwargs:{...n.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in n)return new vn({...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(bn(t))return t;if(Array.isArray(t)){const[e,n]=t;return Xi({type:e,content:n})}else if(Zl(t)){const{role:e,...n}=t;return Xi({...n,type:e})}else return Xi(t)}function Yi(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 xw(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 Qi(t){const e=xw(t);switch(e.type){case"human":return new an(e.data);case"ai":return new on(e.data);case"system":return new En(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 vn(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 Iw(t){return t.map(Qi)}function Aw(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 Fn({...n})}else{if(e==="system")return new rr({...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 kw={};ge(kw,{getEnv:()=>eo,getEnvironmentVariable:()=>st,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(),eo=()=>{let t;return sd()?t="browser":od()?t="node":ad()?t="webworker":id()?t="jsdom":Hs()?t="deno":t="other",t};let to;function cd(){return to===void 0&&(to={library:"langchain-js",runtime:eo()}),to}function st(t){try{return typeof process<"u"?process.env?.[t]:Hs()?Deno?.env.get(t):void 0}catch{return}}var Ow=/^(?:[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"&&Ow.test(t)}function $w(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=[],no=0;no<256;++no)Ye.push((no+256).toString(16).slice(1));function ro(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,Cw=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(Cw)}function Rw(t){t=unescape(encodeURIComponent(t));for(var e=[],n=0;n<t.length;++n)e.push(t.charCodeAt(n));return e}var Nw="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Pw="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Mw(t,e,n){function r(s,a,i,o){var c;if(typeof s=="string"&&(s=Rw(s)),typeof a=="string"&&(a=$w(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 ro(u)}try{r.name=t}catch{}return r.DNS=Nw,r.URL=Pw,r}var Lw=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ld={randomUUID:Lw};function Un(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,ro(r)}function jw(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 so(t,e){return t<<e|t>>>32-e}function Dw(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]=so(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=so(m,5)+jw(A,y,v,w)+E+e[A]+f[x]>>>0;E=w,w=v,v=so(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=Mw("v5",80,Dw),dd=null,hd=null,Mt=0;function Sn(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>Mt&&t.msecs===void 0&&(Mt=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>Mt&&o===null?++u>524287&&(u=0,++c>4095&&(c=0,Mt++)):Mt=i,hd=c,dd=u,s[r++]=Mt/1099511627776&255,s[r++]=Mt/4294967296&255,s[r++]=Mt/16777216&255,s[r++]=Mt/65536&255,s[r++]=Mt/256&255,s[r++]=Mt&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||ro(s)}var zw={};ge(zw,{BaseCallbackHandler:()=>Fr,callbackHandlerPrefersStreaming:()=>ao,isBaseCallbackHandler:()=>fd});var Fw=class{};function ao(t){return"lc_prefer_streaming"in t&&t.lc_prefer_streaming}var Fr=class extends Fw{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,Li(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=st("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 zn.prototype.toJSON.call(this)}toJSONNotImplemented(){return zn.prototype.toJSONNotImplemented.call(this)}static fromMethods(t){class e extends Fr{name=Sn();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"},Uw="gen_ai.operation.name",Bw="gen_ai.system",pd="gen_ai.request.model",Zw="gen_ai.response.model",md="gen_ai.usage.input_tokens",gd="gen_ai.usage.output_tokens",_d="gen_ai.usage.total_tokens",qw="gen_ai.request.max_tokens",Vw="gen_ai.request.temperature",Hw="gen_ai.request.top_p",Gw="gen_ai.request.frequency_penalty",Ww="gen_ai.request.presence_penalty",Jw="gen_ai.response.finish_reasons",Kw="gen_ai.prompt",Xw="gen_ai.completion",Yw="gen_ai.request.extra_query",Qw="gen_ai.request.extra_body",eb="gen_ai.serialized.name",tb="gen_ai.serialized.signature",nb="gen_ai.serialized.doc",rb="gen_ai.response.id",sb="gen_ai.response.service_tier",ab="gen_ai.response.system_fingerprint",ib="gen_ai.usage.input_token_details",ob="gen_ai.usage.output_token_details",cb="langsmith.trace.session_id",ub="langsmith.trace.session_name",lb="langsmith.span.kind",db="langsmith.trace.name",hb="langsmith.metadata",yd="langsmith.span.tags",fb="langsmith.request.streaming",pb="langsmith.request.headers",mb=(...t)=>fetch(...t),wd=Symbol.for("ls:fetch_implementation"),gb=()=>{const t=globalThis[wd];return t?typeof t=="function"&&"Headers"in t&&"Request"in t&&"Response"in t:!1},_b=t=>async(...e)=>{if(t||ct("DEBUG")==="true"){const[r,s]=e;console.log(`\u2192 ${s?.method||"GET"} ${r}`)}const n=await(globalThis[wd]??mb)(...e);return(t||ct("DEBUG")==="true")&&console.log(`\u2190 ${n.status} ${n.statusText} ${n.url}`),n},bd=()=>ct("PROJECT")??Xt("LANGCHAIN_SESSION")??"default",vd={};function Ed(t){vd[t]||(console.warn(t),vd[t]=!0)}const yb=/^[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(!yb.test(t)){const n=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(n)}return t}function wb(t){const e=typeof t=="string"?Date.parse(t):t;return Sn({msecs:e,seq:0})}function bb(t,e){throw new Error("dump() is not supported in browser environments.")}function vb(t){throw new Error("load() is not supported in browser environments.")}function Eb(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}class Sb{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;bb()}load(e){const n=vb();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())Eb(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 Tb=()=>typeof window<"u"&&typeof window.document<"u",xb=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Ib=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Td=()=>typeof Deno<"u",Ab=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Td(),xd=()=>Kt||(typeof Bun<"u"?Kt="bun":Tb()?Kt="browser":Ab()?Kt="node":xb()?Kt="webworker":Ib()?Kt="jsdom":Td()?Kt="deno":Kt="other",Kt);let io;function Id(){if(io===void 0){const t=xd(),e=Ob();io={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:Sd,...e}}return io}function Ad(){const t=kb(),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 kb(){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 ct(t){return Xt(`LANGSMITH_${t}`)||Xt(`LANGCHAIN_${t}`)}let oo;function Ob(){if(oo!==void 0)return oo;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 oo=e,e}function kd(){return Xt("OTEL_ENABLED")==="true"||ct("OTEL_ENABLED")==="true"}class $b{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 Cb{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new $b})}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 Rb{active(){return{}}with(e,n){return n()}}const co=Symbol.for("ls:otel_trace"),uo=Symbol.for("ls:otel_context"),Od=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),Nb=new Cb,Pb=new Rb;class Mb{getTraceInstance(){return globalThis[co]??Nb}getContextInstance(){return globalThis[uo]??Pb}initializeGlobalInstances(e){globalThis[co]===void 0&&(globalThis[co]=e.trace),globalThis[uo]===void 0&&(globalThis[uo]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[Od]=e}getDefaultOTLPTracerComponents(){return globalThis[Od]??void 0}}const lo=new Mb;function $d(){return lo.getTraceInstance()}function Lb(){return lo.getContextInstance()}function jb(){return lo.getDefaultOTLPTracerComponents()}const Db={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function zb(t){return Db[t]||t}class Fb{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(lb,n.run_type);const o=zb(n.run_type||"chain");e.setAttribute(Uw,o)}"name"in n&&n.name&&e.setAttribute(db,n.name),"session_id"in n&&n.session_id&&e.setAttribute(cb,n.session_id),"session_name"in n&&n.session_name&&e.setAttribute(ub,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(`${hb}.${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(eb,String(o.name)),o.signature&&e.setAttribute(tb,String(o.signature)),o.doc&&e.setAttribute(nb,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(Bw,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(qw,r.max_tokens),r.temperature!==void 0&&e.setAttribute(Vw,r.temperature),r.top_p!==void 0&&e.setAttribute(Hw,r.top_p),r.frequency_penalty!==void 0&&e.setAttribute(Gw,r.frequency_penalty),r.presence_penalty!==void 0&&e.setAttribute(Ww,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(fb,r.stream),r.extra_headers&&e.setAttribute(pb,JSON.stringify(r.extra_headers)),r.extra_query&&e.setAttribute(Yw,JSON.stringify(r.extra_query)),r.extra_body&&e.setAttribute(Qw,JSON.stringify(r.extra_body))),e.setAttribute(Kw,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(Zw,String(r.model)),r.id&&e.setAttribute(rb,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(Jw,a.join(", "))}if(r.service_tier&&e.setAttribute(sb,r.service_tier),r.system_fingerprint&&e.setAttribute(ab,r.system_fingerprint),r.usage_metadata&&typeof r.usage_metadata=="object"){const a=r.usage_metadata;a.input_token_details&&e.setAttribute(ib,JSON.stringify(a.input_token_details)),a.output_token_details&&e.setAttribute(ob,JSON.stringify(a.output_token_details))}}e.setAttribute(Xw,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 Ub=Object.prototype.toString,Bb=t=>Ub.call(t)==="[object Error]",Zb=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 qb(t){if(!(t&&Bb(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:Zb.has(n)}function Vb(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 Hb=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 Gb(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 Wb({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 Hb)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&&!qb(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=Gb(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 Jb(t,e={}){if(e={...e},Vb(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 Wb({error:a,attemptNumber:n,retriesConsumed:r,startTime:s,options:e})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Js={},ho={exports:{}},Rd;function Kb(){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})(ho)),ho.exports}var Ur={exports:{}},fo,Nd;function Xb(){return Nd||(Nd=1,fo=(t,e)=>(e=e||(()=>{}),t.then(n=>new Promise(r=>{r(e())}).then(()=>n),n=>new Promise(r=>{r(e())}).then(()=>{throw n})))),fo}var Pd;function Yb(){if(Pd)return Ur.exports;Pd=1;const t=Xb();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 Qb(){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 ev(){if(Ld)return Ks;Ld=1,Object.defineProperty(Ks,"__esModule",{value:!0});const t=Qb();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 tv(){if(jd)return Js;jd=1,Object.defineProperty(Js,"__esModule",{value:!0});const t=Kb(),e=Yb(),n=ev(),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 nv=tv(),cn=Ms(nv);const rv=[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(()=>Jb(()=>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")&&!rv.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:{}},po,Ud;function Qs(){if(Ud)return po;Ud=1;const t="2.0.0",e=256,n=Number.MAX_SAFE_INTEGER||9007199254740991,r=16,s=e-6;return po={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},po}var mo,Bd;function ea(){return Bd||(Bd=1,mo=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\\bsemver\\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{}),mo}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 go,qd;function _o(){if(qd)return go;qd=1;const t=Object.freeze({loose:!0}),e=Object.freeze({});return go=r=>r?typeof r!="object"?t:r:e,go}var yo,Vd;function Hd(){if(Vd)return yo;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 yo={compareIdentifiers:e,rcompareIdentifiers:(r,s)=>e(s,r)},yo}var wo,Gd;function ut(){if(Gd)return wo;Gd=1;const t=ea(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:n}=Qs(),{safeRe:r,t:s}=Br(),a=_o(),{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 wo=o,wo}var bo,Wd;function sr(){if(Wd)return bo;Wd=1;const t=ut();return bo=(n,r,s=!1)=>{if(n instanceof t)return n;try{return new t(n,r)}catch(a){if(!s)return null;throw a}},bo}var vo,Jd;function sv(){if(Jd)return vo;Jd=1;const t=sr();return vo=(n,r)=>{const s=t(n,r);return s?s.version:null},vo}var Eo,Kd;function av(){if(Kd)return Eo;Kd=1;const t=sr();return Eo=(n,r)=>{const s=t(n.trim().replace(/^[=v]+/,""),r);return s?s.version:null},Eo}var So,Xd;function iv(){if(Xd)return So;Xd=1;const t=ut();return So=(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}},So}var To,Yd;function ov(){if(Yd)return To;Yd=1;const t=sr();return To=(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"},To}var xo,Qd;function cv(){if(Qd)return xo;Qd=1;const t=ut();return xo=(n,r)=>new t(n,r).major,xo}var Io,eh;function uv(){if(eh)return Io;eh=1;const t=ut();return Io=(n,r)=>new t(n,r).minor,Io}var Ao,th;function lv(){if(th)return Ao;th=1;const t=ut();return Ao=(n,r)=>new t(n,r).patch,Ao}var ko,nh;function dv(){if(nh)return ko;nh=1;const t=sr();return ko=(n,r)=>{const s=t(n,r);return s&&s.prerelease.length?s.prerelease:null},ko}var Oo,rh;function Lt(){if(rh)return Oo;rh=1;const t=ut();return Oo=(n,r,s)=>new t(n,s).compare(new t(r,s)),Oo}var $o,sh;function hv(){if(sh)return $o;sh=1;const t=Lt();return $o=(n,r,s)=>t(r,n,s),$o}var Co,ah;function fv(){if(ah)return Co;ah=1;const t=Lt();return Co=(n,r)=>t(n,r,!0),Co}var Ro,ih;function No(){if(ih)return Ro;ih=1;const t=ut();return Ro=(n,r,s)=>{const a=new t(n,s),i=new t(r,s);return a.compare(i)||a.compareBuild(i)},Ro}var Po,oh;function pv(){if(oh)return Po;oh=1;const t=No();return Po=(n,r)=>n.sort((s,a)=>t(s,a,r)),Po}var Mo,ch;function mv(){if(ch)return Mo;ch=1;const t=No();return Mo=(n,r)=>n.sort((s,a)=>t(a,s,r)),Mo}var Lo,uh;function ta(){if(uh)return Lo;uh=1;const t=Lt();return Lo=(n,r,s)=>t(n,r,s)>0,Lo}var jo,lh;function Do(){if(lh)return jo;lh=1;const t=Lt();return jo=(n,r,s)=>t(n,r,s)<0,jo}var zo,dh;function hh(){if(dh)return zo;dh=1;const t=Lt();return zo=(n,r,s)=>t(n,r,s)===0,zo}var Fo,fh;function ph(){if(fh)return Fo;fh=1;const t=Lt();return Fo=(n,r,s)=>t(n,r,s)!==0,Fo}var Uo,mh;function Bo(){if(mh)return Uo;mh=1;const t=Lt();return Uo=(n,r,s)=>t(n,r,s)>=0,Uo}var Zo,gh;function qo(){if(gh)return Zo;gh=1;const t=Lt();return Zo=(n,r,s)=>t(n,r,s)<=0,Zo}var Vo,_h;function yh(){if(_h)return Vo;_h=1;const t=hh(),e=ph(),n=ta(),r=Bo(),s=Do(),a=qo();return Vo=(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}`)}},Vo}var Ho,wh;function gv(){if(wh)return Ho;wh=1;const t=ut(),e=sr(),{safeRe:n,t:r}=Br();return Ho=(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)},Ho}var Go,bh;function _v(){if(bh)return Go;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 Go=t,Go}var Wo,vh;function jt(){if(vh)return Wo;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(Q=>!m(Q[0])),this.set.length===0)this.set=[H];else if(this.set.length>1){for(const Q of this.set)if(Q.length===1&&y(Q[0])){this.set=[Q];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,Q=r.get(H);if(Q)return Q;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=>Y(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(Q=>v(Q,P)&&H.every(q=>Q.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(Ot(this.set[P],R,this.options))return!0;return!1}}Wo=e;const n=_v(),r=new n,s=_o(),a=na(),i=ea(),o=ut(),{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 Q=H.pop();for(;P&&H.length;)P=H.every(q=>Q.intersects(q,R)),Q=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,Q,q,ne,me)=>{i("tilde",L,H,Q,q,ne,me);let fe;return E(Q)?fe="":E(q)?fe=`>=${Q}.0.0 <${+Q+1}.0.0-0`:E(ne)?fe=`>=${Q}.${q}.0 <${Q}.${+q+1}.0-0`:me?(i("replaceTilde pr",me),fe=`>=${Q}.${q}.${ne}-${me} <${Q}.${+q+1}.0-0`):fe=`>=${Q}.${q}.${ne} <${Q}.${+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,(Q,q,ne,me,fe)=>{i("caret",L,Q,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,Q,q,ne,me,fe)=>{i("xRange",L,H,Q,q,ne,me,fe);const Se=E(q),ze=Se||E(ne),Ee=ze||E(me),_=Ee;return Q==="="&&_&&(Q=""),fe=R.includePrerelease?"-0":"",Se?Q===">"||Q==="<"?H="<0.0.0-0":H="*":Q&&_?(ze&&(ne=0),me=0,Q===">"?(Q=">=",ze?(q=+q+1,ne=0,me=0):(ne=+ne+1,me=0)):Q==="<="&&(Q="<",ze?q=+q+1:ne=+ne+1),Q==="<"&&(fe="-0"),H=`${Q+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],"")),Y=(L,R)=>(i("replaceGTE0",L,R),L.trim().replace(c[R.includePrerelease?u.GTE0PRE:u.GTE0],"")),Be=L=>(R,P,H,Q,q,ne,me,fe,Se,ze,Ee,_)=>(E(H)?P="":E(Q)?P=`>=${H}.0.0${L?"-0":""}`:E(q)?P=`>=${H}.${Q}.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()),Ot=(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 Q=L[H].semver;if(Q.major===R.major&&Q.minor===R.minor&&Q.patch===R.patch)return!0}return!1}return!0};return Wo}var Jo,Eh;function na(){if(Eh)return Jo;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(">")))}}Jo=e;const n=_o(),{safeRe:r,t:s}=Br(),a=yh(),i=ea(),o=ut(),c=jt();return Jo}var Ko,Sh;function ra(){if(Sh)return Ko;Sh=1;const t=jt();return Ko=(n,r,s)=>{try{r=new t(r,s)}catch{return!1}return r.test(n)},Ko}var Xo,Th;function yv(){if(Th)return Xo;Th=1;const t=jt();return Xo=(n,r)=>new t(n,r).set.map(s=>s.map(a=>a.value).join(" ").trim().split(" ")),Xo}var Yo,xh;function wv(){if(xh)return Yo;xh=1;const t=ut(),e=jt();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,Ih;function bv(){if(Ih)return Qo;Ih=1;const t=ut(),e=jt();return Qo=(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},Qo}var ec,Ah;function vv(){if(Ah)return ec;Ah=1;const t=ut(),e=jt(),n=ta();return ec=(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},ec}var tc,kh;function Ev(){if(kh)return tc;kh=1;const t=jt();return tc=(n,r)=>{try{return new t(n,r).range||"*"}catch{return null}},tc}var nc,Oh;function rc(){if(Oh)return nc;Oh=1;const t=ut(),e=na(),{ANY:n}=e,r=jt(),s=ra(),a=ta(),i=Do(),o=qo(),c=Bo();return nc=(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},nc}var sc,$h;function Sv(){if($h)return sc;$h=1;const t=rc();return sc=(n,r,s)=>t(n,r,">",s),sc}var ac,Ch;function Tv(){if(Ch)return ac;Ch=1;const t=rc();return ac=(n,r,s)=>t(n,r,"<",s),ac}var ic,Rh;function xv(){if(Rh)return ic;Rh=1;const t=jt();return ic=(n,r,s)=>(n=new t(n,s),r=new t(r,s),n.intersects(r,s)),ic}var oc,Nh;function Iv(){if(Nh)return oc;Nh=1;const t=ra(),e=Lt();return oc=(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},oc}var cc,Ph;function Av(){if(Ph)return cc;Ph=1;const t=jt(),e=na(),{ANY:n}=e,r=ra(),s=Lt(),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 cc=a,cc}var uc,Mh;function kv(){if(Mh)return uc;Mh=1;const t=Br(),e=Qs(),n=ut(),r=Hd(),s=sr(),a=sv(),i=av(),o=iv(),c=ov(),u=cv(),l=uv(),d=lv(),f=dv(),h=Lt(),p=hv(),m=fv(),y=No(),v=pv(),w=mv(),E=ta(),x=Do(),A=hh(),N=ph(),j=Bo(),b=qo(),oe=yh(),ue=gv(),Y=na(),Be=jt(),Ot=ra(),L=yv(),R=wv(),P=bv(),H=vv(),Q=Ev(),q=rc(),ne=Sv(),me=Tv(),fe=xv(),Se=Iv(),ze=Av();return uc={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:Y,Range:Be,satisfies:Ot,toComparators:L,maxSatisfying:R,minSatisfying:P,minVersion:H,validRange:Q,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},uc}kv();function Tn(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 Ov 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 $v 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 J(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 $v(s);if(t.status===409)throw new Ov(s);const a=new Error(s);throw a.status=t.status,a}const jh="ERR_CONFLICTING_ENDPOINTS";class Cv 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 Rv(t){return typeof t=="object"&&t!==null&&t.code===jh}var Dh="[...]",Nv={result:"[Circular]"},sa=[],ar=[];const Pv=new TextEncoder;function Mv(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function aa(t){return Pv.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 Lv(t){return function(e,n){return zh(n)}}function wt(t,e,n,r,s){try{const a=JSON.stringify(t,Lv(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]");ct("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`\nContext: ${e}`:""}`),typeof s>"u"&&(s=Mv()),dc(t,"",0,[],void 0,0,s);let i;try{ar.length===0?i=JSON.stringify(t,n,r):i=JSON.stringify(t,jv(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 lc(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])):ar.push([e,n,t]):(r[n]=t,sa.push([r,n,e]))}function dc(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){lc(Nv,t,e,s);return}if(typeof i.depthLimit<"u"&&a>i.depthLimit){lc(Dh,t,e,s);return}if(typeof i.edgesLimit<"u"&&n+1>i.edgesLimit){lc(Dh,t,e,s);return}if(r.push(t),Array.isArray(t))for(o=0;o<t.length;o++)dc(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];dc(t[u],u,o,r,t,a,i)}}r.pop()}}function jv(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(ar.length>0)for(var r=0;r<ar.length;r++){var s=ar[r];if(s[1]===e&&s[0]===n){n=s[2],ar.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 Dv=t=>{const e=t?.toString()??ct("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},zv=t=>{const n=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return n==="localhost"||n==="127.0.0.1"||n==="::1"};async function Fv(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 Uv=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 Bv=24*1024*1024,Bh=1024*1024*1024,Zv=1e4,qv=100,Zh="https://api.smith.langchain.com";class Vv{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=wt(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||_b(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:ct("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=Dv(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??ct("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:Uv,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 Vv(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 Fb),this.cachedLSEnvVarsForMetadata=Ad(),e.cache===!0?this._cache=new Sb:e.cache&&typeof e.cache=="object"?this._cache=e.cache:this._cache=void 0}static getDefaultClientConfig(){const e=ct("API_KEY"),n=ct("ENDPOINT")??Zh,r=ct("HIDE_INPUTS")==="true",s=ct("HIDE_OUTPUTS")==="true";return{apiUrl:n,apiKey:e,webUrl:void 0,hideInputs:r,hideOutputs:s}}getHostUrl(){return this.webUrl?this.webUrl:zv(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 J(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 J(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 J(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??Bv}async _getBatchSizeLimit(){const e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??qv}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(Zv),...this.fetchOptions});return await J(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=Lb();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=wt(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 J(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(wt(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 J(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=wt(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=wt(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 Y,Be;if(Array.isArray(ue)?[Y,Be]=ue:(Y=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:`${Y}; 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=gb(),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 J(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=wt(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 J(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:ct("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 Fv(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(Y=>Y.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 J(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 J(j,"get run stats"),j})).json()}async shareRun(e,{shareId:n}={}){const r={run_id:e,share_token:n||Un()};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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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]??Un())}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 J(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 J(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 J(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 J(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 J(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??Un(),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 J(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 J(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 J(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 J(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 J(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||Un(),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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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]=Tn(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 J(c,`${n?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(e){const[n,r,s]=Tn(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]=Tn(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 J(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]=Tn(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 J(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]=Tn(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 J(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=wt(c,`Serializing body for example with id: ${o}`),l=new Blob([u],{type:"application/json"});if(r.append(o,l),i.inputs){const d=wt(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=wt(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=wt(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 J(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??Un()).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=wt(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=wt(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=wt(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 J(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]=Tn(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 J(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]=Tn(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 J(i,"delete prompt"),i})).json()}_getPromptCacheKey(e,n){return`${e}${n?":with_model":""}`}async _fetchPromptFromApi(e,n){const[r,s,a]=Tn(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 J(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 jb()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function qh(t){return"dataset_id"in t||"dataset_name"in t}const Hv=t=>!!["TRACING_V2","TRACING"].find(n=>ct(n)==="true"),xn=Symbol.for("lc:context_variables"),hc=Symbol.for("langsmith:replica_trace_roots");function Vh(t,e){if(xn in t)return t[xn][e]}function Gv(t,e,n){const r=xn in t?t[xn]:{};r[e]=n,t[xn]=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 Wv(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:Wv(r)+e,microsecondPrecisionDatestring:r}}const Jv=new Set(["projectName","updates","reroot"]);function Kv(t){const e={};for(const n of Object.keys(t))Jv.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:Kv(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 pt{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}),Xv(e)){Object.assign(this,{...e});return}const n=pt.getDefaultConfig(),{metadata:r,...s}=e,a=s.client??pt.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=wb(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=t0(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 pt.sharedClient||(pt.sharedClient=new Zr),pt.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 pt({...e,parent_run:this,project_name:this.project_name,replicas:s,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:n,child_execution_order:n});xn in this&&(a[xn]=this[xn]);const i=Symbol.for("lc:child_config"),o=e.extra?.[i]??this.extra[i];if(Qv(o)){const l={...o},d=Yv(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,hc)??{};r[e]=n,Gv(this,hc,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,hc)??{},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=Hv();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 pt({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 pt({...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 pt(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(pt,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function Xv(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 Yv(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}function Qv(t){const e=t?.callbacks;return t!=null&&typeof e=="object"&&(Kh(e?.handlers)||Kh(e))}function e0(){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){n0(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(Rv(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 t0(t){return t?t.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):e0()}function n0(t){if(Object.keys(t).length>0&&ct("ENDPOINT"))throw new Cv}var r0={};ge(r0,{BaseTracer:()=>or,isBaseTracer:()=>ir});const s0=t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t};function fc(t,e){if(t)return new pt({...t,start_time:t._serialized_start_time??t.start_time,parent_run:fc(e),child_runs:t.child_runs.map(n=>fc(n)).filter(n=>n!==void 0),extra:{...t.extra,runtime:cd()},tracingEnabled:!1})}function pc(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}function ir(t){return typeof t._addRunToRunMap=="function"}var or=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?s0(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=fc(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=pc(t,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),s?.inputs!==void 0&&(a.inputs=pc(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=pc(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 a0(){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 i0=a0(),Yh=Ms(i0),o0={};ge(o0,{ConsoleCallbackHandler:()=>mc});function lt(t,e){return`${t.open}${e}${t.close}`}function $t(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}function Qh(t){return typeof t=="string"?t.trim():t==null?t:$t(t,t.toString())}function In(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:mt}=Yh;var mc=class extends or{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?lt(Yh.bold,i):i}).join(" > ");return lt(mt.grey,n)}onChainStart(t){const e=this.getBreadcrumbs(t);console.log(`${lt(mt.green,"[chain/start]")} [${e}] Entering Chain run with input: ${$t(t.inputs,"[inputs]")}`)}onChainEnd(t){const e=this.getBreadcrumbs(t);console.log(`${lt(mt.cyan,"[chain/end]")} [${e}] [${In(t)}] Exiting Chain run with output: ${$t(t.outputs,"[outputs]")}`)}onChainError(t){const e=this.getBreadcrumbs(t);console.log(`${lt(mt.red,"[chain/error]")} [${e}] [${In(t)}] Chain run errored with error: ${$t(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(`${lt(mt.green,"[llm/start]")} [${e}] Entering LLM run with input: ${$t(n,"[inputs]")}`)}onLLMEnd(t){const e=this.getBreadcrumbs(t);console.log(`${lt(mt.cyan,"[llm/end]")} [${e}] [${In(t)}] Exiting LLM run with output: ${$t(t.outputs,"[response]")}`)}onLLMError(t){const e=this.getBreadcrumbs(t);console.log(`${lt(mt.red,"[llm/error]")} [${e}] [${In(t)}] LLM run errored with error: ${$t(t.error,"[error]")}`)}onToolStart(t){const e=this.getBreadcrumbs(t);console.log(`${lt(mt.green,"[tool/start]")} [${e}] Entering Tool run with input: "${Qh(t.inputs.input)}"`)}onToolEnd(t){const e=this.getBreadcrumbs(t);console.log(`${lt(mt.cyan,"[tool/end]")} [${e}] [${In(t)}] Exiting Tool run with output: "${Qh(t.outputs?.output)}"`)}onToolError(t){const e=this.getBreadcrumbs(t);console.log(`${lt(mt.red,"[tool/error]")} [${e}] [${In(t)}] Tool run errored with error: ${$t(t.error,"[error]")}`)}onRetrieverStart(t){const e=this.getBreadcrumbs(t);console.log(`${lt(mt.green,"[retriever/start]")} [${e}] Entering Retriever run with input: ${$t(t.inputs,"[inputs]")}`)}onRetrieverEnd(t){const e=this.getBreadcrumbs(t);console.log(`${lt(mt.cyan,"[retriever/end]")} [${e}] [${In(t)}] Exiting Retriever run with output: ${$t(t.outputs,"[outputs]")}`)}onRetrieverError(t){const e=this.getBreadcrumbs(t);console.log(`${lt(mt.red,"[retriever/error]")} [${e}] [${In(t)}] Retriever run errored with error: ${$t(t.error,"[error]")}`)}onAgentAction(t){const e=t,n=this.getBreadcrumbs(t);console.log(`${lt(mt.blue,"[agent/action]")} [${n}] Agent selected action: ${$t(e.actions[e.actions.length-1],"[action]")}`)}};let gc;const ef=()=>{if(gc===void 0){const t=st("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};gc=new Zr(t)}return gc};let c0=class{getStore(){}run(e,n){return n()}};const _c=Symbol.for("ls:tracing_async_local_storage"),u0=new c0;let l0=class{getInstance(){return globalThis[_c]??u0}initializeGlobalInstance(e){globalThis[_c]===void 0&&(globalThis[_c]=e)}};const d0=new l0;function h0(t=!1){const e=d0.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 yc(t){return typeof t=="function"&&"langsmith:traceable"in t}var f0={};ge(f0,{LangChainTracer:()=>ua});function p0(t){let e;for(const n of t)for(const r of n)on.isInstance(r.message)&&r.message.usage_metadata!==void 0&&(e=Wi(e,r.message.usage_metadata));return e}var ua=class ay extends or{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=ay.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=p0(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 pt({...n,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return h0(!0)}catch{return}}};let Bn;function m0(){const t="default"in cn?cn.default:cn;return new t({autoStart:!0,concurrency:1})}function g0(){return typeof Bn>"u"&&(Bn=m0()),Bn}async function Fe(t,e){if(e===!0){const n=Nr();n!==void 0?await n.run(void 0,async()=>t()):await t()}else Bn=g0(),Bn.add(async()=>{const n=Nr();n!==void 0?await n.run(void 0,async()=>t()):await t()})}async function _0(){const t=ef();await Promise.allSettled([typeof Bn<"u"?Bn.onIdle():Promise.resolve(),t.awaitPendingTraceBatches()])}var y0={};ge(y0,{awaitAllCallbacks:()=>_0,consumeCallback:()=>Fe});const w0=t=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(n=>st(n)==="true");function tf(t){const e=Nr();return e===void 0?void 0:e.getStore()?.[Rr]?.[t]}const b0=Symbol("lc:configure_hooks"),v0=()=>tf(b0)||[];var E0={};ge(E0,{BaseCallbackManager:()=>nf,BaseRunManager:()=>Hr,CallbackManager:()=>dt,CallbackManagerForChainRun:()=>sf,CallbackManagerForLLMRun:()=>wc,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 dt(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)))}},wc=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 dt(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 dt(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)))}},dt=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:Sn();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return ir(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 wc(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:Sn();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return ir(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=Yi(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 wc(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,n,r=Sn(),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 ir(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=Sn(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreAgent)return ir(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=Sn(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return ir(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=Sn();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=st("LANGCHAIN_VERBOSE")==="true"||o?.verbose,l=ua.getTraceableRunTree()?.tracingEnabled??w0(),d=l||(st("LANGCHAIN_TRACING")??!1);if(u||d){if(c||(c=new Os),u&&!c.handlers.some(f=>f.name===mc.prototype.name)){const f=new mc;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 v0()){const y=m&&st(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 S0=new of,cf=Symbol.for("lc:child_config");var T0=class{getInstance(){return Nr()??S0}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[cf]}runWithConfig(t,e,n){const r=dt._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 pt({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&&Ny(t)}};const Dt=new T0;var x0={};ge(x0,{AsyncLocalStorageProviderSingleton:()=>Dt,MockAsyncLocalStorage:()=>of,_CONTEXT_VARIABLES_KEY:()=>Rr});const bc=25;async function bt(t){return dt._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 dt(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 I0=new Set(["string","number","boolean"]);function we(t){const e=Dt.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))I0.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 A0={};ge(A0,{AsyncGeneratorWithSetup:()=>Zn,IterableReadableStream:()=>zt,atee:()=>vc,concat:()=>An,pipeGeneratorWithSetup:()=>uf});var zt=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 vc(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 An(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]=An(n[r],s):n[r]=s;return n}else throw new Error(`Cannot concat ${typeof t} and ${typeof e}`)}var Zn=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)=>{Dt.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?Dt.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 Zn({generator:e,startSetup:n,signal:r}),i=await a.setup;return{output:t(a,i,...s),setup:i}}const k0=Object.prototype.hasOwnProperty;function Ec(t,e){return k0.call(t,e)}function Sc(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)Ec(t,n)&&e.push(n);return e}function Ft(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Tc(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 cr(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\\//g,"~1")}function O0(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function xc(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let n=0,r=t.length;n<r;n++)if(xc(t[n]))return!0}else if(typeof t=="object"){const n=Sc(t),r=n.length;for(var e=0;e<r;e++)if(xc(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 $0=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:()=>qn,applyPatch:()=>lr,applyReducer:()=>N0,deepClone:()=>C0,getValueByPointer:()=>da,validate:()=>hf,validator:()=>ha});const Le=$0,C0=Ft;function Ic(t){return Object.getOwnPropertyNames(Object.prototype).includes(t)}const ur={add:function(t,e,n){if(Ic(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(Ic(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(Ic(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=Ft(r));const s=qn(n,{op:"remove",path:this.from}).removed;return qn(n,{op:"add",path:this.path,value:s}),{newDocument:n,removed:r}},copy:function(t,e,n){const r=da(n,this.from);return qn(n,{op:"add",path:this.path,value:Ft(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 R0={add:function(t,e,n){return Tc(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:ur.move,copy:ur.copy,test:ur.test,_get:ur._get};function da(t,e){if(e=="")return t;var n={op:"_get",path:e};return qn(t,n),n.value}function qn(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=Ft(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=O0(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&&!Tc(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);Tc(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=R0[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=ur[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 lr(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=Ft(t));const a=new Array(e.length);for(let i=0,o=e.length;i<o;i++)a[i]=qn(t,e[i],n,!0,s,i),t=a[i].newDocument;return a.newDocument=t,a}function N0(t,e,n){const r=qn(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(ur[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")&&xc(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)lr(Ft(e),Ft(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=Sc(e),i=Sc(t),o=!1,c=i.length-1;c>=0;c--){var u=i[c],l=t[u];if(Ec(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+"/"+cr(u),s):l!==d&&(s&&n.push({op:"test",path:r+"/"+cr(u),value:Ft(l)}),n.push({op:"replace",path:r+"/"+cr(u),value:Ft(d)}))}else Array.isArray(t)===Array.isArray(e)?(s&&n.push({op:"test",path:r+"/"+cr(u),value:Ft(l)}),n.push({op:"remove",path:r+"/"+cr(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];!Ec(t,u)&&e[u]!==void 0&&n.push({op:"add",path:r+"/"+cr(u),value:Ft(e[u])})}}}function Ac(t,e,n=!1){var r=[];return ff(t,e,r,"",n),r}({...df});var P0={};ge(P0,{LogStreamCallbackHandler:()=>Oc,RunLog:()=>kc,RunLogPatch:()=>dn,isLogStreamHandler:()=>pf});var dn=class{ops;constructor(t){this.ops=t.ops??[]}concat(t){const e=this.ops.concat(t.ops),n=lr({},e);return new kc({ops:e,state:n[n.length-1].newDocument})}},kc=class Tl extends dn{state;constructor(e){super(e),this.state=e.state}concat(e){const n=this.ops.concat(e.ops),r=lr(this.state,e.ops);return new Tl({ops:n,state:r[r.length-1].newDocument})}static fromRunLogPatch(e){const n=lr({},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 M0(t){return t!==void 0&&t.message!==void 0}var Oc=class extends or{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=zt.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?M0(n?.chunk)?a=n?.chunk:a=new Fn({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)}},L0={};ge(L0,{ChatGenerationChunk:()=>$c,GenerationChunk:()=>dr,RUN_KEY:()=>Kr});const Kr="__run";var dr=class iy{text;generationInfo;constructor(e){this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new iy({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}},$c=class oy extends dr{message;constructor(e){super(e),this.message=e.message}concat(e){return new oy({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 j0=t=>t.name==="event_stream_tracer";var D0=class extends or{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=zt.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 dr({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 Fn({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 dr({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 z0=Object.prototype.toString,F0=t=>z0.call(t)==="[object Error]",U0=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 B0(t){if(!(t&&F0(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:U0.has(n)}function Z0(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 q0=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 V0(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 H0({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 q0)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&&!B0(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=V0(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 Cc(t,e={}){if(e={...e},Z0(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 H0({error:a,attemptNumber:n,retriesConsumed:r,startTime:s,options:e})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}var G0={};ge(G0,{AsyncCaller:()=>Xr});const W0=[400,401,402,403,404,405,406,407,409],J0=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&&W0.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??J0;const e="default"in cn?cn.default:cn;this.queue=new e({concurrency:this.maxConcurrency})}async call(t,...e){return this.queue.add(()=>Cc(()=>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 or{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 Rc(t){return t?t.lc_runnable:!1}var K0=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 X0=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 kn(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 Y0(t,e){return typeof e=="bigint"?e.toString():e}function Nc(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function Pc(t){return t==null}function Mc(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function Q0(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 Lc(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 eE=Nc(()=>{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 tE=new Set(["string","number","symbol"]);function es(t){return t.replace(/[.*+?^${}()|[\\]\\\\]/g,"\\\\$&")}function at(t,e,n){const r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function ee(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 nE(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const rE={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 sE(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 at(t,{...t._zod.def,shape:n,checks:[]})}function aE(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 at(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 Lc(this,"shape",r),r},checks:[]};return at(t,n)}function iE(t,e){return at(t,{...t._zod.def,get shape(){const n={...t._zod.def.shape,...e._zod.def.shape};return Lc(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 at(e,{...e._zod.def,shape:s,checks:[]})}function oE(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 at(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 Vn(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 On(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 jc(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,Y0,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},xf=I("$ZodError",Tf),ya=I("$ZodError",Tf,{Parent:Error});function cE(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 uE(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 lE(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 dE(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 ${lE(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=>On(c,a,kn())));throw vf(o,s?.callee),o}return i.value},Dc=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=>On(c,a,kn())));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=>On(i,s,kn())))}:{success:!0,data:a.value}},hE=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=>On(i,s,kn())))}:{success:!0,data:a.value}},fE=$f(ya),pE=/^[cC][^\\s-]{8,}$/,mE=/^[0-9a-z]+$/,gE=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,_E=/^[0-9a-vA-V]{20}$/,yE=/^[A-Za-z0-9]{27}$/,wE=/^[a-zA-Z0-9_-]{21}$/,bE=/^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/,vE=/^([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)$/,EE=/^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_\'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/,SE="^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$";function TE(){return new RegExp(SE,"u")}const xE=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,IE=/^(([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})$/,AE=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/,kE=/^(([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])$/,OE=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Rf=/^[A-Za-z0-9_-]*$/,$E=/^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/,CE=/^\\+(?:[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])))",RE=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 NE(t){return new RegExp(`^${Pf(t)}$`)}function PE(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 ME=t=>{const e=t?`[\\\\s\\\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\\\s\\\\S]*";return new RegExp(`^${e}$`)},LE=/^\\d+$/,jE=/^-?\\d+(?:\\.\\d+)?/i,DE=/^[^A-Z]*$/,zE=/^[^a-z]*$/,gt=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)=>{gt.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)=>{gt.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})}}),FE=I("$ZodCheckMultipleOf",(t,e)=>{gt.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):Q0(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})}}),UE=I("$ZodCheckNumberFormat",(t,e)=>{gt.init(t,e),e.format=e.format||"float64";const n=e.format?.includes("int"),r=n?"int":"number",[s,a]=rE[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=LE)}),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})}}),BE=I("$ZodCheckMaxLength",(t,e)=>{var n;gt.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Pc(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=jc(s);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),ZE=I("$ZodCheckMinLength",(t,e)=>{var n;gt.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Pc(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=jc(s);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),qE=I("$ZodCheckLengthEquals",(t,e)=>{var n;gt.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Pc(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=jc(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;gt.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=()=>{})}),VE=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})}}),HE=I("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=DE),wa.init(t,e)}),GE=I("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=zE),wa.init(t,e)}),WE=I("$ZodCheckIncludes",(t,e)=>{gt.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})}}),JE=I("$ZodCheckStartsWith",(t,e)=>{gt.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})}}),KE=I("$ZodCheckEndsWith",(t,e)=>{gt.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})}}),XE=I("$ZodCheckOverwrite",(t,e)=>{gt.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class YE{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 QE={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=QE;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=hE(t,s);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return fE(t,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),zc=I("$ZodString",(t,e)=>{Re.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??ME(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),zc.init(t,e)}),eS=I("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=vE),$e.init(t,e)}),tS=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)}),nS=I("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=EE),$e.init(t,e)}),rS=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:$E.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})}}}),sS=I("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=TE()),$e.init(t,e)}),aS=I("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=wE),$e.init(t,e)}),iS=I("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=pE),$e.init(t,e)}),oS=I("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=mE),$e.init(t,e)}),cS=I("$ZodULID",(t,e)=>{e.pattern??(e.pattern=gE),$e.init(t,e)}),uS=I("$ZodXID",(t,e)=>{e.pattern??(e.pattern=_E),$e.init(t,e)}),lS=I("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=yE),$e.init(t,e)}),dS=I("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=PE(e)),$e.init(t,e)}),hS=I("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=RE),$e.init(t,e)}),fS=I("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=NE(e)),$e.init(t,e)}),pS=I("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=bE),$e.init(t,e)}),mS=I("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=xE),$e.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),gS=I("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=IE),$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})}}}),_S=I("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=AE),$e.init(t,e)}),yS=I("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=kE),$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 wS=I("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=OE),$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 bS(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 vS=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=>{bS(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),ES=I("$ZodE164",(t,e)=>{e.pattern??(e.pattern=CE),$e.init(t,e)});function SS(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 TS=I("$ZodJWT",(t,e)=>{$e.init(t,e),t._zod.check=n=>{SS(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??jE,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}}),xS=I("$ZodNumber",(t,e)=>{UE.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(...Vn(n,t.issues)),e.value[n]=t.value}const IS=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(...Vn(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(...Vn(n,t.issues)):t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}const AS=I("$ZodObject",(t,e)=>{Re.init(t,e);const n=Nc(()=>{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=nE(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 YE(["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&&eE.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=>On(a,r,kn())))}),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=>Mc(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)}}),kS=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=Nc(()=>{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)}}),OS=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 Fc(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=Fc(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=Fc(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=Fc(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 $S=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(...Vn(c,l.issues)),n.value[c]=l.value})):(u.issues.length&&n.issues.push(...Vn(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=>On(u,r,kn())),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(...Vn(i,u.issues)),n.value[o.value]=u.value})):(c.issues.length&&n.issues.push(...Vn(i,c.issues)),n.value[o.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),CS=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=>tE.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}}),RS=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}}),NS=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}}),Uc=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(`^(${Mc(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)}),PS=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(`^(${Mc(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)}),MS=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 LS=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))}),jS=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 DS=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=>On(i,r,kn()))},input:n.value}),n.issues=[]),n)):(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(a=>On(a,r,kn()))},input:n.value}),n.issues=[]),n)}}),zS=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 FS=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 US=I("$ZodCustom",(t,e)=>{gt.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 BS(){return new Yf}const Je=BS();function ZS(t,e){return new t({type:"string",...ee(e)})}function qS(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ee(e)})}function Qf(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ee(e)})}function VS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ee(e)})}function HS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ee(e)})}function GS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ee(e)})}function WS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ee(e)})}function JS(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ee(e)})}function KS(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ee(e)})}function XS(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ee(e)})}function YS(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ee(e)})}function QS(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ee(e)})}function eT(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ee(e)})}function tT(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ee(e)})}function nT(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ee(e)})}function rT(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ee(e)})}function sT(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ee(e)})}function aT(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ee(e)})}function iT(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ee(e)})}function oT(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ee(e)})}function cT(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ee(e)})}function uT(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ee(e)})}function lT(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ee(e)})}function dT(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ee(e)})}function hT(t,e){return new t({type:"string",format:"date",check:"string_format",...ee(e)})}function fT(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ee(e)})}function pT(t,e){return new t({type:"string",format:"duration",check:"string_format",...ee(e)})}function mT(t,e){return new t({type:"number",checks:[],...ee(e)})}function gT(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ee(e)})}function ep(t){return new t({type:"unknown"})}function tp(t,e){return new t({type:"never",...ee(e)})}function np(t,e){return new Lf({check:"less_than",...ee(e),value:t,inclusive:!1})}function Bc(t,e){return new Lf({check:"less_than",...ee(e),value:t,inclusive:!0})}function rp(t,e){return new jf({check:"greater_than",...ee(e),value:t,inclusive:!1})}function Zc(t,e){return new jf({check:"greater_than",...ee(e),value:t,inclusive:!0})}function sp(t,e){return new FE({check:"multiple_of",...ee(e),value:t})}function ap(t,e){return new BE({check:"max_length",...ee(e),maximum:t})}function va(t,e){return new ZE({check:"min_length",...ee(e),minimum:t})}function ip(t,e){return new qE({check:"length_equals",...ee(e),length:t})}function _T(t,e){return new VE({check:"string_format",format:"regex",...ee(e),pattern:t})}function yT(t){return new HE({check:"string_format",format:"lowercase",...ee(t)})}function wT(t){return new GE({check:"string_format",format:"uppercase",...ee(t)})}function bT(t,e){return new WE({check:"string_format",format:"includes",...ee(e),includes:t})}function vT(t,e){return new JE({check:"string_format",format:"starts_with",...ee(e),prefix:t})}function ET(t,e){return new KE({check:"string_format",format:"ends_with",...ee(e),suffix:t})}function rs(t){return new XE({check:"overwrite",tx:t})}function ST(t){return rs(e=>e.normalize(t))}function TT(){return rs(t=>t.trim())}function xT(){return rs(t=>t.toLowerCase())}function IT(){return rs(t=>t.toUpperCase())}function AT(t,e,n){return new t({type:"array",element:e,...ee(n)})}function kT(t,e,n){return new t({type:"custom",check:"custom",fn:e,...ee(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 OT(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 hr(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 $T(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 CT(t,e){if(Ne(t))try{return{success:!0,data:Dc(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 RT(t,e){if(Ne(t))return Dc(t,e);if(Ve(t))return t.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function qc(t){if(Ne(t))return Je.get(t)?.description;if(Ve(t)||"description"in t&&typeof t.description=="string")return t.description}function NT(t){if(!hr(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 Vc(t){return hr(t)?Ve(t)?t._def.typeName==="ZodString":Ne(t)?t._zod.def.type==="string":!1:!1}function Hc(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 PT(t){return!!(Hc(t)||Yt(t))}function Gc(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 MT(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 LT(t){if(Ve(t))return t.partial();if(Ne(t))return Sf(Uc,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]=at(i,{...i._zod.def,element:c})}else n[a]=i;const o=Je.get(i);o&&Je.add(n[a],o)}const r=at(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 Wc(t,e=!1){if(Hc(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=Wc(i,e);n[a]=c}else if(Sa(i)){let c=i._zod.def.element;Yt(c)&&(c=Wc(c,e)),n[a]=at(i,{...i._zod.def,element:c})}else n[a]=i;const o=Je.get(i);o&&Je.add(n[a],o)}const r=at(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 jT(t){if(Ve(t))try{const e=t.parse(void 0);return()=>e}catch{return}if(Ne(t))try{const e=Dc(t,void 0);return()=>e}catch{return}}function DT(t){return Ve(t)&&"typeName"in t._def&&t._def.typeName==="ZodEffects"}function zT(t){return Ne(t)&&t._zod.def.type==="pipe"}function Hn(t,e,n){const r=n.get(t);if(r!==void 0)return r;if(Ve(t))return DT(t)?Hn(t._def.schema,e,n):t;if(Ne(t)){let s=t;if(zT(t)&&(s=Hn(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]=Hn(c,e,n);s=at(s,{...s._zod.def,shape:i})}else if(Sa(s)){const i=Hn(s._zod.def.element,e,n);s=at(s,{...s._zod.def,element:i})}else if(hp(s)){const i=Hn(s._zod.def.innerType,e,n);s=at(s,{...s._zod.def,innerType:i})}else if(fp(s)){const i=Hn(s._zod.def.innerType,e,n);s=at(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 Hn(t,e,new WeakMap)}function FT(t,e){if(Ve(t)){const n=Gc(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=Gc(t),r={...t._zod.def.shape};for(const[i,o]of Object.entries(n))e(i,o)&&(r[i]=new Uc({type:"optional",innerType:o}));const s=at(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 Jc(t){return t.replace(/[^a-zA-Z-_0-9]/g,"_")}const UT=["*","_","`"];function BT(t){let e="";for(const[n,r]of Object.entries(t))e+=` classDef ${n} ${r};\n`;return e}function ZT(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=UT.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}",Jc(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,Y)=>oe.slice(Y*c,(Y+1)*c).join(" ")).join("&nbsp;<br>&nbsp;")),j=N?` -. &nbsp;${b}&nbsp; .-> `:` -- &nbsp;${b}&nbsp; --> `}else j=N?" -.-> ":" --> ";u+=` ${Jc(E)}${j}${Jc(x)};\n`}m&&!y&&(u+=` end\n`)}h(l[""]??[],"");for(const p in l)!p.includes(":")&&p!==""&&h(l[p],p);return i&&(u+=BT(a??{})),u}async function qT(t,e){let n=e?.backgroundColor??"white";const r=e?.imageType??"png",s=X0(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 VT=Symbol("Let zodToJsonSchema decide on which parser to use"),HT={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"},GT=t=>({...HT,...t}),WT=t=>{const e=GT(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 vt(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"]),$n=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 Kc=(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 JT=Kc;function KT(){return JT}const XT=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=KT(),r=XT({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Kc?void 0:Kc].filter(s=>!!s)});t.common.issues.push(r)}class Et{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 Et.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}),Ct=t=>({status:"valid",value:t}),wp=t=>t.status==="aborted",bp=t=>t.status==="dirty",fr=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 Cn{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(fr(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 $n(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:$n(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Et,ctx:{common:e.parent.common,data:e.data,parsedType:$n(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:$n(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:$n(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:n});return fr(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=>fr(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:$n(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 gr({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 Nn.create(this,this._def)}nullable(){return _r.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pr.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 gr({..._e(this._def),schema:this,typeName:C.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new nu({..._e(this._def),innerType:this,defaultValue:n,typeName:C.ZodDefault})}brand(){return new bx({typeName:C.ZodBranded,type:this,..._e(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new ru({..._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 su.create(this,e)}readonly(){return au.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const YT=/^c[^\\s-]{8,}$/i,QT=/^[0-9a-z]+$/,ex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,tx=/^[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,nx=/^[a-z0-9_-]{21}$/i,rx=/^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/,sx=/^[-+]?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)?)??$/,ax=/^(?!\\.)(?!.*\\.\\.)([A-Z0-9_\'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i,ix="^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$";let Xc;const ox=/^(?:(?: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])$/,cx=/^(?:(?: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])$/,ux=/^(([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]))$/,lx=/^(([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])$/,dx=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,hx=/^([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])))",fx=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 px(t){return new RegExp(`^${Sp(t)}$`)}function mx(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 gx(t,e){return!!((e==="v4"||!e)&&ox.test(t)||(e==="v6"||!e)&&ux.test(t))}function _x(t,e){if(!rx.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 yx(t,e){return!!((e==="v4"||!e)&&cx.test(t)||(e==="v6"||!e)&&lx.test(t))}let Yc=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 Et;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")ax.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")Xc||(Xc=new RegExp(ix,"u")),Xc.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")tx.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")nx.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")YT.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")QT.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")ex.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"?mx(a).test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{code:$.invalid_string,validation:"datetime",message:a.message}),r.dirty()):a.kind==="date"?fx.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{code:$.invalid_string,validation:"date",message:a.message}),r.dirty()):a.kind==="time"?px(a).test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{code:$.invalid_string,validation:"time",message:a.message}),r.dirty()):a.kind==="duration"?sx.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"duration",code:$.invalid_string,message:a.message}),r.dirty()):a.kind==="ip"?gx(e.data,a.version)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"ip",code:$.invalid_string,message:a.message}),r.dirty()):a.kind==="jwt"?_x(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"jwt",code:$.invalid_string,message:a.message}),r.dirty()):a.kind==="cidr"?yx(e.data,a.version)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"cidr",code:$.invalid_string,message:a.message}),r.dirty()):a.kind==="base64"?dx.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"base64",code:$.invalid_string,message:a.message}),r.dirty()):a.kind==="base64url"?hx.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}};Yc.create=t=>new Yc({checks:[],typeName:C.ZodString,coerce:t?.coerce??!1,..._e(t)});function wx(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 Et;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"?wx(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 Et;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 Ct(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 Et;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 Ct(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 Ct(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 Ct(e.data)}}kp.create=t=>new kp({typeName:C.ZodNull,..._e(t)});class Qc extends be{constructor(){super(...arguments),this._any=!0}_parse(e){return Ct(e.data)}}Qc.create=t=>new Qc({typeName:C.ZodAny,..._e(t)});let Op=class extends be{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ct(e.data)}};Op.create=t=>new Op({typeName:C.ZodUnknown,..._e(t)});let Rn=class extends be{_parse(e){const n=this._getOrReturnCtx(e);return F(n,{code:$.invalid_type,expected:V.never,received:n.parsedType}),he}};Rn.create=t=>new Rn({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 Ct(e.data)}}$p.create=t=>new $p({typeName:C.ZodVoid,..._e(t)});let pr=class Ni 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 Cn(n,i,n.path,o)))).then(i=>Et.mergeArray(r,i));const a=[...n.data].map((i,o)=>s.type._parseSync(new Cn(n,i,n.path,o)));return Et.mergeArray(r,a)}get element(){return this._def.type}min(e,n){return new Ni({...this._def,minLength:{value:e,message:G.toString(n)}})}max(e,n){return new Ni({...this._def,maxLength:{value:e,message:G.toString(n)}})}length(e,n){return new Ni({...this._def,exactLength:{value:e,message:G.toString(n)}})}nonempty(e){return this.min(1,e)}};pr.create=(t,e)=>new pr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:C.ZodArray,..._e(e)});function mr(t){if(t instanceof fn){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=Nn.create(mr(r))}return new fn({...t._def,shape:()=>e})}else return t instanceof pr?new pr({...t._def,type:mr(t.element)}):t instanceof Nn?Nn.create(mr(t.unwrap())):t instanceof _r?_r.create(mr(t.unwrap())):t instanceof Gn?Gn.create(t.items.map(e=>mr(e))):t}let fn=class Jt 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 Rn&&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 Cn(s,d,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof Rn){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 Cn(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=>Et.mergeObjectSync(r,u)):Et.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return G.errToObj,new Jt({...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 Jt({...this._def,unknownKeys:"strip"})}passthrough(){return new Jt({...this._def,unknownKeys:"passthrough"})}extend(e){return new Jt({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Jt({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 Jt({...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 Jt({...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 Jt({...this._def,shape:()=>n})}deepPartial(){return mr(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 Jt({...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 Nn;)a=a._def.innerType;n[r]=a}return new Jt({...this._def,shape:()=>n})}keyof(){return Pp(ve.objectKeys(this.shape))}};fn.create=(t,e)=>new fn({shape:()=>t,unknownKeys:"strip",catchall:Rn.create(),typeName:C.ZodObject,..._e(e)}),fn.strictCreate=(t,e)=>new fn({shape:()=>t,unknownKeys:"strict",catchall:Rn.create(),typeName:C.ZodObject,..._e(e)}),fn.lazycreate=(t,e)=>new fn({shape:t,unknownKeys:"strip",catchall:Rn.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 eu(t,e){const n=$n(t),r=$n(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=eu(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=eu(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=eu(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 Gn 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 Cn(r,i,r.path,o)):null}).filter(i=>!!i);return r.common.async?Promise.all(a).then(i=>Et.mergeArray(n,i)):Et.mergeArray(n,a)}get items(){return this._def.items}rest(e){return new Gn({...this._def,rest:e})}}Gn.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Gn({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 Cn(r,o,r.path,[u,"key"])),value:a._parse(new Cn(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 Cn(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 tu({values:t,typeName:C.ZodEnum,..._e(e)})}let tu=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 Ct(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})}};tu.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 Ct(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 Ct(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 gr 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(!fr(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=>fr(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:n.value,value:o})):he);ve.assertNever(s)}}gr.create=(t,e,n)=>new gr({schema:t,typeName:C.ZodEffects,effect:e,..._e(n)}),gr.createWithPreprocess=(t,e,n)=>new gr({schema:e,effect:{type:"preprocess",transform:t},typeName:C.ZodEffects,..._e(n)});let Nn=class extends be{_parse(e){return this._getType(e)===V.undefined?Ct(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Nn.create=(t,e)=>new Nn({innerType:t,typeName:C.ZodOptional,..._e(e)});let _r=class extends be{_parse(e){return this._getType(e)===V.null?Ct(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_r.create=(t,e)=>new _r({innerType:t,typeName:C.ZodNullable,..._e(e)});let nu=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}};nu.create=(t,e)=>new nu({innerType:t,typeName:C.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._e(e)});let ru=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}};ru.create=(t,e)=>new ru({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 bx 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 su 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 su({in:e,out:n,typeName:C.ZodPipeline})}}let au=class extends be{_parse(e){const n=this._def.innerType._parse(e),r=s=>(fr(s)&&(s.value=Object.freeze(s.value)),s);return xa(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};au.create=(t,e)=>new au({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=Yc.create,jp=Qc.create;Rn.create,pr.create;const Ca=fn.create;Aa.create,ka.create,Gn.create,tu.create,Oa.create,Nn.create,_r.create;function vx(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 Ex(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 Sx(){return{type:"boolean"}}function Dp(t,e){return Te(t.type._def,e)}const Tx=(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 xx(t,e)}}const xx=(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 Ix(t,e){return{...Te(t.innerType._def,e),default:t.defaultValue()}}function Ax(t,e){return e.effectStrategy==="input"?Te(t.schema._def,e):vt(e)}function kx(t){return{type:"string",enum:Array.from(t.values)}}const Ox=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function $x(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(Ox(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 Cx(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 iu;const Ut={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:()=>(iu===void 0&&(iu=RegExp("^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$","u")),iu),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":Bt(n,"email",r.message,e);break;case"format:idn-email":Bt(n,"idn-email",r.message,e);break;case"pattern:zod":ht(n,Ut.email,r.message,e);break}break;case"url":Bt(n,"uri",r.message,e);break;case"uuid":Bt(n,"uuid",r.message,e);break;case"regex":ht(n,r.regex,r.message,e);break;case"cuid":ht(n,Ut.cuid,r.message,e);break;case"cuid2":ht(n,Ut.cuid2,r.message,e);break;case"startsWith":ht(n,RegExp(`^${ou(r.value,e)}`),r.message,e);break;case"endsWith":ht(n,RegExp(`${ou(r.value,e)}$`),r.message,e);break;case"datetime":Bt(n,"date-time",r.message,e);break;case"date":Bt(n,"date",r.message,e);break;case"time":Bt(n,"time",r.message,e);break;case"duration":Bt(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":ht(n,RegExp(ou(r.value,e)),r.message,e);break;case"ip":r.version!=="v6"&&Bt(n,"ipv4",r.message,e),r.version!=="v4"&&Bt(n,"ipv6",r.message,e);break;case"base64url":ht(n,Ut.base64url,r.message,e);break;case"jwt":ht(n,Ut.jwt,r.message,e);break;case"cidr":r.version!=="v6"&&ht(n,Ut.ipv4Cidr,r.message,e),r.version!=="v4"&&ht(n,Ut.ipv6Cidr,r.message,e);break;case"emoji":ht(n,Ut.emoji(),r.message,e);break;case"ulid":ht(n,Ut.ulid,r.message,e);break;case"base64":switch(e.base64Strategy){case"format:binary":Bt(n,"binary",r.message,e);break;case"contentEncoding:base64":xe(n,"contentEncoding","base64",r.message,e);break;case"pattern:zod":ht(n,Ut.base64,r.message,e);break}break;case"nanoid":ht(n,Ut.nanoid,r.message,e);break}return n}function ou(t,e){return e.patternStrategy==="escape"?Nx(t):t}const Rx=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Nx(t){let e="";for(let n=0;n<t.length;n++)Rx.has(t[n])||(e+="\\\\"),e+=t[n];return e}function Bt(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 ht(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]})??vt(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 Px(t,e){if(e.mapStrategy==="record")return Bp(t,e);const n=Te(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||vt(e),r=Te(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||vt(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function Mx(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 Lx(t){return t.target==="openAi"?void 0:{not:vt({...t,currentPath:[...t.currentPath,"not"]})}}function jx(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Ra={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Dx(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 zx(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 Fx(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 Ux(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=Zx(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=Bx(t,e);return i!==void 0&&(r.additionalProperties=i),r}function Bx(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 Zx(t){try{return t.isOptional()}catch{return!0}}const qx=(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:vt(e)},n]}:vt(e)},Vx=(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 Hx(t,e){return Te(t.type._def,e)}function Gx(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 Wx(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 Jx(t){return{not:vt(t)}}function Kx(t){return vt(t)}const Xx=(t,e)=>Te(t.innerType._def,e),Yx=(t,e,n)=>{switch(e){case C.ZodString:return Fp(t,n);case C.ZodNumber:return Fx(t,n);case C.ZodObject:return Ux(t,n);case C.ZodBigInt:return Ex(t,n);case C.ZodBoolean:return Sx();case C.ZodDate:return zp(t,n);case C.ZodUndefined:return Jx(n);case C.ZodNull:return jx(n);case C.ZodArray:return vx(t,n);case C.ZodUnion:case C.ZodDiscriminatedUnion:return Dx(t,n);case C.ZodIntersection:return $x(t,n);case C.ZodTuple:return Wx(t,n);case C.ZodRecord:return Bp(t,n);case C.ZodLiteral:return Cx(t,n);case C.ZodEnum:return kx(t);case C.ZodNativeEnum:return Mx(t);case C.ZodNullable:return zx(t,n);case C.ZodOptional:return qx(t,n);case C.ZodMap:return Px(t,n);case C.ZodSet:return Gx(t,n);case C.ZodLazy:return()=>t.getter()._def;case C.ZodPromise:return Hx(t,n);case C.ZodNaN:case C.ZodNever:return Lx(n);case C.ZodEffects:return Ax(t,n);case C.ZodAny:return vt(n);case C.ZodUnknown:return Kx(n);case C.ZodDefault:return Ix(t,n);case C.ZodBranded:return Dp(t,n);case C.ZodReadonly:return Xx(t,n);case C.ZodCatch:return Tx(t,n);case C.ZodPipeline:return Vx(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!==VT)return o}if(r&&!n){const o=Qx(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=Yx(t,t.typeName,e),i=typeof a=="function"?Te(a(),e):a;if(i&&eI(t,e,i),e.postProcess){const o=e.postProcess(i,t,e);return s.jsonSchema=i,o}return s.jsonSchema=i,i}const Qx=(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`),vt(e)):e.$refStrategy==="seen"?vt(e):void 0}},eI=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n),tI=(t,e)=>{const n=WT(e);let r;const s=Te(t._def,n,!1)??vt(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 Wn(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(!Wn(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(!Wn(t[i],e[i]))return!1;return!0}return t===e}function Zt(t){return encodeURI(nI(t))}function nI(t){return t.replace(/~/g,"~0").replace(/\\//g,"~1")}const rI={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},sI={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},aI={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 iI=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 Pn(t,e=Object.create(null),n=iI,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:Pn(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(aI[a])continue;const i=`${r}/${Zt(a)}`,o=t[a];if(Array.isArray(o)){if(rI[a]){const c=o.length;for(let u=0;u<c;u++)Pn(o[u],e,n,`${i}/${u}`)}}else if(sI[a])for(let c in o)Pn(o[c],e,n,`${i}/${Zt(c)}`);else Pn(o,e,n,i)}return e}const oI=/^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$/,cI=[0,31,28,31,30,31,30,31,31,30,31,30,31],uI=/^(\\d\\d):(\\d\\d):(\\d\\d)(\\.\\d+)?(z|[+-]\\d\\d(?::?\\d\\d)?)?$/i,lI=/^(?=.{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,dI=/^(?:[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,hI=/^(?:(?:[^\\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,fI=/^(?:(?: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,pI=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,mI=/^(?:\\/(?:[^~/]|~0|~1)*)*$/,gI=/^#(?:\\/(?:[a-z0-9_\\-.!$&\'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,_I=/^(?:0|[1-9][0-9]*)(?:#|(?:\\/(?:[^~/]|~0|~1)*)*)$/,yI=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))},wI=/^(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$/,bI=/^((([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,vI=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":TI,duration:vI,uri:AI,"uri-reference":Qt(dI),"uri-template":Qt(hI),url:Qt(fI),email:yI,hostname:Qt(lI),ipv4:Qt(wI),ipv6:Qt(bI),regex:OI,uuid:Qt(pI),"json-pointer":Qt(mI),"json-pointer-uri-fragment":Qt(gI),"relative-json-pointer":Qt(_I)};function EI(t){return t%4===0&&(t%100!==0||t%400===0)}function Vp(t){const e=t.match(oI);if(!e)return!1;const n=+e[1],r=+e[2],s=+e[3];return r>=1&&r<=12&&s>=1&&s<=(r==2&&EI(n)?29:cI[r])}function Hp(t,e){const n=e.match(uI);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 SI=/t|\\s/i;function TI(t){const e=t.split(SI);return e.length==2&&Vp(e[0])&&Hp(!0,e[1])}const xI=/\\/|:/,II=/^(?:[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 AI(t){return xI.test(t)&&II.test(t)}const kI=/[^\\\\]\\\\Z/;function OI(t){if(kI.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}function $I(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=Pn(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:Y,additionalProperties:Be,unevaluatedProperties:Ot,minProperties:L,maxProperties:R,propertyNames:P,dependentRequired:H,dependentSchemas:Q,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:Wt,maxLength:je,pattern:Rt,__absolute_ref__:$r,__absolute_recursive_ref__:Ci}=e,z=[];if(h===!0&&a===null&&(a=e),f==="#"){const se=a===null?r[Ci]: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"?Wn(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=>Wn(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 tr=[];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&&tr.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&&tr.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&&tr.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,...tr),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}/${Zt(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(Q!==void 0)for(const Z in Q){const D=`${o}/dependentSchemas`;if(Z in t){const ce=Ce(t,Q[Z],n,r,s,a,i,`${D}/${Zt(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}/${Zt(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}/${Zt(D)}`,ae=Ce(t[D],ue[D],n,r,s,a,ce,`${Z}/${Zt(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&&Y!==void 0){const Z=`${o}/patternProperties`;for(const D in Y){const ce=new RegExp(D,"u"),ae=Y[D];for(const yt in t){if(!ce.test(yt))continue;const ey=`${i}/${Zt(yt)}`,ty=Ce(t[yt],ae,n,r,s,a,ey,`${Z}/${Zt(D)}`);ty.valid?c[yt]=te[yt]=!0:(le=s,z.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:Z,error:`Property "${yt}" matches pattern "${D}" but does not match associated schema.`},...ty.errors))}}}if(!le&&Be!==void 0){const Z=`${o}/additionalProperties`;for(const D in t){if(te[D])continue;const ce=`${i}/${Zt(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&&Ot!==void 0){const Z=`${o}/unevaluatedProperties`;for(const D in t)if(!c[D]){const ce=`${i}/${Zt(D)}`,ae=Ce(t[D],Ot,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 yt=Ce(t[ae],ze,n,r,s,a,`${i}/${ae}`,Z);yt.valid?(c[ae]=!0,ce++):z.push(...yt.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 yt=t[ae];(D===yt||ce&&(typeof yt=="object"&&yt!==null)&&Wn(D,yt))&&(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=Wt===void 0&&je===void 0?0:$I(t);Wt!==void 0&&se<Wt&&z.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${se} < ${Wt}).`}),je!==void 0&&se>je&&z.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${se} > ${je}).`}),Rt!==void 0&&!new RegExp(Rt,"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 CI{schema;draft;shortCircuit;lookup;constructor(e,n="2019-09",r=!0){this.schema=e,this.draft=n,this.shortCircuit=r,this.lookup=Pn(e)}validate(e){return Ce(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,n){n&&(e={...e,$id:n}),Pn(e,this.lookup)}}var RI={};ge(RI,{Validator:()=>CI,deepCompareStrict:()=>Wn,toJsonSchema:()=>yr,validatesOnlyStrings:()=>os});function yr(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)?tI(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=Pn(t);return n[e]?os(n[e]):!1}return!1}var NI={};ge(NI,{Graph:()=>cu});function PI(t,e){if(t!==void 0&&!Dr(t))return t;if(Rc(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 MI(t){return Rc(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...yr(t.data.schema),title:t.data.name}}}var cu=class cy{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],...MI(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??Un(),a={id:s,data:e,name:PI(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 cy({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 ZT(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 qT(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 LI(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 zt.fromReadableStream(n)}function Jp(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}const jI=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function";function uu(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*Kp(t,e){for(;;){const{value:n,done:r}=Dt.runWithConfig(un(t),e.next.bind(e),!0);if(r)break;yield n}}async function*lu(t,e){const n=e[Symbol.asyncIterator]();for(;;){const{value:r,done:s}=await Dt.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 zn{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 du({bound:this,kwargs:{},config:{},maxAttemptNumber:t?.stopAfterAttempt,...t})}withConfig(t){return new wr({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 Zn({generator:this._streamIterator(t,n),config:n});return await r.setup,zt.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 bt(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(bt)),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 An(t,e)}async*_transformStreamWithConfig(t,e,n){let r,s=!0,a,i=!0;const o=we(n),c=await bt(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(j0);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 cu,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:qt(t)})}pick(t){return this.pipe(new Yp(t))}assign(t){return this.pipe(new hu(new br({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 Oc({...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"?LI(r):zt.fromAsyncGenerator(r)}async*_streamEventsV2(t,e,n){const r=new D0({...n,autoClose:!1}),s=we(e),a=s.runId??Un();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 Oc({...n,autoClose:!1,_schemaFormat:"streaming_events"}),l=new K0({...n}),d=this._streamLog(t,u,a);for await(const h of d){if(r?r=r.concat(h):r=kc.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 Rc(t)}withListeners({onStart:t,onEnd:e,onError:n}){return new wr({bound:this,config:{},configFactories:[r=>({callbacks:[new yf({config:r,onStart:t,onEnd:e,onError:n})]})]})}asTool(t){return BI(this,t)}},wr=class uy 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 du({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 zt.fromAsyncGenerator(a())}static isRunnableBinding(e){return e.bound&&Pe.isRunnable(e.bound)}withListeners({onStart:e,onEnd:n,onError:r}){return new uy({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[s=>({callbacks:[new yf({config:s,onStart:e,onEnd:n,onError:r})]})]})}},DI=class ly 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 ly({bound:this.bound.withListeners({onStart:e,onEnd:n,onError:r})})}},du=class extends wr{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 Cc(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 Cc(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 bt(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(bt)),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 bt(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 cu;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:qt(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:qt(e),middle:n.slice(0,-1).map(qt),last:qt(n[n.length-1])})}},br=class dy 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]=qt(r)}static from(e){return new dy({steps:e})}async invoke(e,n){const r=we(n),a=await(await bt(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=vc(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 Zn({generator:this.transform(r(),s),config:s});return await a.setup,zt.fromAsyncGenerator(a)}},zI=class hy extends Pe{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(e){if(super(e),!yc(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 bt(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(uu(s)){for await(const a of s)r?.signal?.throwIfAborted(),yield a;return}if(jI(s)){for(;;){r?.signal?.throwIfAborted();const a=s.next();if(a.done)break;yield a.value}return}yield s}static from(e){return new hy({func:e})}};function FI(t){if(yc(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn\'t happen.")}var Mn=class fy extends Pe{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(e){if(yc(e.func))return zI.from(e.func);super(e),FI(e.func),this.func=e.func}static from(e){return new fy({func:e})}async _invoke(e,n,r){return new Promise((s,a)=>{const i=Ae(n,{callbacks:r?.getChild(),recursionLimit:(n?.recursionLimit??bc)-1});Dt.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??bc)-1})}else if(uu(o)){let c;for await(const u of lu(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??bc)-1}),i=await new Promise((o,c)=>{Dt.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(uu(i))for await(const o of lu(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 Zn({generator:this.transform(r(),s),config:s});return await a.setup,zt.fromAsyncGenerator(a)}},UI=class extends br{},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 bt(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 Dt.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 bt(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=lu(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=>bt(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 qt(t){if(typeof t=="function")return new Mn({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]=qt(r);return new br({steps:e})}else throw new Error(`Expected a Runnable, function or object.\nInstead got an unsupported type.`)}var hu=class extends Pe{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(t){t instanceof br&&(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]=vc(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 Zn({generator:this.transform(n(),r),config:r});return await s.setup,zt.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 Zn({generator:this.transform(n(),r),config:r});return await s.setup,zt.fromAsyncGenerator(s)}},fu=class extends wr{name;description;schema;constructor(t){const e=Na.from([Mn.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 BI(t,e){const n=e.name??t.getName(),r=e.description??qc(e.schema);return Vc(e.schema)?new fu({name:n,description:r,schema:Ca({input:$a()}).transform(s=>s.input),bound:t}):new fu({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)}},ZI=class extends Qp{async transformDocuments(t){const e=[];for(const n of t){const r=await this._transformDocument(n);e.push(r)}return e}},qI={};ge(qI,{BaseDocumentTransformer:()=>Qp,Document:()=>Dn,MappingDocumentTransformer:()=>ZI});function VI(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 HI(t,e){let n=0;for(let r=0;r<t.length;r++)n+=t[r]*e[r];return n}function GI(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 WI(t,e){return Math.sqrt(GI(t,e))}var JI={};ge(JI,{cosineSimilarity:()=>pu,euclideanDistance:()=>YI,innerProduct:()=>XI,matrixFunc:()=>Pa,maximalMarginalRelevance:()=>em,normalize:()=>KI});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 KI(t,e=!1){const n=QI(t);return t.map(r=>r.map(s=>e?1-s/n:s/n))}function pu(t,e){return Pa(t,e,VI)}function XI(t,e){return Pa(t,e,HI)}function YI(t,e){return Pa(t,e,WI)}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=pu(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=pu(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 QI(t){return t.reduce((e,n)=>Math.max(e,tm(n).maxValue),0)}var eA={};ge(eA,{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 dt.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}}},tA={};ge(tA,{SaveableVectorStore:()=>nA,VectorStore:()=>mu,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)}},mu=class extends zn{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})}}},nA=class extends mu{static load(t,e){throw new Error("Not implemented")}},rA={};_y(rA,{MemoryVectorStore:()=>gu});var gu=class py extends mu{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(e,{similarity:n,...r}={}){super(e,r),this.similarity=n??yy}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 Dn({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 Dn({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 Dn({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 Dn({pageContent:e[i],metadata:o});a.push(c)}return py.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 _u(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const yu=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 W extends Error{}class Qe extends W{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:yu(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 St 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 W{constructor(){super("Could not parse response content as the length limit was reached")}}class fm extends W{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 sA=/^[a-z][a-z0-9+.-]*:/i,aA=t=>sA.test(t);let _t=t=>(_t=Array.isArray,_t(t)),pm=_t;function mm(t){return typeof t!="object"?{}:t??{}}function iA(t){if(!t)return!0;for(const e in t)return!1;return!0}function oA(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function za(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}const cA=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new W(`${t} must be an integer`);if(e<0)throw new W(`${t} must be a positive integer`);return e},uA=t=>{try{return JSON.parse(t)}catch{return}},us=t=>new Promise(e=>setTimeout(e,t)),vr="6.16.0",lA=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function dA(){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 hA=()=>{const t=dA();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":vr,"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":vr,"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":vr,"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=fA();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":vr,"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":vr,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function fA(){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 pA=()=>ym??(ym=hA());function mA(){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 gA(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 _A=({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},yA="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,wA=(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===yA&&(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 bA(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function xm(t,e){if(_t(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,_t(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:wA,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 vA(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"&&_t(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(vA(w)||bA(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"&&_t(w))m&&c&&(w=xm(w,c)),j=[{value:w.length>0?w.join(",")||null:void 0}];else if(_t(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&&_t(w)&&w.length===1?b+"[]":b;if(s&&_t(w)&&w.length===0)return oe+"[]";for(let ue=0;ue<j.length;++ue){const Y=j[ue],Be=typeof Y=="object"&&typeof Y.value<"u"?Y.value:w[Y];if(i&&Be===null)continue;const Ot=d&&o?Y.replace(/\\./g,"%2E"):Y,L=_t(w)?typeof n=="function"?n(oe,Ot):oe:oe+(d?"."+Ot:"["+Ot+"]");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&&_t(w)?null:c,u,l,d,f,h,p,m,y,R))}return N}function EA(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"||_t(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 SA(t,e={}){let n=t;const r=EA(e);let s,a;typeof r.filter=="function"?(a=r.filter,n=a("",n)):_t(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 TA(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 Tt,xt;class Fa{constructor(){Tt.set(this,void 0),xt.set(this,void 0),re(this,Tt,new Uint8Array),re(this,xt,null)}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Eu(e):e;re(this,Tt,TA([T(this,Tt,"f"),n]));const r=[];let s;for(;(s=xA(T(this,Tt,"f"),T(this,xt,"f")))!=null;){if(s.carriage&&T(this,xt,"f")==null){re(this,xt,s.index);continue}if(T(this,xt,"f")!=null&&(s.index!==T(this,xt,"f")+1||s.carriage)){r.push(Rm(T(this,Tt,"f").subarray(0,T(this,xt,"f")-1))),re(this,Tt,T(this,Tt,"f").subarray(T(this,xt,"f"))),re(this,xt,null);continue}const a=T(this,xt,"f")!==null?s.preceding-1:s.preceding,i=Rm(T(this,Tt,"f").subarray(0,a));r.push(i),re(this,Tt,T(this,Tt,"f").subarray(s.index)),re(this,xt,null)}return r}flush(){return T(this,Tt,"f").length?this.decode(`\n`):[]}}Tt=new WeakMap,xt=new WeakMap,Fa.NEWLINE_CHARS=new Set([`\n`,"\\r"]),Fa.NEWLINE_REGEXP=/\\r\\n|[\\n\\r]/g;function xA(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 IA(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 Ua={off:0,error:200,warn:300,info:400,debug:500},Nm=(t,e,n)=>{if(t){if(oA(Ua,t))return t;et(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(Ua))}`)}};function ls(){}function Ba(t,e,n){return!e||Ua[t]>Ua[n]?ls:e[t].bind(e)}const AA={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 AA;const r=Pm.get(e);if(r&&r[0]===n)return r[1];const s={error:Ba("error",e,n),warn:Ba("warn",e,n),info:Ba("info",e,n),debug:Ba("debug",e,n)};return Pm.set(e,[n,s]),s}const Jn=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 W("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(const c of kA(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(_u(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 Fa,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 W("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(_u(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*kA(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new W("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 W("Attempted to iterate over a response with no body");const n=new $A,r=new Fa,s=vm(t.body);for await(const a of OA(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*OA(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=IA(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class $A{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]=CA(e,":");return s.startsWith(" ")&&(s=s.substring(1)),n==="event"?this.event=s:n==="data"&&this.data.push(s),null}}function CA(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`,Jn({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 Za 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 Za(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 qa;class Su{constructor(e,n,r,s){qa.set(this,void 0),re(this,qa,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 W("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await T(this,qa,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(qa=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const n of e.getPaginatedItems())yield n}}class RA extends Za{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 Va 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 Ha 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 Ga(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,Kn=async(t,e)=>({...t,body:await Fm(t.body,e)}),zm=new WeakMap;function NA(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 NA(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,PA=t=>typeof t=="object"&&t!==null&&(t instanceof Response||Tu(t)||Um(t)),xu=t=>{if(PA(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()],Ga(n)));else if(Tu(n))t.append(e,fs([await new Response(bm(n)).blob()],Ga(n)));else if(Um(n))t.append(e,n,Ga(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",MA=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Bm(t),LA=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function jA(t,e,n){if(jm(),t=await t,MA(t))return t instanceof File?t:fs([await t.arrayBuffer()],t.name);if(LA(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=Ga(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}`:""}${DA(t)}`)}return e}function DA(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}class X{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 W(`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 X{list(e,n={},r){return this._client.getAPIList(O`/chat/completions/${e}/messages`,Ue,{query:n,...r})}};function Wa(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 zA(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=>UA(e,s))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?FA(e,r.message.content):null}}});return{...t,choices:n}}function FA(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 UA(t,e){const n=t.tools?.find(r=>Wa(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 BA(t,e){if(!t||!("tools"in t)||!t.tools)return!1;const n=t.tools?.find(r=>Wa(r)&&r.function?.name===e.function.name);return Wa(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 W(`Currently only \\`function\\` tool calls are supported; Received \\`${e.type}\\``)}function ZA(t){for(const e of t??[]){if(e.type!=="function")throw new W(`Currently only \\`function\\` tool types support auto-parsing; Received \\`${e.type}\\``);if(e.function.strict!==!0)throw new W(`The \\`${e.function.name}\\` tool is not marked with \\`strict: true\\`. Only strict function tools can be auto-parsed`)}}const Ja=t=>t?.role==="assistant",Wm=t=>t?.role==="tool";var $u,Ka,Xa,ms,gs,Ya,_s,pn,ys,Qa,ei,Er,Jm;class Cu{constructor(){$u.add(this),this.controller=new AbortController,Ka.set(this,void 0),Xa.set(this,()=>{}),ms.set(this,()=>{}),gs.set(this,void 0),Ya.set(this,()=>{}),_s.set(this,()=>{}),pn.set(this,{}),ys.set(this,!1),Qa.set(this,!1),ei.set(this,!1),Er.set(this,!1),re(this,Ka,new Promise((e,n)=>{re(this,Xa,e,"f"),re(this,ms,n,"f")})),re(this,gs,new Promise((e,n)=>{re(this,Ya,e,"f"),re(this,_s,n,"f")})),T(this,Ka,"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,Xa,"f").call(this),this._emit("connect"))}get ended(){return T(this,ys,"f")}get errored(){return T(this,Qa,"f")}get aborted(){return T(this,ei,"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,Er,!0),e!=="error"&&this.once("error",r),this.once(e,n)})}async done(){re(this,Er,!0),await T(this,gs,"f")}_emit(e,...n){if(T(this,ys,"f"))return;e==="end"&&(re(this,ys,!0),T(this,Ya,"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,Er,"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,Er,"f")&&!r?.length&&Promise.reject(s),T(this,ms,"f").call(this,s),T(this,_s,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Ka=new WeakMap,Xa=new WeakMap,ms=new WeakMap,gs=new WeakMap,Ya=new WeakMap,_s=new WeakMap,pn=new WeakMap,ys=new WeakMap,Qa=new WeakMap,ei=new WeakMap,Er=new WeakMap,$u=new WeakSet,Jm=function(e){if(re(this,Qa,!0),e instanceof Error&&e.name==="AbortError"&&(e=new St),e instanceof St)return re(this,ei,!0),this._emit("abort",e);if(e instanceof W)return this._emit("error",e);if(e instanceof Error){const n=new W(e.message);return n.cause=e,this._emit("error",n)}return this._emit("error",new W(String(e)))};function qA(t){return typeof t.parse=="function"}var ft,Ru,ti,Nu,Pu,Mu,Km,Xm;const VA=10;class Ym extends Cu{constructor(){super(...arguments),ft.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(Ja(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 W("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),T(this,ft,"m",Ru).call(this)}async finalMessage(){return await this.done(),T(this,ft,"m",ti).call(this)}async finalFunctionToolCall(){return await this.done(),T(this,ft,"m",Nu).call(this)}async finalFunctionToolCallResult(){return await this.done(),T(this,ft,"m",Pu).call(this)}async totalUsage(){return await this.done(),T(this,ft,"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,ft,"m",ti).call(this);n&&this._emit("finalMessage",n);const r=T(this,ft,"m",Ru).call(this);r&&this._emit("finalContent",r);const s=T(this,ft,"m",Nu).call(this);s&&this._emit("finalFunctionToolCall",s);const a=T(this,ft,"m",Pu).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",T(this,ft,"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,ft,"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=VA}=r||{},l=n.tools.map(h=>{if(ps(h)){if(!h.$callback)throw new W("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 W("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=qA(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,ft,"m",Xm).call(this,N);if(this._addMessage({role:s,tool_call_id:v,content:j}),c)return}}}}ft=new WeakSet,Ru=function(){return T(this,ft,"m",ti).call(this).content??null},ti=function(){let e=this.messages.length;for(;e-- >0;){const n=this.messages[e];if(Ja(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new W("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(Ja(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 W("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),Ja(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,HA=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:HA};class GA extends Error{}class WA extends Error{}function JA(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 KA(t.trim(),e)}const KA=(t,e)=>{const n=t.length;let r=0;const s=f=>{throw new GA(`${f} at position ${r}`)},a=f=>{throw new WA(`${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=>JA(t,Ke.ALL^Ke.NUM);var We,mn,Sr,Ln,ju,ni,Du,zu,Fu,ri,Uu,fg;class ws extends Ym{constructor(e){super(),We.add(this),mn.set(this,void 0),Sr.set(this,void 0),Ln.set(this,void 0),re(this,mn,e),re(this,Sr,[])}get currentChatCompletionSnapshot(){return T(this,Ln,"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 St;return this._addChatCompletion(T(this,We,"m",ri).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",ri).call(this)),T(this,We,"m",Du).call(this,i),a=i.id;if(s.controller.signal?.aborted)throw new St;return this._addChatCompletion(T(this,We,"m",ri).call(this))}[(mn=new WeakMap,Sr=new WeakMap,Ln=new WeakMap,We=new WeakSet,ju=function(){this.ended||re(this,Ln,void 0)},ni=function(n){let r=T(this,Sr,"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,Sr,"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",ni).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",ni).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=>Wa(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",ni).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}))},ri=function(){if(this.ended)throw new W("stream has ended, this shouldn\'t happen");const n=T(this,Ln,"f");if(!n)throw new W("request ended without sending any chunks");return re(this,Ln,void 0),re(this,Sr,[]),XA(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,Ln,"f");const{choices:c,...u}=n;o?Object.assign(o,u):o=re(this,Ln,{...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 Y=(i=m.message.tool_calls)[N]??(i[N]={});Object.assign(Y,ue),j&&(Y.id=j),b&&(Y.type=b),oe&&(Y.function??(Y.function={name:oe.name??"",arguments:""})),oe?.name&&(Y.function.name=oe.name),oe?.arguments&&(Y.function.arguments+=oe.arguments,BA(T(this,mn,"f"),Y)&&(Y.function.parsed_arguments=hg(Y.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 XA(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 W(`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 W(`missing role for choice ${d}`);if(m){const{arguments:E,name:x}=m;if(E==null)throw new W(`missing function_call.arguments for choice ${d}`);if(!x)throw new W(`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,...Y}=A||{};if(j==null)throw new W(`missing choices[${d}].tool_calls[${x}].id\n${si(t)}`);if(N==null)throw new W(`missing choices[${d}].tool_calls[${x}].type\n${si(t)}`);if(ue==null)throw new W(`missing choices[${d}].tool_calls[${x}].function.name\n${si(t)}`);if(oe==null)throw new W(`missing choices[${d}].tool_calls[${x}].function.arguments\n${si(t)}`);return{...b,id:j,type:N,function:{...Y,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 zA(c,e)}function si(t){return JSON.stringify(t)}function iC(t){}class ai extends ws{static fromReadableStream(e){const n=new ai(null);return n._run(()=>n._fromReadableStream(e)),n}static runTools(e,n,r){const s=new ai(n),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,n,a)),s}}let Bu=class extends X{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 ZA(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?ai.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 X{constructor(){super(...arguments),this.completions=new Bu(this._client)}}Zu.Completions=Bu;const pg=Symbol("brand.privateNullableHeaders");function*YA(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 YA(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 X{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 X{create(e,n){return this._client.post("/audio/transcriptions",Kn({body:e,...n,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class _g extends X{create(e,n){return this._client.post("/audio/translations",Kn({body:e,...n,__metadata:{model:e.model}},this._client))}}class bs extends X{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 X{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 X{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 X{create(e,n){return this._client.post("/realtime/sessions",{body:e,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};class vg extends X{create(e,n){return this._client.post("/realtime/transcription_sessions",{body:e,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}}let ii=class extends X{constructor(){super(...arguments),this.sessions=new bg(this._client),this.transcriptionSessions=new vg(this._client)}};ii.Sessions=bg,ii.TranscriptionSessions=vg;class Eg extends X{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 X{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",Ha,{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`,Ha,{query:n,...r,headers:U([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}};class oi extends X{constructor(){super(...arguments),this.sessions=new Eg(this._client),this.threads=new Sg(this._client)}}oi.Sessions=Eg,oi.Threads=Sg;class Tg extends X{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 X{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 QA=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))}},gn=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,Xn,qu,nn,ci,Vt,Yn,Tr,Qn,ui,It,li,di,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,{}),ci.set(this,{}),Vt.set(this,void 0),Yn.set(this,void 0),Tr.set(this,void 0),Qn.set(this,void 0),ui.set(this,void 0),It.set(this,void 0),li.set(this,void 0),di.set(this,void 0),vs.set(this,void 0)}[(qu=new WeakMap,nn=new WeakMap,ci=new WeakMap,Vt=new WeakMap,Yn=new WeakMap,Tr=new WeakMap,Qn=new WeakMap,ui=new WeakMap,It=new WeakMap,li=new WeakMap,di=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 Xn;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 St;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 Xn;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 St;return this._addRun(T(this,tt,"m",Ss).call(this))}static createThreadAssistantStream(e,n,r){const s=new Xn;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 Xn;return a._run(()=>a._runAssistantStream(e,n,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return T(this,li,"f")}currentRun(){return T(this,di,"f")}currentMessageSnapshot(){return T(this,Vt,"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,ci,"f"))}async finalRun(){if(await this.done(),!T(this,Yn,"f"))throw Error("Final run was not received.");return T(this,Yn,"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 St;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 St;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(za(a)&&za(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(!za(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)}}Xn=Ts,Es=function(e){if(!this.ended)switch(re(this,li,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 W("stream has ended, this shouldn\'t happen");if(!T(this,Yn,"f"))throw Error("Final run has not been received");return T(this,Yn,"f")},Ig=function(e){const[n,r]=T(this,tt,"m",$g).call(this,e,T(this,Vt,"f"));re(this,Vt,n),T(this,ci,"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,Qn,"f"))switch(T(this,Qn,"f").type){case"text":this._emit("textDone",T(this,Qn,"f").text,T(this,Vt,"f"));break;case"image_file":this._emit("imageFileDone",T(this,Qn,"f").image_file,T(this,Vt,"f"));break}re(this,Tr,s.index)}re(this,Qn,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,Vt,"f"));break;case"text":this._emit("textDone",s.text,T(this,Vt,"f"));break}}T(this,Vt,"f")&&this._emit("messageDone",e.data),re(this,Vt,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,ui,"f")?this._emit("toolCallDelta",a,n.step_details.tool_calls[a.index]):(T(this,It,"f")&&this._emit("toolCallDone",T(this,It,"f")),re(this,ui,a.index),re(this,It,n.step_details.tool_calls[a.index]),T(this,It,"f")&&this._emit("toolCallCreated",T(this,It,"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,It,"f")&&(this._emit("toolCallDone",T(this,It,"f")),re(this,It,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=Xn.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 Xn.accumulateDelta(n,e)},Rg=function(e){switch(re(this,di,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,Yn,e.data),T(this,It,"f")&&(this._emit("toolCallDone",T(this,It,"f")),re(this,It,void 0));break}};let Vu=class extends X{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 hi extends X{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)}}hi.Runs=Vu,hi.Messages=Tg;class xr extends X{constructor(){super(...arguments),this.realtime=new ii(this._client),this.chatkit=new oi(this._client),this.assistants=new wg(this._client),this.threads=new hi(this._client)}}xr.Realtime=ii,xr.ChatKit=oi,xr.Assistants=wg,xr.Threads=hi;class Ng extends X{create(e,n){return this._client.post("/completions",{body:e,...n,stream:e.stream??!1})}}class Pg extends X{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 X{constructor(){super(...arguments),this.content=new Pg(this._client)}create(e,n,r){return this._client.post(O`/containers/${e}/files`,Kn({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 X{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 X{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`,Ha,{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 X{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 X{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=QA(c)}),i)))}};class jg extends X{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 X{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 X{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 X{create(e,n){return this._client.post("/files",Kn({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 X{}let Fg=class extends X{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 X{constructor(){super(...arguments),this.graders=new Fg(this._client)}}Xu.Graders=Fg;class Ug extends X{create(e,n,r){return this._client.getAPIList(O`/fine_tuning/checkpoints/${e}/permissions`,Va,{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 X{constructor(){super(...arguments),this.permissions=new Ug(this._client)}};Yu.Permissions=Ug;class Bg extends X{list(e,n={},r){return this._client.getAPIList(O`/fine_tuning/jobs/${e}/checkpoints`,Ue,{query:n,...r})}}class Qu extends X{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 X{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 X{}class el extends X{constructor(){super(...arguments),this.graderModels=new Zg(this._client)}}el.GraderModels=Zg;class qg extends X{createVariation(e,n){return this._client.post("/images/variations",Kn({body:e,...n},this._client))}edit(e,n){return this._client.post("/images/edits",Kn({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 X{retrieve(e,n){return this._client.get(O`/models/${e}`,n)}list(e){return this._client.getAPIList("/models",Va,e)}delete(e,n){return this._client.delete(O`/models/${e}`,n)}}class Hg extends X{create(e,n){return this._client.post("/moderations",{body:e,...n})}}class Gg extends X{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 X{create(e,n){return this._client.post("/realtime/client_secrets",{body:e,...n})}}class fi extends X{constructor(){super(...arguments),this.clientSecrets=new Wg(this._client),this.calls=new Gg(this._client)}}fi.ClientSecrets=Wg,fi.Calls=Gg;function ek(t,e){return!e||!nk(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:ak(e,s)};if(s.type==="message"){const a=s.content.map(i=>i.type==="output_text"?{...i,parsed:tk(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 tk(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function nk(t){return!!ku(t.text?.format)}function rk(t){return t?.$brand==="auto-parseable-tool"}function sk(t,e){return t.find(n=>n.type==="function"&&n.name===e)}function ak(t,e){const n=sk(t.tools??[],e.name);return{...e,...e,parsed_arguments:rk(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,pi,jn,mi,Kg,Xg,Yg,Qg;class nl extends Cu{constructor(e){super(),Ar.add(this),pi.set(this,void 0),jn.set(this,void 0),mi.set(this,void 0),re(this,pi,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 St;return T(this,Ar,"m",Yg).call(this)}[(pi=new WeakMap,jn=new WeakMap,mi=new WeakMap,Ar=new WeakSet,Kg=function(){this.ended||re(this,jn,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 W(`missing output at index ${n.output_index}`);if(i.type==="message"){const o=i.content[n.content_index];if(!o)throw new W(`missing content at index ${n.content_index}`);if(o.type!=="output_text")throw new W(`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 W(`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 W("stream has ended, this shouldn\'t happen");const n=T(this,jn,"f");if(!n)throw new W("request ended without sending any events");re(this,jn,void 0);const r=ik(n,T(this,pi,"f"));return re(this,mi,r),r},Qg=function(n){let r=T(this,jn,"f");if(!r){if(n.type!=="response.created")throw new W(`When snapshot hasn\'t been set yet, expected \'response.created\' event, got ${n.type}`);return r=re(this,jn,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 W(`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 W(`missing output at index ${n.output_index}`);if(s.type==="message"){const a=s.content[n.content_index];if(!a)throw new W(`missing content at index ${n.content_index}`);if(a.type!=="output_text")throw new W(`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 W(`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 W(`missing output at index ${n.output_index}`);if(s.type==="reasoning"){const a=s.content?.[n.content_index];if(!a)throw new W(`missing content at index ${n.content_index}`);if(a.type!=="reasoning_text")throw new W(`expected content to be \'reasoning_text\', got ${a.type}`);a.text+=n.delta}break}case"response.completed":{re(this,jn,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,mi,"f");if(!e)throw new W("stream ended without producing a ChatCompletion");return e}}function ik(t,e){return ek(t,e)}class e_ extends X{list(e,n={},r){return this._client.getAPIList(O`/responses/${e}/input_items`,Ue,{query:n,...r})}}class t_ extends X{count(e={},n){return this._client.post("/responses/input_tokens",{body:e,...n})}}class gi extends X{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})}}gi.InputItems=e_,gi.InputTokens=t_;class n_ extends X{create(e,n,r){return this._client.post(O`/uploads/${e}/parts`,Kn({body:n,...r},this._client))}}class rl extends X{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 ok=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 X{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 ok(d),await this.createAndPoll(e,{file_ids:u})}}class s_ extends X{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`,Va,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class _i extends X{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`,Va,{body:n,method:"post",...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}_i.Files=s_,_i.FileBatches=r_;class a_ extends X{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",Ha,{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_,yi;class o_ extends X{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",yi).call(this,a,"webhook-signature"),o=T(this,kr,"m",yi).call(this,a,"webhook-timestamp"),c=T(this,kr,"m",yi).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")},yi=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,wi,c_;class pe{constructor({baseURL:e=gn("OPENAI_BASE_URL"),apiKey:n=gn("OPENAI_API_KEY"),organization:r=gn("OPENAI_ORG_ID")??null,project:s=gn("OPENAI_PROJECT_ID")??null,webhookSecret:a=gn("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(sl.add(this),wi.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 _i(this),this.webhooks=new o_(this),this.beta=new xr(this),this.batches=new yg(this),this.uploads=new rl(this),this.responses=new gi(this),this.realtime=new fi(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 W("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&&lA())throw new W(`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(gn("OPENAI_LOG"),"process.env[\'OPENAI_LOG\']",this)??c,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??mA(),re(this,wi,_A),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 SA(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${vr}`}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 W?r:new W(`Failed to get token from \'apiKey\' function: ${r.message}`,{cause:r})}if(typeof n!="string"||!n)throw new W(`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=aA(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return iA(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 Za(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`,Jn({retryOfRequestLogID:r,method:s.method,url:o,options:s,headers:i.headers})),s.signal?.aborted)throw new St;const f=new AbortController,h=await this.fetchWithTimeout(o,i,c,f).catch(yu),p=Date.now();if(h instanceof globalThis.Error){const v=`retrying, ${n} attempts remaining`;if(s.signal?.aborted)throw new St;const w=_u(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})`,Jn({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)`,Jn({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 gA(h.body),et(this).info(`${y} - ${j}`),et(this).debug(`[${u}] response error (${j})`,Jn({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=>yu(j).message),x=uA(E),A=x?void 0:E;throw et(this).debug(`[${u}] response error (${w})`,Jn({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`,Jn({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 RA(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&&cA("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))}:{},...pA(),"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,wi,"f").call(this,{body:e,headers:r})}}al=pe,wi=new WeakMap,sl=new WeakSet,c_=function(){return this.baseURL!=="https://api.openai.com/v1"},pe.OpenAI=al,pe.DEFAULT_TIMEOUT=6e5,pe.OpenAIError=W,pe.APIError=Qe,pe.APIConnectionError=ja,pe.APIConnectionTimeoutError=Da,pe.APIUserAbortError=St,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=jA,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=_i,pe.Webhooks=o_,pe.Beta=xr,pe.Batches=yg,pe.Uploads=rl,pe.Responses=gi,pe.Realtime=fi,pe.Conversations=Wu,pe.Evals=Ku,pe.Containers=Gu,pe.Videos=a_;class ck extends pe{constructor({baseURL:e=gn("OPENAI_BASE_URL"),apiKey:n=gn("AZURE_OPENAI_API_KEY"),apiVersion:r=gn("OPENAI_API_VERSION"),endpoint:s,deployment:a,azureADTokenProvider:i,dangerouslyAllowBrowser:o,...c}={}){if(!r)throw new W("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: \'My API Version\' }).");if(typeof i=="function"&&(o=!0),!i&&!n)throw new W("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(i&&n)throw new W("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(c.defaultQuery={...c.defaultQuery,"api-version":r},e){if(s)throw new W("baseURL and endpoint are mutually exclusive")}else{if(s||(s=process.env.AZURE_OPENAI_ENDPOINT),!s)throw new W("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${s}/openai`}super({apiKey:i??n,baseURL:e,...c,...o!==void 0?{dangerouslyAllowBrowser:o}:{}}),this.apiVersion="",this.apiVersion=r,this.deploymentName=a}async buildRequest(e,n={}){if(uk.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!za(e.body))throw new Error("Expected request body to be an object");const r=this.deploymentName||e.body.model||e.__metadata?.model;r!==void 0&&!this.baseURL.includes("/deployments")&&(e.path=`/deployments/${r}${e.path}`)}return super.buildRequest(e,n)}async authHeaders(e){return typeof this._options.apiKey=="string"?U([{"api-key":this.apiKey}]):super.authHeaders(e)}}const uk=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);function u_(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===St.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 bi=(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 lk(t,e){return Array.isArray(t)?l_(t,e):Mn.from(n=>l_(n,t))}function l_(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&&bi(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&&bi(u,s)||i&&u.id&&i.some(l=>l===u.id))&&c.push(u):c.push(u)}return c}function dk(t){return Array.isArray(t)?d_(t):Mn.from(d_)}function d_(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(pk(o))}}return e}function hk(t,e){if(Array.isArray(t)){const n=t;if(!e)throw new Error("Options parameter is required when providing messages.");return h_(n,e)}else{const n=t;return Mn.from(r=>h_(r,n)).withConfig({runName:"trim_messages"})}}async function h_(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=m_;if(u&&("splitText"in u?d=u.splitText:d=async f=>u(f)),s==="first")return f_(t,{maxTokens:n,tokenCounter:l,textSplitter:d,partialStrategy:a?"first":void 0,endOn:i});if(s==="last")return fk(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 f_(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&&!bi(o[c-1],u);)c-=1}return o.slice(0,c)}async function fk(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,Zi(l))});if(s){const l=Array.isArray(s)?s:[s];for(;o.length>0&&!bi(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 f_(u,{...i,partialStrategy:n?"last":void 0,endOn:a}),c?[u[0],...u.slice(1).reverse()]:u.reverse()}const p_={human:{message:an,messageChunk:Zs},ai:{message:on,messageChunk:Fn},system:{message:En,messageChunk:rr},developer:{message:En,messageChunk:rr},tool:{message:vn,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 Fn(a)}else s=new on(e);break;case"system":n?r=new rr(e):s=new En(e);break;case"developer":n?r=new rr({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}}):s=new En({...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 vn(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 pk(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 p_&&(n=il(e,r)),!n)throw new Error(`Unrecognized message chunk class ${e}. Supported classes are ${Object.keys(p_)}`);return n}function m_(t){const e=t.split(`\n`);return Promise.resolve([...e.slice(0,-1).map(n=>`${n}\n`),e[e.length-1]])}const mk=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"],gk=["image","video","audio","text-plain","file"],_k=["text","reasoning",...mk,...gk];var yk={};ge(yk,{AIMessage:()=>on,AIMessageChunk:()=>Fn,BaseMessage:()=>sn,BaseMessageChunk:()=>wn,ChatMessage:()=>Lr,ChatMessageChunk:()=>Fs,DEFAULT_MERGE_IGNORE_KEYS:()=>Ul,FunctionMessage:()=>Us,FunctionMessageChunk:()=>Bs,HumanMessage:()=>an,HumanMessageChunk:()=>Zs,KNOWN_BLOCK_TYPES:()=>_k,RemoveMessage:()=>qs,SystemMessage:()=>En,SystemMessageChunk:()=>rr,ToolMessage:()=>vn,ToolMessageChunk:()=>Ds,_isMessageFieldWithRole:()=>Zl,_mergeDicts:()=>rt,_mergeLists:()=>Mr,_mergeObj:()=>Bl,_mergeStatus:()=>Fl,coerceMessageLikeToMessage:()=>jr,collapseToolCallChunks:()=>rd,convertToChunk:()=>Vs,convertToOpenAIImageBlock:()=>Pl,convertToProviderContentBlock:()=>Ly,defaultTextSplitter:()=>m_,defaultToolCallParser:()=>Vi,filterMessages:()=>lk,getBufferString:()=>Yi,iife:()=>Ew,isAIMessage:()=>Ji,isAIMessageChunk:()=>Ki,isBase64ContentBlock:()=>Di,isBaseMessage:()=>bn,isBaseMessageChunk:()=>Zi,isChatMessage:()=>nw,isChatMessageChunk:()=>rw,isDataContentBlock:()=>yn,isDirectToolOutput:()=>qi,isFunctionMessage:()=>sw,isFunctionMessageChunk:()=>aw,isHumanMessage:()=>iw,isHumanMessageChunk:()=>ow,isIDContentBlock:()=>Nl,isMessage:()=>zl,isOpenAIToolCallArray:()=>Qy,isPlainTextContentBlock:()=>Py,isSystemMessage:()=>cw,isSystemMessageChunk:()=>uw,isToolMessage:()=>ql,isToolMessageChunk:()=>Vl,isURLContentBlock:()=>ji,mapChatMessagesToStoredMessages:()=>Aw,mapStoredMessageToChatMessage:()=>Qi,mapStoredMessagesToChatMessages:()=>Iw,mergeContent:()=>rn,mergeMessageRuns:()=>dk,mergeResponseMetadata:()=>td,mergeUsageMetadata:()=>Wi,parseBase64DataUrl:()=>zi,parseMimeType:()=>My,trimMessages:()=>hk});const wk=t=>t();function g_(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 __(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function bk(t){const e=wk(()=>{if(__(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&__(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 vk(){let t=eo();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function y_(t,e=!1,n="1.0.0"){const r=bk(t),s=vk(),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&&(hr(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 Ek={};ge(Ek,{convertToOpenAIFunction:()=>w_,convertToOpenAITool:()=>Sk,isLangChainTool:()=>ll,isRunnableToolLike:()=>cl,isStructuredTool:()=>ol,isStructuredToolParams:()=>ul});function w_(t,e){const n=typeof e=="number"?void 0:e;return{name:t.name,description:t.description,parameters:yr(t.schema),...n?.strict!==void 0?{strict:n.strict}:{}}}function Sk(t,e){const n=typeof e=="number"?void 0:e;let r;return ll(t)?r={type:"function",function:w_(t)}:r=t,n?.strict!==void 0&&(r.function.strict=n.strict),r}var Tk={};ge(Tk,{extendInteropZodObject:()=>MT,getInteropZodDefaultGetter:()=>jT,getInteropZodObjectShape:()=>Gc,getSchemaDescription:()=>qc,interopParse:()=>RT,interopParseAsync:()=>Ea,interopSafeParse:()=>CT,interopSafeParseAsync:()=>dp,interopZodObjectMakeFieldsOptional:()=>FT,interopZodObjectPartial:()=>LT,interopZodObjectPassthrough:()=>Wc,interopZodObjectStrict:()=>Ta,interopZodTransformInputSchema:()=>pp,isInteropZodError:()=>mp,isInteropZodLiteral:()=>$T,isInteropZodObject:()=>PT,isInteropZodSchema:()=>hr,isShapelessZodSchema:()=>NT,isSimpleStringZodSchema:()=>Vc,isZodArrayV4:()=>Sa,isZodLiteralV3:()=>up,isZodLiteralV4:()=>lp,isZodNullableV4:()=>fp,isZodObjectV3:()=>Hc,isZodObjectV4:()=>Yt,isZodOptionalV4:()=>hp,isZodSchema:()=>OT,isZodSchemaV3:()=>Ve,isZodSchemaV4:()=>Ne});const xk=I("ZodISODateTime",(t,e)=>{dS.init(t,e),Me.init(t,e)});function Ik(t){return dT(xk,t)}const Ak=I("ZodISODate",(t,e)=>{hS.init(t,e),Me.init(t,e)});function kk(t){return hT(Ak,t)}const Ok=I("ZodISOTime",(t,e)=>{fS.init(t,e),Me.init(t,e)});function $k(t){return fT(Ok,t)}const Ck=I("ZodISODuration",(t,e)=>{pS.init(t,e),Me.init(t,e)});function Rk(t){return pT(Ck,t)}const vi=I("ZodError",(t,e)=>{xf.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>uE(t,n)},flatten:{value:n=>cE(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}),Nk=If(vi),Pk=Af(vi),Mk=Of(vi),Lk=$f(vi),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)=>at(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>Nk(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Mk(t,n,r),t.parseAsync=async(n,r)=>Pk(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Lk(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(OO(n,r)),t.superRefine=n=>t.check($O(n)),t.overwrite=n=>t.check(rs(n)),t.optional=()=>A_(t),t.nullable=()=>k_(t),t.nullish=()=>A_(k_(t)),t.nonoptional=n=>vO(t,n),t.array=()=>xs(t),t.or=n=>oO([t,n]),t.and=n=>lO(t,n),t.transform=n=>$_(t,mO(n)),t.default=n=>yO(t,n),t.prefault=n=>bO(t,n),t.catch=n=>SO(t,n),t.pipe=n=>$_(t,n),t.readonly=()=>IO(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)),b_=I("_ZodString",(t,e)=>{zc.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(_T(...r)),t.includes=(...r)=>t.check(bT(...r)),t.startsWith=(...r)=>t.check(vT(...r)),t.endsWith=(...r)=>t.check(ET(...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(yT(r)),t.uppercase=r=>t.check(wT(r)),t.trim=()=>t.check(TT()),t.normalize=(...r)=>t.check(ST(...r)),t.toLowerCase=()=>t.check(xT()),t.toUpperCase=()=>t.check(IT())}),jk=I("ZodString",(t,e)=>{zc.init(t,e),b_.init(t,e),t.email=n=>t.check(qS(Dk,n)),t.url=n=>t.check(JS(zk,n)),t.jwt=n=>t.check(lT(eO,n)),t.emoji=n=>t.check(KS(Fk,n)),t.guid=n=>t.check(Qf(v_,n)),t.uuid=n=>t.check(VS(Ei,n)),t.uuidv4=n=>t.check(HS(Ei,n)),t.uuidv6=n=>t.check(GS(Ei,n)),t.uuidv7=n=>t.check(WS(Ei,n)),t.nanoid=n=>t.check(XS(Uk,n)),t.guid=n=>t.check(Qf(v_,n)),t.cuid=n=>t.check(YS(Bk,n)),t.cuid2=n=>t.check(QS(Zk,n)),t.ulid=n=>t.check(eT(qk,n)),t.base64=n=>t.check(oT(Xk,n)),t.base64url=n=>t.check(cT(Yk,n)),t.xid=n=>t.check(tT(Vk,n)),t.ksuid=n=>t.check(nT(Hk,n)),t.ipv4=n=>t.check(rT(Gk,n)),t.ipv6=n=>t.check(sT(Wk,n)),t.cidrv4=n=>t.check(aT(Jk,n)),t.cidrv6=n=>t.check(iT(Kk,n)),t.e164=n=>t.check(uT(Qk,n)),t.datetime=n=>t.check(Ik(n)),t.date=n=>t.check(kk(n)),t.time=n=>t.check($k(n)),t.duration=n=>t.check(Rk(n))});function At(t){return ZS(jk,t)}const Me=I("ZodStringFormat",(t,e)=>{$e.init(t,e),b_.init(t,e)}),Dk=I("ZodEmail",(t,e)=>{nS.init(t,e),Me.init(t,e)}),v_=I("ZodGUID",(t,e)=>{eS.init(t,e),Me.init(t,e)}),Ei=I("ZodUUID",(t,e)=>{tS.init(t,e),Me.init(t,e)}),zk=I("ZodURL",(t,e)=>{rS.init(t,e),Me.init(t,e)}),Fk=I("ZodEmoji",(t,e)=>{sS.init(t,e),Me.init(t,e)}),Uk=I("ZodNanoID",(t,e)=>{aS.init(t,e),Me.init(t,e)}),Bk=I("ZodCUID",(t,e)=>{iS.init(t,e),Me.init(t,e)}),Zk=I("ZodCUID2",(t,e)=>{oS.init(t,e),Me.init(t,e)}),qk=I("ZodULID",(t,e)=>{cS.init(t,e),Me.init(t,e)}),Vk=I("ZodXID",(t,e)=>{uS.init(t,e),Me.init(t,e)}),Hk=I("ZodKSUID",(t,e)=>{lS.init(t,e),Me.init(t,e)}),Gk=I("ZodIPv4",(t,e)=>{mS.init(t,e),Me.init(t,e)}),Wk=I("ZodIPv6",(t,e)=>{gS.init(t,e),Me.init(t,e)}),Jk=I("ZodCIDRv4",(t,e)=>{_S.init(t,e),Me.init(t,e)}),Kk=I("ZodCIDRv6",(t,e)=>{yS.init(t,e),Me.init(t,e)}),Xk=I("ZodBase64",(t,e)=>{wS.init(t,e),Me.init(t,e)}),Yk=I("ZodBase64URL",(t,e)=>{vS.init(t,e),Me.init(t,e)}),Qk=I("ZodE164",(t,e)=>{ES.init(t,e),Me.init(t,e)}),eO=I("ZodJWT",(t,e)=>{TS.init(t,e),Me.init(t,e)}),E_=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(Zc(r,s)),t.min=(r,s)=>t.check(Zc(r,s)),t.lt=(r,s)=>t.check(np(r,s)),t.lte=(r,s)=>t.check(Bc(r,s)),t.max=(r,s)=>t.check(Bc(r,s)),t.int=r=>t.check(S_(r)),t.safe=r=>t.check(S_(r)),t.positive=r=>t.check(rp(0,r)),t.nonnegative=r=>t.check(Zc(0,r)),t.negative=r=>t.check(np(0,r)),t.nonpositive=r=>t.check(Bc(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 it(t){return mT(E_,t)}const tO=I("ZodNumberFormat",(t,e)=>{xS.init(t,e),E_.init(t,e)});function S_(t){return gT(tO,t)}const nO=I("ZodUnknown",(t,e)=>{Ff.init(t,e),De.init(t,e)});function T_(){return ep(nO)}const rO=I("ZodNever",(t,e)=>{Uf.init(t,e),De.init(t,e)});function sO(t){return tp(rO,t)}const aO=I("ZodArray",(t,e)=>{IS.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 AT(aO,t,e)}const iO=I("ZodObject",(t,e)=>{AS.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:T_()}),t.loose=()=>t.clone({...t._zod.def,catchall:T_()}),t.strict=()=>t.clone({...t._zod.def,catchall:sO()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>Ef(t,n),t.merge=n=>iE(t,n),t.pick=n=>sE(t,n),t.omit=n=>aE(t,n),t.partial=(...n)=>Sf(I_,t,n[0]),t.required=(...n)=>oE(O_,t,n[0])});function ot(t,e){const n={type:"object",get shape(){return Lc(this,"shape",{...t}),this.shape},...ee(e)};return new iO(n)}const x_=I("ZodUnion",(t,e)=>{Vf.init(t,e),De.init(t,e),t.options=e.options});function oO(t,e){return new x_({type:"union",options:t,...ee(e)})}const cO=I("ZodDiscriminatedUnion",(t,e)=>{x_.init(t,e),kS.init(t,e)});function dl(t,e,n){return new cO({type:"union",options:e,discriminator:t,...ee(n)})}const uO=I("ZodIntersection",(t,e)=>{OS.init(t,e),De.init(t,e)});function lO(t,e){return new uO({type:"intersection",left:t,right:e})}const dO=I("ZodRecord",(t,e)=>{$S.init(t,e),De.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function hO(t,e,n){return new dO({type:"record",keyType:t,valueType:e,...ee(n)})}const hl=I("ZodEnum",(t,e)=>{CS.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:[],...ee(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:[],...ee(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,...ee(e)})}const fO=I("ZodLiteral",(t,e)=>{RS.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 kt(t,e){return new fO({type:"literal",values:Array.isArray(t)?t:[t],...ee(e)})}const pO=I("ZodTransform",(t,e)=>{NS.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 mO(t){return new pO({type:"transform",transform:t})}const I_=I("ZodOptional",(t,e)=>{Uc.init(t,e),De.init(t,e),t.unwrap=()=>t._zod.def.innerType});function A_(t){return new I_({type:"optional",innerType:t})}const gO=I("ZodNullable",(t,e)=>{PS.init(t,e),De.init(t,e),t.unwrap=()=>t._zod.def.innerType});function k_(t){return new gO({type:"nullable",innerType:t})}const _O=I("ZodDefault",(t,e)=>{MS.init(t,e),De.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function yO(t,e){return new _O({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const wO=I("ZodPrefault",(t,e)=>{LS.init(t,e),De.init(t,e),t.unwrap=()=>t._zod.def.innerType});function bO(t,e){return new wO({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const O_=I("ZodNonOptional",(t,e)=>{jS.init(t,e),De.init(t,e),t.unwrap=()=>t._zod.def.innerType});function vO(t,e){return new O_({type:"nonoptional",innerType:t,...ee(e)})}const EO=I("ZodCatch",(t,e)=>{DS.init(t,e),De.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function SO(t,e){return new EO({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const TO=I("ZodPipe",(t,e)=>{zS.init(t,e),De.init(t,e),t.in=e.in,t.out=e.out});function $_(t,e){return new TO({type:"pipe",in:t,out:e})}const xO=I("ZodReadonly",(t,e)=>{FS.init(t,e),De.init(t,e)});function IO(t){return new xO({type:"readonly",innerType:t})}const AO=I("ZodCustom",(t,e)=>{US.init(t,e),De.init(t,e)});function kO(t){const e=new gt({check:"custom"});return e._zod.check=t,e}function OO(t,e={}){return kT(AO,t,e)}function $O(t){const e=kO(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 CO={};ge(CO,{BasePromptValue:()=>Si,ChatPromptValue:()=>R_,ImagePromptValue:()=>RO,StringPromptValue:()=>C_});var Si=class extends zn{},C_=class extends Si{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)]}},R_=class extends Si{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 Yi(this.messages)}toChatMessages(){return this.messages}},RO=class extends Si{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(""),NO=[-2147483648,8388608,32768,128],Ht=[24,16,8,0],Ti=[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 Gt(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}Gt.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]<<Ht[a++&3];else for(a=this.start;s<i&&a<64;++s)r=t.charCodeAt(s),r<128?o[a>>>2]|=r<<Ht[a++&3]:r<2048?(o[a>>>2]|=(192|r>>>6)<<Ht[a++&3],o[a>>>2]|=(128|r&63)<<Ht[a++&3]):r<55296||r>=57344?(o[a>>>2]|=(224|r>>>12)<<Ht[a++&3],o[a>>>2]|=(128|r>>>6&63)<<Ht[a++&3],o[a>>>2]|=(128|r&63)<<Ht[a++&3]):(r=65536+((r&1023)<<10|t.charCodeAt(++s)&1023),o[a>>>2]|=(240|r>>>18)<<Ht[a++&3],o[a>>>2]|=(128|r>>>12&63)<<Ht[a++&3],o[a>>>2]|=(128|r>>>6&63)<<Ht[a++&3],o[a>>>2]|=(128|r&63)<<Ht[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}},Gt.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=NO[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()}},Gt.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+Ti[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+Ti[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+Ti[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+Ti[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},Gt.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},Gt.prototype.toString=Gt.prototype.hex,Gt.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},Gt.prototype.array=Gt.prototype.digest,Gt.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 N_=(...t)=>new Gt(!1,!0).update(t.join("")).hex();var PO={};ge(PO,{sha256:()=>N_});var MO={};ge(MO,{BaseCache:()=>M_,InMemoryCache:()=>L_,defaultHashKeyEncoder:()=>P_,deserializeStoredGeneration:()=>LO,serializeGeneration:()=>jO});const P_=(...t)=>N_(t.join("_"));function LO(t){return t.message!==void 0?{text:t.text,message:Qi(t.message)}:{text:t.text}}function jO(t){const e={text:t.text};return t.message!==void 0&&(e.message=t.message.toDict()),e}var M_=class{keyEncoder=P_;makeDefaultKeyEncoder(t){this.keyEncoder=t}};const DO=new Map;var L_=class my extends M_{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 my(DO)}},Is={},j_;function zO(){if(j_)return Is;j_=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 FO=zO(),UO=Ms(FO),BO=Object.defineProperty,ZO=(t,e,n)=>e in t?BO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,qO=(t,e,n)=>(ZO(t,e+"",n),n);function VO(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 HO(t,e){return t.length===1?[e.get(t.join(","))]:VO(t,e).map(n=>e.get(t.slice(n.start,n.end).join(","))).filter(n=>n!=null)}function GO(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=UO.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(...HO(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)}},D_=pl;qO(D_,"specialTokenRegex",t=>new RegExp(t.map(e=>GO(e)).join("|"),"g"));function WO(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 JO={};ge(JO,{encodingForModel:()=>ml,getEncoding:()=>z_});const xi={},KO=new Xr({});async function z_(t){return t in xi||(xi[t]=KO.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new D_(e)).catch(e=>{throw delete xi[t],e})),await xi[t]}async function ml(t){return z_(WO(t))}var XO={};ge(XO,{BaseLangChain:()=>gl,BaseLanguageModel:()=>_l,calculateMaxTokens:()=>e$,getEmbeddingContextSize:()=>YO,getModelContextSize:()=>F_,getModelNameForTiktoken:()=>Ii,isOpenAITool:()=>QO});const Ii=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,YO=t=>{switch(t){case"text-embedding-ada-002":return 8191;default:return 2046}},F_=t=>{switch(Ii(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 QO(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 e$=async({prompt:t,modelName:e})=>{let n;try{n=(await ml(Ii(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 F_(e)-n},t$=()=>!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??t$(),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=L_.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?Ii(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 C_(t):Array.isArray(t)?new R_(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{}}},Ai=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=An(r,a)}catch{r=void 0,s=!1}this.func&&r!==void 0&&await this.func(r,n)}static assign(t){return new hu(new br({steps:t}))}};const n$=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 r$={};ge(r$,{BaseChatModel:()=>U_,SimpleChatModel:()=>s$});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];(ji(a)||Di(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 U_=class nr extends _l{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(e){super(e),this.outputVersion=n$(()=>{const n=e.outputVersion??st("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=nr._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===nr.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(e,n);else{const s=nr._convertInputToPromptValue(e).toChatMessages(),[a,i]=this._separateRunnableConfigFromCallOptionsCompat(n),o={...a.metadata,...this.getLsParams(i)},c=await dt.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,Ki(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 dt.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(ao)&&!this.disableStreaming&&a.length===1&&this._streamResponseChunks!==nr.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=An(h,m),Ki(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 dt.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=nr._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&&bn(A.message)&&Ji(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=nr._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=qc(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;hr(r)?u=[{type:"function",function:{name:c,description:a,parameters:yr(r)}}]:("name"in r&&(c=r.name),u=[{type:"function",function:{name:c,description:a,parameters:r}}]);const l=this.bindTools(u),d=Mn.from(m=>{if(!Fn.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=Ai.assign({parsed:(m,y)=>d.invoke(m.raw,y)}),h=Ai.assign({parsed:()=>null}),p=f.withFallbacks({fallbacks:[h]});return Na.from([{raw:l},p]).withConfig({runName:"StructuredOutputRunnable"})}},s$=class extends U_{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}]}}},a$=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)}},i$=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])=>[qt(s),qt(a)]),r=qt(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 bt(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=An(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=An(s,o)}catch{s=void 0,a=!1}}}catch(o){throw await r?.handleChainError(o),o}await r?.handleChainEnd(s??{})}},o$=class extends wr{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(t){let e=Mn.from((a,i)=>this._enterHistory(a,i??{})).withConfig({runName:"loadHistory"});const n=t.historyMessagesKey??t.inputMessagesKey;n&&(e=Ai.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)&&!bn(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(bn(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)&&!bn(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(bn(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}},c$={};ge(c$,{RouterRunnable:()=>a$,Runnable:()=>Pe,RunnableAssign:()=>hu,RunnableBinding:()=>wr,RunnableBranch:()=>i$,RunnableEach:()=>DI,RunnableLambda:()=>Mn,RunnableMap:()=>br,RunnableParallel:()=>UI,RunnablePassthrough:()=>Ai,RunnablePick:()=>Yp,RunnableRetry:()=>du,RunnableSequence:()=>Na,RunnableToolLike:()=>fu,RunnableWithFallbacks:()=>Xp,RunnableWithMessageHistory:()=>o$,_coerceToRunnable:()=>qt,ensureConfig:()=>we,getCallbackManagerForConfig:()=>bt,mergeConfigs:()=>la,patchConfig:()=>Ae,pickRunnableConfigKeys:()=>un,raceWithSignal:()=>ln});var B_=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"})}},ki=class extends B_{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")}},_n=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 ki{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"})}},Oi=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(Zi(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");s=new $c({message:r,text:r.content})}else if(bn(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");s=new $c({message:Vs(r),text:r.content})}else s=new dr({text:r});n===void 0?n=s:n=n.concat(s);const a=await this.parsePartialResult([n]);a!=null&&!Wn(a,e)&&(this.diff?yield this._diff(e,a):yield a,e=a)}}getFormatInstructions(){return""}},u$=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]}},l$=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 _n(`Could not parse output: ${t}`,t)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},d$=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 _n(`Incorrect number of items. Expected ${this.length}, got ${e.length}.`);return e}catch(e){throw Object.getPrototypeOf(e)===_n.prototype?e:new _n(`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\\`)`}},h$=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])}},f$=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])}},p$=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),"")}},Z_=class extends ki{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(yr(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 _n(`Failed to parse. Text: "${t}". Error: ${e}`,t)}}},q_=class extends Z_{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(yr(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)}},m$=class extends ki{structuredInputParser;constructor({inputSchema:t}){super(...arguments),this.structuredInputParser=new q_(t)}async parse(t){let e;try{e=await this.structuredInputParser.parse(t)}catch(n){throw new _n(`Failed to parse. Text: "${t}". Error: ${n}`,t)}return this.outputProcessor(e)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}},g$={};ge(g$,{applyPatch:()=>lr,compare:()=>Ac});var _$=class extends Oi{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?Ac(t,e):[{op:"replace",path:"",value:e}]}async parsePartialResult(t){return Hi(t[0].text)}async parse(t){return Hi(t,JSON.parse)}getFormatInstructions(){return""}_baseMessageToString(t){return t.text}};const y$=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":Y(_,"oncdata",_.cdata),_.cdata="";break;case"script":Y(_,"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!==""&&(Y(_,"oncdata",_.cdata),_.cdata=""),_.script!==""&&(Y(_,"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 Y(_,g,k){_.textNode&&Be(_),ue(_,g,k)}function Be(_){_.textNode=Ot(_.opt,_.textNode),_.textNode&&ue(_,"ontext",_.textNode),_.textNode=""}function Ot(_,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,Y(_,"onopentagstart",k)}function Q(_,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=Q(_.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,Y(_,"onattribute",{name:_.attribName,value:_.attribValue});_.attribName=_.attribValue=""}function ne(_,g){if(_.opt.xmlns){var k=_.tag,S=Q(_.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(tr){Y(_,"onopennamespace",{prefix:tr,uri:k.ns[tr]})});for(var Ie=0,Oe=_.attribList.length;Ie<Oe;Ie++){var Ze=_.attribList[Ie],nt=Ze[0],Wt=Ze[1],je=Q(nt,!0),Rt=je.prefix,$r=je.local,Ci=Rt===""?"":k.ns[Rt]||"",z={name:nt,value:Wt,prefix:Rt,local:$r,uri:Ci};Rt&&Rt!=="xmlns"&&!Ci&&(P(_,"Unbound namespace prefix: "+JSON.stringify(Rt)),z.uri=Rt),_.tag.attributes[nt]=z,Y(_,"onattribute",z)}_.attribList.length=0}_.tag.isSelfClosing=!!g,_.sawRoot=!0,_.tags.push(_.tag),Y(_,"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}Y(_,"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,Y(_,"onclosetag",_.tagName);var Ze={};for(var nt in Oe.ns)Ze[nt]=Oe.ns[nt];var Wt=_.tags[_.tags.length-1]||_;_.opt.xmlns&&Oe.ns!==Wt.ns&&Object.keys(Oe.ns).forEach(function(je){var Rt=Oe.ns[je];Y(_,"onclosenamespace",{prefix:je,uri:Rt})})}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?(Y(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===">"?(Y(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,Y(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=Ot(g.opt,g.comment),g.comment&&Y(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&&Y(g,"oncdata",g.cdata),Y(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===">"?(Y(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="",Y(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 Wt="";++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)&&(Wt+=_.apply(null,ye),ye.length=0)}return Wt};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 w$=class extends Oi{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?Ac(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 b$=t=>t.split(`\n`).map(e=>e.replace(/^\\s+/,"")).join(`\n`).trim(),V_=t=>{if(Object.keys(t).length===0)return{};const e={};return t.children.length>0?(e[t.name]=t.children.map(V_),e):(e[t.name]=t.text??void 0,e)};function vl(t){const e=b$(t),n=y$.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]),V_(r)}var v$={};ge(v$,{AsymmetricStructuredOutputParser:()=>m$,BaseCumulativeTransformOutputParser:()=>Oi,BaseLLMOutputParser:()=>B_,BaseOutputParser:()=>ki,BaseTransformOutputParser:()=>As,BytesOutputParser:()=>u$,CommaSeparatedListOutputParser:()=>l$,CustomListOutputParser:()=>d$,JsonMarkdownStructuredOutputParser:()=>q_,JsonOutputParser:()=>_$,ListOutputParser:()=>ks,MarkdownListOutputParser:()=>f$,NumberedListOutputParser:()=>h$,OutputParserException:()=>_n,StringOutputParser:()=>p$,StructuredOutputParser:()=>Z_,XMLOutputParser:()=>w$,XML_FORMAT_INSTRUCTIONS:()=>bl,parseJsonMarkdown:()=>Hi,parsePartialJson:()=>zs,parseXMLMarkdown:()=>vl});function H_(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 _n([`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 E$(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 S$(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var G_=class extends Oi{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(Ji(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=>H_(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}},T$=class extends G_{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 _n(`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}},x$={};ge(x$,{JsonOutputKeyToolsParser:()=>T$,JsonOutputToolsParser:()=>G_,convertLangChainToolCallToOpenAI:()=>E$,makeInvalidToolCall:()=>S$,parseToolCall:()=>H_});var I$={};ge(I$,{BaseLLM:()=>W_,LLM:()=>A$});var W_=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 dt.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 dr({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 dt.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(ao);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=An(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 dt.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"}},A$=class extends W_{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}])))}}},k$={};ge(k$,{chunkArray:()=>J_});const J_=(t,e)=>t.reduce((n,r,s)=>{const a=Math.floor(s/e),i=n[a]||[];return n[a]=i.concat([r]),n},[]);var O$={};ge(O$,{Embeddings:()=>K_});var K_=class{caller;constructor(t){this.caller=new Xr(t??{})}},$$=class extends K_{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??st("OPENAI_API_KEY");this.organization=e?.configuration?.organization??st("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=J_(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=g_(n),s={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};s.baseURL||delete s.baseURL,s.defaultHeaders=y_(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 u_(n)}})}},C$=class extends $${azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;constructor(t){super(t),this.batchSize=t?.batchSize??1,this.azureOpenAIApiKey=t?.azureOpenAIApiKey??(typeof t?.apiKey=="string"?t?.apiKey:void 0)??st("AZURE_OPENAI_API_KEY"),this.azureOpenAIApiVersion=t?.azureOpenAIApiVersion??t?.openAIApiVersion??st("AZURE_OPENAI_API_VERSION"),this.azureOpenAIBasePath=t?.azureOpenAIBasePath??st("AZURE_OPENAI_BASE_PATH"),this.azureOpenAIApiInstanceName=t?.azureOpenAIApiInstanceName??st("AZURE_OPENAI_API_INSTANCE_NAME"),this.azureOpenAIApiDeploymentName=(t?.azureOpenAIApiEmbeddingsDeploymentName||t?.azureOpenAIApiDeploymentName)??(st("AZURE_OPENAI_API_EMBEDDINGS_DEPLOYMENT_NAME")||st("AZURE_OPENAI_API_DEPLOYMENT_NAME")),this.azureADTokenProvider=t?.azureADTokenProvider}async embeddingWithRetry(t){if(!this.client){const n={azureOpenAIApiDeploymentName:this.azureOpenAIApiDeploymentName,azureOpenAIApiInstanceName:this.azureOpenAIApiInstanceName,azureOpenAIApiKey:this.azureOpenAIApiKey,azureOpenAIBasePath:this.azureOpenAIBasePath,azureADTokenProvider:this.azureADTokenProvider,baseURL:this.clientConfig.baseURL},r=g_(n),{apiKey:s,...a}=this.clientConfig,i={...a,baseURL:r,timeout:this.timeout,maxRetries:0};this.azureADTokenProvider||(i.apiKey=n.azureOpenAIApiKey),i.baseURL||delete i.baseURL,i.defaultHeaders=y_(i.defaultHeaders,!0,"2.0.0"),this.client=new ck({apiVersion:this.azureOpenAIApiVersion,azureADTokenProvider:this.azureADTokenProvider,deployment:this.azureOpenAIApiDeploymentName,...i})}const e={};return this.azureOpenAIApiKey&&(e.headers={"api-key":this.azureOpenAIApiKey,...e.headers},e.query={"api-version":this.azureOpenAIApiVersion,...e.query}),this.caller.call(async()=>{try{return await this.client.embeddings.create(t,e)}catch(n){throw u_(n)}})}},R$={};ge(R$,{BaseToolkit:()=>N$,DynamicStructuredTool:()=>Q_,DynamicTool:()=>Y_,StructuredTool:()=>El,Tool:()=>X_,ToolInputParsingException:()=>js,isLangChainTool:()=>ll,isRunnableToolLike:()=>cl,isStructuredTool:()=>ol,isStructuredToolParams:()=>ul,tool:()=>P$});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(hr(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${dE(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 dt.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&&Ry(a)&&(d=a.toolCall.id);const f=M$({content:u,artifact:l,toolCallId:d,name:this.name,metadata:this.metadata});return await o?.handleToolEnd(f),f}},X_=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)}},Y_=class extends X_{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)}},Q_=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)}},N$=class{getTools(){return this.tools}};function P$(t,e){const n=Vc(e.schema),r=os(e.schema);if(!e.schema||n||r)return new Y_({...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()});Dt.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 Q_({...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()});Dt.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 M$(t){const{content:e,artifact:n,toolCallId:r,metadata:s}=t;return r&&!qi(e)?typeof e=="string"||Array.isArray(e)&&e.every(a=>typeof a=="object")?new vn({status:"success",content:e,artifact:n,tool_call_id:r,name:t.name,metadata:s}):new vn({status:"success",content:L$(e),artifact:n,tool_call_id:r,name:t.name,metadata:s}):e}function L$(t){try{return JSON.stringify(t)??""}catch{return`${t}`}}const j$=ot({type:kt("screenshot")}),D$=ot({type:kt("click"),x:it(),y:it(),button:fl(["left","right","wheel","back","forward"]).default("left")}),z$=ot({type:kt("double_click"),x:it(),y:it(),button:fl(["left","right","wheel","back","forward"]).default("left")}),F$=ot({type:kt("drag"),path:xs(ot({x:it(),y:it()}))}),U$=ot({type:kt("keypress"),keys:xs(At())}),B$=ot({type:kt("move"),x:it(),y:it()}),Z$=ot({type:kt("scroll"),x:it(),y:it(),scroll_x:it(),scroll_y:it()}),q$=ot({type:kt("type"),text:At()}),V$=ot({type:kt("wait"),duration:it().optional()}),H$=dl("type",[j$,D$,z$,F$,U$,B$,Z$,q$,V$]);ot({action:H$});const G$=ot({type:kt("exec"),command:xs(At()),env:hO(At(),At()).optional(),working_directory:At().optional(),timeout_ms:it().optional(),user:At().optional()});dl("type",[G$]),ot({commands:xs(At()).describe("Array of shell commands to execute"),timeout_ms:it().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:it().optional().describe("Optional maximum number of characters to return from each command")});const W$=ot({type:kt("create_file"),path:At(),diff:At()}),J$=ot({type:kt("update_file"),path:At(),diff:At()}),K$=ot({type:kt("delete_file"),path:At()});dl("type",[W$,J$,K$]);const X$={"gpt-4.1":{deploymentName:"gpt-4.1",apiVersion:"2024-10-21",pathSegment:"models/gpt-4.1/openai/deployments/gpt-4.1/chat/completions"},"gpt-4.1-mini":{deploymentName:"gpt-4.1-mini",apiVersion:"2024-10-21",pathSegment:"models/gpt-4.1-mini/openai/deployments/gpt-4.1-mini/chat/completions"},"text-embedding-ada-002":{deploymentName:"text-embedding-ada-002",apiVersion:"2024-10-21",pathSegment:"models/text-embedding-ada-002/openai/deployments/text-embedding-ada-002/embeddings"}},Y$={default:"text-embedding-ada-002"},Q$=["x-stainless-package-version","x-stainless-timeout","x-stainless-retry-count","x-stainless-lang","x-stainless-os","x-stainless-arch","x-stainless-runtime","x-stainless-runtime-version","x-stainless-helper-method","api-key"],eC=t=>async(e,n)=>{const r=new Headers(n?.headers);return Q$.forEach(s=>r.delete(s)),t&&t.length>0&&r.set("X-Esri-Authorization",`Bearer ${t}`),await fetch(e,{...n,headers:r})};let Or,er;const $i=new Map,tC=12,nC=10,rC=async t=>{if(!Or)return;er?er.memoryVectors=[]:er=new gu(Or);const e=[];for(const[n,{layerItem:r}]of t.entries()){const s=`Name: ${r.name}\nTitle: ${r.title}\nDescription: ${r.description}`,a=new Dn({id:n,pageContent:s,metadata:{layerId:n}});e.push(a)}await er.addDocuments(e),console.log("Layer Vectorstore contents:",er.memoryVectors)},sC=async t=>{if(!Or)return;$i.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 Dn({id:c,pageContent:l,metadata:{layerId:n}})),a.push(l)}const i=new gu(Or),o=(async()=>{const c=await Or.embedDocuments(a);await i.addVectors(c,s),$i.set(n,i)})();e.push(o)}await Promise.all(e),console.log("Field Vectorstore contents:",Array.from($i.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=Y$.default,c=X$[o];Or=new C$({azureOpenAIApiKey:"x",azureOpenAIBasePath:a.apiUrl,azureOpenAIApiDeploymentName:c.deploymentName,azureOpenAIApiVersion:c.apiVersion,model:o,batchSize:2048,maxConcurrency:10,configuration:{fetch:eC(a.token)}}),n&&(await rC(n),await sC(n)),globalThis.postMessage("completed");break}case"layerSearch":{if(er){const o=await er.similaritySearchVectorWithScore(i,nC);globalThis.postMessage({requestId:s,results:o})}break}case"fieldSearch":{if(r.length>0){const o=r.map(async l=>{const d=$i.get(l);if(!d)return null;const f=await d.similaritySearchVectorWithScore(i,tC);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};